Object reference not set to an instance of an object

Hi All,

After I created a MS SQL Server database I created a new Application. After that I generated the application from the Data and after that I created the security pages. Then I started with the run commabd and switched to the browser application. When I logged in with admin/admin it worked. But when opening forms generated from the database, it gives the message "unable to load .... ".
When I look in the log there is the message "Object reference not set to an instance of an object".

Anybody any idea ? What is it missing, Am I doing wrong ?

The database is a MS SQL Server 2019 version.
My version of Radzen is 2.56.12
I created a Angular version

If the log is needed, it's here:
dotnet: info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 OPTIONS http://localhost:5000/auth/login

dotnet: info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
CORS policy execution successful.

dotnet: info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 12.5546ms 204

dotnet: info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST http://localhost:5000/auth/login application/json 39

dotnet: info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
CORS policy execution successful.

dotnet: info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Login", controller = "Auth"}. Executing controller action with signature System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] Login(Newtonsoft.Json.Linq.JObject) on controller VpIvcr.Controllers.AuthController (server).

dotnet: info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 3.1.4 initialized 'ApplicationIdentityDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (17ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT 1

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (19ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]');

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT 1

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]');

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [MigrationId], [ProductVersion]
FROM [__EFMigrationsHistory]
ORDER BY [MigrationId];

dotnet: info: Microsoft.EntityFrameworkCore.Migrations[20405]
No migrations were applied. The database is already up to date.

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [a].[Id], [a].[ConcurrencyStamp], [a].[Name], [a].[NormalizedName]
FROM [AspNetRoles] AS [a]

dotnet: info: Microsoft.AspNetCore.Mvc.NewtonsoftJson.NewtonsoftJsonResultExecutor[1]
Executing JsonResult, writing value of type '<>f__AnonymousType2`2[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Double, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]'.

dotnet: info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action VpIvcr.Controllers.AuthController.Login (server) in 1194.8775ms

dotnet: info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 1316.8451ms 200 application/json; charset=utf-8

dotnet: info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 OPTIONS http://localhost:5000/odata/VPIv2t2d/GenDashboards?$top=20&$skip=0&$count=true

dotnet: info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
CORS policy execution successful.

dotnet: info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 1.921ms 204

dotnet: info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/odata/VPIv2t2d/GenDashboards?$top=20&$skip=0&$count=true
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
CORS policy execution successful.

dotnet: info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "GetGenDashboards", controller = "GenDashboards"}. Executing controller action with signature System.Collections.Generic.IEnumerable`1[VpIvcr.Models.VpIv2T2D.GenDashboard] GetGenDashboards() on controller VpIvcr.Controllers.VpIv2T2D.GenDashboardsController (server).

dotnet: info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[2]
Successfully validated the token.

dotnet: info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
Authorization was successful.

dotnet: info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 3.1.4 initialized 'ApplicationIdentityDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None

dotnet: info
dotnet: : Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT 1

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]');

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT 1

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]');

dotnet: info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [MigrationId], [ProductVersion]
FROM [__EFMigrationsHistory]
ORDER BY [MigrationId];

dotnet: info: Microsoft.EntityFrameworkCore.Migrations[20405]
No migrations were applied. The database is already up to date.

dotnet: info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action VpIvcr.Controllers.VpIv2T2D.GenDashboardsController.GetGenDashboards (server) in 180.7904ms

dotnet: fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.)
---> System.NullReferenceException: Object reference not set to an instance of an object.
at VpIvcr.Controllers.AuthController.AddTokenToHeader(HttpContext context) in D:\RadzenProjecten\VPIvcr\server\Controllers\AuthController.cs:line 100
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at VpIvcr.Controllers.VpIv2T2D.GenDashboardsController.GetGenDashboards() in D:\RadzenProjecten\VPIvcr\server\Controllers\VPIv2t2d\GenDashboardsController.cs:line 39
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

dotnet: info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 341.3499ms 500 text/plain

With regards
Henk Spierings

Hi @SPIeR-IT,

Can you post more info about the code around this line?

Hi Enchev,

Is it that you mean that you want the sourcecode of this module ?
Line 39 is
AuthController.AddTokenToHeader(this.HttpContext).Wait();

It's below:
using System;
using System.Net;
using System.Data;
using System.Linq;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.AspNet.OData.Query;

namespace VpIvcr.Controllers.VpIv2T2D
{
using Models;
using Data;
using Models.VpIv2T2D;

[ODataRoutePrefix("odata/VPIv2t2d/GenDashboards")]
[Route("mvc/odata/VPIv2t2d/GenDashboards")]
public partial class GenDashboardsController : ODataController
{
private Data.VpIv2T2DContext context;

public GenDashboardsController(Data.VpIv2T2DContext context)
{
  this.context = context;
}
// GET /odata/VpIv2T2D/GenDashboards
[Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes="Bearer")]
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
[HttpGet]
public IEnumerable<Models.VpIv2T2D.GenDashboard> GetGenDashboards()
{
   AuthController.AddTokenToHeader(this.HttpContext).Wait();

  var items = this.context.GenDashboards.AsQueryable<Models.VpIv2T2D.GenDashboard>();
  this.OnGenDashboardsRead(ref items);

  return items;
}

partial void OnGenDashboardsRead(ref IQueryable<Models.VpIv2T2D.GenDashboard> items);

[Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes="Bearer")]
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
[HttpGet("{Dsh_ID}")]
public SingleResult<GenDashboard> GetGenDashboard(string key)
{
    AuthController.AddTokenToHeader(this.HttpContext).Wait();

    var items = this.context.GenDashboards.Where(i=>i.Dsh_ID == key);
    this.OnGenDashboardsGet(ref items);

    return SingleResult.Create(items);
}

partial void OnGenDashboardsGet(ref IQueryable<Models.VpIv2T2D.GenDashboard> items);

partial void OnGenDashboardDeleted(Models.VpIv2T2D.GenDashboard item);

[Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes="Bearer")]
[HttpDelete("{Dsh_ID}")]
public IActionResult DeleteGenDashboard(string key)
{
    AuthController.AddTokenToHeader(this.HttpContext).Wait();

    try
    {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }


        var items = this.context.GenDashboards
            .Where(i => i.Dsh_ID == key)
            .AsQueryable();

        items = EntityPatch.ApplyTo<Models.VpIv2T2D.GenDashboard>(Request, items);

        var itemToDelete = items.FirstOrDefault();

        if (itemToDelete == null)
        {
            return StatusCode((int)HttpStatusCode.PreconditionFailed);
        }

        this.OnGenDashboardDeleted(itemToDelete);
        this.context.GenDashboards.Remove(itemToDelete);
        this.context.SaveChanges();

        return new NoContentResult();
    }
    catch(Exception ex)
    {
        ModelState.AddModelError("", ex.Message);
        return BadRequest(ModelState);
    }
}

partial void OnGenDashboardUpdated(Models.VpIv2T2D.GenDashboard item);

[Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes="Bearer")]
[HttpPut("{Dsh_ID}")]
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
public IActionResult PutGenDashboard(string key, [FromBody]Models.VpIv2T2D.GenDashboard newItem)
{
    AuthController.AddTokenToHeader(this.HttpContext).Wait();

    try
    {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var items = this.context.GenDashboards
            .Where(i => i.Dsh_ID == key)
            .AsQueryable();

        items = EntityPatch.ApplyTo<Models.VpIv2T2D.GenDashboard>(Request, items);

        var itemToUpdate = items.FirstOrDefault();

        if (itemToUpdate == null)
        {
            return StatusCode((int)HttpStatusCode.PreconditionFailed);
        }

        this.OnGenDashboardUpdated(newItem);
        this.context.GenDashboards.Update(newItem);
        this.context.SaveChanges();

        var itemToReturn = this.context.GenDashboards.Where(i => i.Dsh_ID == key);
        return new ObjectResult(SingleResult.Create(itemToReturn));
    }
    catch(Exception ex)
    {
        ModelState.AddModelError("", ex.Message);
        return BadRequest(ModelState);
    }
}

[Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes="Bearer")]
[HttpPatch("{Dsh_ID}")]
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
public IActionResult PatchGenDashboard(string key, [FromBody]Delta<Models.VpIv2T2D.GenDashboard> patch)
{
    AuthController.AddTokenToHeader(this.HttpContext).Wait();

    try
    {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var items = this.context.GenDashboards.Where(i => i.Dsh_ID == key);

        items = EntityPatch.ApplyTo<Models.VpIv2T2D.GenDashboard>(Request, items);

        var itemToUpdate = items.FirstOrDefault();

        if (itemToUpdate == null)
        {
            return StatusCode((int)HttpStatusCode.PreconditionFailed);
        }

        patch.Patch(itemToUpdate);

        this.OnGenDashboardUpdated(itemToUpdate);
        this.context.GenDashboards.Update(itemToUpdate);
        this.context.SaveChanges();

        var itemToReturn = this.context.GenDashboards.Where(i => i.Dsh_ID == key);
        return new ObjectResult(SingleResult.Create(itemToReturn));
    }
    catch(Exception ex)
    {
        ModelState.AddModelError("", ex.Message);
        return BadRequest(ModelState);
    }
}

partial void OnGenDashboardCreated(Models.VpIv2T2D.GenDashboard item);

[Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes="Bearer")]
[HttpPost]
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
public IActionResult Post([FromBody] Models.VpIv2T2D.GenDashboard item)
{
    AuthController.AddTokenToHeader(this.HttpContext).Wait();

    try
    {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (item == null)
        {
            return BadRequest();
        }

        this.OnGenDashboardCreated(item);
        this.context.GenDashboards.Add(item);
        this.context.SaveChanges();

        return Created($"odata/VpIv2T2D/GenDashboards/{item.Dsh_ID}", item);
    }
    catch(Exception ex)
    {
        ModelState.AddModelError("", ex.Message);
        return BadRequest(ModelState);
    }
}

}
}

BTW Thanks for your quick response.

Greets
Henk

Thanks Henk! This is definitely a bug related to session refresh feature and admin/admin login. Please turn off session refresh from security settings temporary - tomorrow we will release a fix.

Hi @SPIeR-IT,

Radzen update was just released with fix for this error included!