Entity Framework 6.4 throwing NullReferenceException with Azure Functions V3 - entity-framework-6

I'm using Azure Functions V3 (.Net Core 3.1) and trying to call an Entity FrameWork class built using EF 6.4 (.Net 7.2) and Entity Framework is throwing a NullReferenceException. The same call succeeds while using .Net Core console app instead of Azure Function. Appreciate your help here.
Here is my function definition:
namespace FunctionAppV32
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
var cstr = ConnectionString2.BuildConnectionString();
FlighterSIEntities entities = new FlighterSIEntities(cstr);
foreach (var x in entities.TGBotComplexVectorParamSettings)
{ .... }
}
}
}
The exception is thrown while accessing entities.TGBotComplexVectorParamSettings in for loop.
Exception Stack Trace:
System.NullReferenceException HResult=0x80004003 Message=Object reference not set to an instance of an object. Source=EntityFramework StackTrace:
at System.Data.Entity.Core.EntityClient.EntityConnection.GetStoreConnection(DbProviderFactory factory)
at System.Data.Entity.Core.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.Entity.Core.EntityClient.EntityConnection..ctor(String connectionString) at System.Data.Entity.Internal.LazyInternalConnection.Initialize() at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel() at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.InternalContext.Initialize() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable.GetEnumerator()
at FunctionAppV32.Function1.Run(TimerInfo myTimer, ILogger log) in D:\src\RnR-ExperimentationTools\src\TGBot\FunctionAppV32\Function1.cs:line 20
at Microsoft.Azure.WebJobs.Host.Executors.VoidMethodInvoker2.InvokeAsync(TReflected instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\VoidMethodInvoker.cs:line 20 at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.d__10.MoveNext() in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs:line 52

I was able to resolve exactly same issue with updating below packages to mentioned versions. Hope it helps to you or anyone facing the same issue.
EntityFramework to Version=6.4.4
Microsoft.EntityFrameworkCore to Version=3.1.6
Microsoft.Extensions.Configuration to Version=3.1.6
Kindly check.

Related

Microsoft.AspNet.Identity.EntityFramework.UserStore does not have a constructor that takes the parameters

I being a newbie working on app with MVC5 and EF 6. I am using dependency injection to resolve my classes. Everything was ok untill I changed the connection string and changed something(i dont know) in my dependency registering class that is unity config.
Now whenever i run it, it gives me this error. Microsoft.AspNet.Identity.EntityFramework.UserStore does not have a constructor that takes the parameters. I am using Unity nuget package manager
below is my code, any help would be appreciated
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Oxford.Core.Data;
using Oxford.Data;
using Oxford.Services;
using OxfordLibrary.Models;
using System.Web.Mvc;
using Unity;
using Unity.Injection;
namespace OxfordLibrary.App_Start
{
public class UnityConfig
{
public static void RegisterComponents()
{
// Repository
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType(typeof(IRepository<>), typeof(EfRepository<>));
container.RegisterType<ApplicationUserManager>();
// Services
container.RegisterType<IMasterService, MasterService>();
// Resolve
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
new InjectionConstructor(typeof(ApplicationDbContext)));
}
}
}
OxfordLibrary is name of my project
Exception I am getting is :
System.InvalidOperationException
HResult=0x80131509
Message=The type Microsoft.AspNet.Identity.EntityFramework.UserStore`1[[OxfordLibrary.Models.ApplicationUser, OxfordLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] does not have a constructor that takes the parameters (ApplicationDbContext).
Source=Unity.Abstractions
StackTrace:
at Unity.Injection.InjectionConstructor.ConstructorByType(Type typeToCreate, Type[] types)
at Unity.Injection.InjectionConstructor.AddPolicies(Type serviceType, Type implementationType, String name, IPolicyList policies)
at Unity.UnityContainer.RegisterType(Type typeFrom, Type typeTo, String name, LifetimeManager lifetimeManager, InjectionMember[] injectionMembers)
at Unity.UnityContainerExtensions.RegisterType[TFrom,TTo](IUnityContainer container, InjectionMember[] injectionMembers)
at OxfordLibrary.App_Start.UnityConfig.RegisterComponents() in D:\Programs\2018\OxfordLibrary\OxfordLibrary\App_Start\UnityConfig.cs:line 35
at OxfordLibrary.MvcApplication.Application_Start() in D:\Programs\2018\OxfordLibrary\OxfordLibrary\Global.asax.cs:line 20

Proxem Stanford Parser asp MVC

I'm using Proxem wrapper for Stanford Parser and I'm facing problem with Parsing in ASP.NET MVC 3 and 4 application. It throws
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Proxem.Antelope.Parsing.Sentence.a(List`1 A_0)
at Proxem.Antelope.Parsing.Sentence..ctor(SerializationInfo info, StreamingContext ctxt)
--- End of inner exception stack trace ---
In WPF and console application it works fine.
I fixed it. Constructor Parser(string path) is invoking constructor Parser(string path, int poolsize) with poolsize value = 1. Using constructor Parser(string path, int poolsize) with values -> Parser(yourPath, 0) make it work with MVC and WCF.

Basic web application using Saxon API and IKVM throws exception

I created a basic .NET 4.0 application and referenced the Saxon assemblies. Here is the list of dll's I referenced in the project.
saxon9.dll
saxon9api.dll
IKVM.OpenJDK.ClassLibrary.dll
IKVM.Runtime.dll
The code for the application is as follows:
Sub Main()
Console.WriteLine("Trying to instantiate SaxonProcessor...")
Try
Dim SaxonProcessor As Saxon.Api.Processor = New Saxon.Api.Processor()
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message & ex.StackTrace)
Console.Read()
End Try
Console.WriteLine("Saxon instantiated successfully!")
Console.Read()
End Sub
When I run this application on our IIS machine, I get the following output:
Trying to instantiate SaxonProcessor...
Saxon instantiated successfully!
I then created a basic web application project and referenced the same files as the windows application. I deployed the web application to a virtual directory that contains all the referenced assemblies. I put the following code inside my Default.aspx page:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write("Trying to instantiate SaxonProcessor...")
Try
Dim SaxonProcessor As Saxon.Api.Processor = New Saxon.Api.Processor()
Response.Write("Saxon instantiated successfully!")
Catch ex As Exception
Response.Write("Error: " & ex.Message & ex.StackTrace)
End Try
End Sub
End Class
When I load the page, it gives me this exception:
Trying to instantiate SaxonProcessor...Error: The type initializer for 'IKVM.NativeCode.java.lang.Thread' threw an exception. at IKVM.NativeCode.java.lang.Class.forName0(String name, Boolean initialize, Object loader) at java.lang.Class.forName0(String , Boolean , ClassLoader ) at java.lang.Class.forName(String className) at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory.class$(String x0) at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory..ctor(Configuration config) at net.sf.saxon.dotnet.DotNetPlatform.initialize(Configuration config) at net.sf.saxon.Configuration.init() at net.sf.saxon.Configuration..ctor() at Saxon.Api.Processor..ctor() at BealSaxxon._Default.Page_Load(Object sender, EventArgs e) in C:\Users\u0147101\Desktop\BealSaxxon\BealSaxxon\Default.aspx.vb:line 9
FULL STACKTRACE FROM IIS MACHINE:
System.TypeInitializationException: The type initializer for 'IKVM.NativeCode.java.lang.Thread' threw an exception. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'java.io.BufferedInputStream' threw an exception. ---> java.lang.RuntimeException: java.lang.IllegalAccessException: Class java.util.concurrent.atomic.AtomicReferenceFieldUpdater can not access a member of class java.io.BufferedInputStream with modifiers "volatile" ---> java.lang.IllegalAccessException: Class java.util.concurrent.atomic.AtomicReferenceFieldUpdater can not access a member of class java.io.BufferedInputStream with modifiers "volatile"
at sun.reflect.misc.ReflectUtil.ensureMemberAccess(Class currentClass, Class memberClass, Object target, Int32 modifiers)
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.AtomicReferenceFieldUpdaterImpl..ctor(Class , Class , String )
--- End of inner exception stack trace ---
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.AtomicReferenceFieldUpdaterImpl..ctor(Class , Class , String )
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater(Class tclass, Class vclass, String fieldName)
at java.io.BufferedInputStream..cctor()
--- End of inner exception stack trace ---
at java.io.BufferedInputStream.__<clinit>()
at java.lang.System.initializeSystemClass()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at IKVM.NativeCode.java.lang.Thread..cctor()
--- End of inner exception stack trace ---
at IKVM.NativeCode.java.lang.Class.forName0(String name, Boolean initialize, Object loader)
at java.lang.Class.forName(String className)
at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory.class$(String x0)
at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory..ctor(Configuration config)
at net.sf.saxon.dotnet.DotNetPlatform.initialize(Configuration config)
at net.sf.saxon.Configuration.init()
at net.sf.saxon.Configuration..ctor()
at Saxon.Api.Processor..ctor()
at EDG.Transforms..ctor()
at EDG.Main..ctor(NameValueCollection applicationSettings, List`1 exceptionList)
at EDG.EGallery..ctor(NameValueCollection ConfigurationSettings, List`1 ExceptionList)
Has anyone seen this exception before? I've searched extensively on Google but nobody seems to have had this specific exception. I'm thinking it's a permissions problem with IIS, but I don't know for sure. The application pool this application is running under is setup with a machine administrator.
I think this can be 2 types of causes.
One of the IKVM dll is missing. Add all dll of IKVM to test if this solve the problem.
IKVM is compiled for .NET 2 and not version 4. You need to add a version mapping to your app.config.
In this situation, it was a product called OpNET that was interfering with apps using the JVM. Once its services and processes were stopped, the Saxon assembly worked fine.

using glimpse and structuremap together

I'm adding structuremap to my project for DI/IOC. I built a demo project to get familiar with it before adding it to my application. After getting it working in the demo I started moving it into my app.
I also use glimpse, and that seems to be the only thing causing problems since the structure map addition (so far).
I followed a pretty basic SM tutorial and the NuGet package, and at this point I'm not even injecting any dependencies yet. Just getting everything wired up.
Here's my application_start
IContainer container = new Container(x =>
{
x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
});
DependencyResolver.SetResolver(new SmDependencyResolver(container));
If I disable glimpse, my application works as it did before. I'd be ready to start doing DI. But if I leave glimpse enabled I get a null object exception. Here's the stack trace, I'm not having much luck following it.
System.NullReferenceException: Object reference not set to an instance of an object.
at Glimpse.Mvc3.Interceptor.ActionInvokerProxyGenerationHook.NonProxyableMemberNotification(Type type, MemberInfo memberInfo)
at Castle.DynamicProxy.Contributors.MembersCollector.AcceptMethod(MethodInfo method, Boolean onlyVirtuals, IProxyGenerationHook hook)
at Castle.DynamicProxy.Contributors.ClassMembersCollector.GetMethodToGenerate(MethodInfo method, IProxyGenerationHook hook, Boolean isStandalone)
at Castle.DynamicProxy.Contributors.MembersCollector.AddMethod(MethodInfo method, IProxyGenerationHook hook, Boolean isStandalone)
at Castle.DynamicProxy.Contributors.MembersCollector.AddProperty(PropertyInfo property, IProxyGenerationHook hook)
at Castle.DynamicProxy.Contributors.MembersCollector.CollectProperties(IProxyGenerationHook hook)
at Castle.DynamicProxy.Contributors.MembersCollector.CollectMembersToProxy(IProxyGenerationHook hook)
at Castle.DynamicProxy.Contributors.ClassProxyTargetContributor.<CollectElementsToProxyInternal>d__2.MoveNext()
at Castle.DynamicProxy.Contributors.CompositeTypeContributor.CollectElementsToProxy(IProxyGenerationHook hook, MetaType model)
at Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateType(String name, Type[] interfaces, INamingScope namingScope)
at Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType(CacheKey cacheKey, Func`3 factory)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Glimpse.Mvc3.Extensions.ControllerExtentions.TrySetActionInvoker(IController iController, IGlimpseLogger logger)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, ref IController controller, ref IControllerFactory factory)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<BeginProcessRequest>b__2()
at System.Web.Mvc.SecurityUtil.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a()
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, ref Boolean completedSynchronously)
Based on your callstack, it looks like you are using an older version of Glimpse.
This bug was fixed in version 0.85 of Glimpse, available now on NuGet and CodePlex. Upgrading should fix your problem.

Entity Framework NullReferenceException calling ToList?

I'm very new to WPF and the EF, and I'm trying to display some data from a table in a datagrid. I've got the entity model pulled from an existing database and simple operations seem to work (getting row counts, using 'first').
I'm running against Firebird 2.5.0 using the 2.0.5 DDEX provider and 2.5.2 ADO NETProvider.
When I try to get the data into the grid or simply into a list, I get a null reference exception.
Possibly I just don't understand how to use the entity framework, but the examples I see on the net make it look really easy.
public partial class Page1 : Page
{
Entities context;
public Page1()
{
context = new Entities();
InitializeComponent();
// This works to get a row into the grid
var arep = context.SALESREPs.First();
var alist = new List<SALESREP>();
alist.Add( arep );
gridUserList.ItemsSource = alist;
// These both fail with null ref exception
var allreps = context.SALESREPs.ToList();
gridUserList.ItemsSource = context.SALESREPs;
}
}
Here's the exception detail:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=System.Data.Entity
StackTrace:
at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
at System.Data.EntityKey.GetHashCode()
at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at System.Data.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& entry)
at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at PSUserMaintenanceWebUI.Page1..ctor() in C:\Documents and Settings\d...\my documents\visual studio 2010\Projects\UserMaintenance\UserMaintenanceWebUI\Page1.xaml.cs:line 36
at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.InvokeDelegate(Action`1 action, Object argument)
at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.CallCtorDelegate(XamlTypeInvoker type)
at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.CreateInstance(XamlTypeInvoker type)
at System.Xaml.Schema.XamlTypeInvoker.CreateInstance(Object[] arguments)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor(XamlType xamlType, Object[] args)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
InnerException:
My table has a multi-field primary key with some of the fields being nullable. The entity framework doesn't like nullable fields in the primary key. I removed those rows and it works fine. I'm already in the process of finding a different solution to the requirement that prompted us to allow nulls in some of the primary key fields.

Resources