Spring.Objects.Factory.ObjectCreationException: System.ArgumentNullException: Key cannot be null - spring.net

This is a long shot...
I'm using spring 1.3.2 and at random times I get ArgumentNullException exception (See stack trace below).
I'm configuring the container in a mix between XML and Code (by using ObjectDefinitionBuilder directly, no code config). And the registrations take place in parallel (5 threads loading definitions).
All my objects use Autowiring via Constructor, the error happens in both components that have items in the constructor or not.
I'm doing the following call after everything was registered in the container
context.GetObjectsOfType(typeof (IFoo)).OfType<DictionaryEntry>().Select(d => (IFoo) d.Value)
From the stack trace and looking at the code, I see that the call to IsAlias seems to be failing, but not sure I understand how this can happen.
Any thoughts/Ideas?
Stack Trace:
Spring.Objects.Factory.ObjectCreationException: Error creating object with name 'My.App.SomeFooImplementation' : Initialization of object failed : Key cannot be null.
Parameter name: key ---> System.ArgumentNullException: Key cannot be null.
Parameter name: key
at System.Collections.Hashtable.ContainsKey(Object key)
at System.Collections.Specialized.OrderedDictionary.Contains(Object key)
at Spring.Objects.Factory.Support.AbstractObjectFactory.IsAlias(String name)
at Spring.Objects.Factory.Support.DefaultListableObjectFactory.DoGetObjectNamesForType(Type type, Boolean includeNonSingletons, Boolean allowEagerInit)
at Spring.Objects.Factory.Support.DefaultListableObjectFactory.GetObjectNamesForType(Type type, Boolean includePrototypes, Boolean includeFactoryObjects)
at Spring.Objects.Factory.ObjectFactoryUtils.ObjectNamesForTypeIncludingAncestors(IListableObjectFactory factory, Type type, Boolean includePrototypes, Boolean includeFactoryObjects)
at Spring.Objects.Factory.Support.DefaultListableObjectFactory.FindAutowireCandidates(String objectName, Type requiredType, DependencyDescriptor descriptor)
at Spring.Objects.Factory.Support.DefaultListableObjectFactory.ResolveDependency(DependencyDescriptor descriptor, String objectName, IList autowiredObjectNames)
at Spring.Objects.Factory.Support.ConstructorResolver.CreateArgumentArray(String objectName, RootObjectDefinition rod, ConstructorArgumentValues resolvedValues, ObjectWrapper wrapper, Type[] paramTypes, MethodBase methodOrCtorInfo, Boolean autowiring, UnsatisfiedDependencyExceptionData& unsatisfiedDependencyExceptionData)
at Spring.Objects.Factory.Support.ConstructorResolver.AutowireConstructor(String objectName, RootObjectDefinition rod, ConstructorInfo[] chosenCtors, Object[] explicitArgs)
at Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.CreateObjectInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments)
at Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure)
--- End of inner exception stack trace ---
at Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure)
at Spring.Objects.Factory.Support.AbstractObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments)
at Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure)
at Spring.Objects.Factory.Support.AbstractObjectFactory.GetObject(String name)
Edit:
I just got all the definition names and somehow there is a null entry in there, that seems to be the issue, not sure why it is happening yet...

The only fix I could come up with was to change the internal objectDefinitionNames ArrayList to be wrapped with ArrayList.Synchronized with reflection. Not nice at all but seems to do the job.
var field = factory.GetType().GetField("objectDefinitionNames", BindingFlags.NonPublic | BindingFlags.Instance);
if (field == null)
throw new InvalidOperationException("Could not get Definitions field from application context.");
var value = (ArrayList) field.GetValue(factory);
field.SetValue(factory, ArrayList.Synchronized(value));

Related

Problem with WHERE in Neo4J, deserialization error

I'm using Neo4JClient in .NET Core web application (I created it in VisualStudio version 2019 template) and I had code that works as expected for my example.
I have 3 types of node: Category(important property name - string), Document(important CreatedBy - represents name of User who created it, other properties are used after WHERE), User(important Username - string). Document can have TAG relationship with Category and User can have INTERESTED_IN relationship with Category.
First I created one query to return Document if it have TAG to Category and if User is INTERESTED_IN this Category (Note: I don't have multiple relationships between nodes). Also number of connections with Category is counted so if I have too many Documents method returns only 10 with most connections.
public async Task<IActionResult> GetNewsFeed(string username)
{
string match = $"(a:User{{Username: '{username}'}})-[:INTERESTED_IN]->(res:Category)<-[:TAG]-(b:Document)";
string where = $"NOT(b.isArchived AND c.isArchived AND b.CreatedBy =~ '{username}')";
string with = "b.name AS name, b.CreatedBy AS creator, b.Pictures AS pictures, b.Paragraphs AS paragraphs, COUNT(res) AS interest1";
var result = _context.Cypher.Match(match)
//.Where(where)
.With(with)
.Return((name, creator, pictures, paragraphs, interest1)=> new SimpleNewsFeedDTO {
Name = name.As<string>()
, Creator = creator.As<string>()
, Pictures = pictures.As<string[]>()
, Paragraphs = paragraphs.As<string[]>()
, Interest = interest1.As<int>() })
.OrderBy("interest1 DESC")
.Limit(10)
.ResultsAsync);
return new JsonResult(await result);
}
When I provide correct Username I can see results in right order, but I also want to filter Documents CreatedBy that User (I want to exclude documents created by user), but when I uncomment Where and send request I get following error:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.ArgumentException: Neo4j returned a valid response, however Neo4jClient was unable to deserialize into the object structure you supplied.
First, try and review the exception below to work out what broke.
If it's not obvious, you can ask for help at http://stackoverflow.com/questions/tagged/neo4jclient
Include the full text of this exception, including this message, the stack trace, and all of the inner exception details.
Include the full type definition of ExtraBlog.DTOs.SimpleNewsFeedDTO.
Include this raw JSON, with any sensitive values replaced with non-sensitive equivalents:
(Parameter 'content')
---> System.ArgumentNullException: Value cannot be null. (Parameter 'input')
at System.Text.RegularExpressions.Regex.Replace(String input, String replacement)
at Neo4jClient.Serialization.CommonDeserializerMethods.ReplaceAllDateInstancesWithNeoDates(String content)
at Neo4jClient.Serialization.CypherJsonDeserializer`1.Deserialize(String content, Boolean isHttp)
--- End of inner exception stack trace ---
at Neo4jClient.Serialization.CypherJsonDeserializer`1.Deserialize(String content, Boolean isHttp)
at Neo4jClient.GraphClient.Neo4jClient.IRawGraphClient.ExecuteGetCypherResultsAsync[TResult](CypherQuery query)
at ExtraBlog.Controllers.UserController.GetNewsFeed(String username) in E:\GithubRepo\NapredneBaze\Neo4JProject\extra-blog\ExtraBlog\Controllers\UsersController.cs:line 39
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
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>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>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>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Also when I run something like this in Neo4J browser I get the same result with or without WHERE:
MATCH (a:User{Username: 'NN'})-[:INTERESTED_IN]->(res:Category)<-[t:TAG]-(b:Document)
WHERE (NOT(b.isArchived AND res.isArchived AND b.CreatedBy =~ 'NN'))
WITH b, COUNT(res) AS interest1
RETURN b.name, interest1
ORDER BY interest1 DESC
LIMIT 10
So my question is: why I can't run my method in Visual Studio, and why this query doesn't return what I was expecting?
With these things, it's always good to check what you are generating from the client. To that end you should look at the query.DebugQueryText property. If you do, you'll see the query you would generate would look like this:
MATCH (a:User{Username: 'NN'})-[:INTERESTED_IN]->(res:Category)<-[:TAG]-(b:Document)
WHERE NOT(b.isArchived AND c.isArchived AND b.CreatedBy =~ 'NN')
WITH b.name AS name, b.CreatedBy AS creator, b.Pictures AS pictures, b.Paragraphs AS paragraphs, COUNT(res) AS interest1
RETURN name AS Name, creator AS Creator, pictures AS Pictures, paragraphs AS Paragraphs, interest1 AS Interest
ORDER BY interest1 DESC
LIMIT 10
If you try to execute that in your browser - it won't work, and that's because you use an alias c to access the isArchived property, but there is no c in your MATCH.

SpecFlow feature file error - Object must implement IConvertible

I am getting below error in SpecFlow (2.1.o) in VS 2107 in one of the steps in feature file. Should it be something related to SpecFlow framework issue?
But I don't have this error in other features. They are working fine.
Error in XXXXfeature.cs file:
Test method ABC.Api.Bdd.Tests.Features.V2.InstantTrackerFeature.InstantTrackerReturnsA500ErrorResponseWhenErrorScenariosOccur threw exception:
System.InvalidCastException: Object must implement IConvertible.
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at TechTalk.SpecFlow.Bindings.StepArgumentTypeConverter.ConvertSimple(Type typeToConvertTo, Object value, CultureInfo cultureInfo)
at TechTalk.SpecFlow.Bindings.StepArgumentTypeConverter.ConvertSimple(IBindingType typeToConvertTo, Object value, CultureInfo cultureInfo)
at TechTalk.SpecFlow.Bindings.StepArgumentTypeConverter.Convert(Object value, IBindingType typeToConvertTo, CultureInfo cultureInfo)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ConvertArg(Object value, IBindingType typeToConvertTo)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.<>c__DisplayClass38_0.<GetExecuteArguments>b__0(Object arg, Int32 argIndex)
at System.Linq.Enumerable.<SelectIterator>d__5`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.GetExecuteArguments(BindingMatch match)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(StepInstance stepInstance)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
at TechTalk.SpecFlow.TestRunner.CollectScenarioErrors()
at ABC.Api.Bdd.Tests.Features.V2.InstantTrackerFeature.ScenarioCleanup()
at ABC.Api.Bdd.Tests.Features.V2.InstantTrackerFeature.InstantTrackerReturnsA500ErrorResponseWhenErrorScenariosOccur() in C:\ABC.API\ABC.Api.Bdd.Tests\features\v2\InstantTracker.feature:line 36
The reason for the error was missing StepArgumentTransformation. as below.
[StepArgumentTransformation]
public IList<MovesStaging> TransformMovesStaging(Table identifiers)
{
return identifiers.Rows.Select(row => new MovesStaging
{
PartitionKey = ParseTableRowFieldAsString(row, "PartitionKey"),
RowKey = ParseTableRowFieldAsString(row, "RowKey"),
Timestamp = ParseTableRowFieldAsTimeStampUtc(row, "Timestamp"),
Status = ParseTableRowFieldAsString(row, "Status"),
ExpiryDate = ParseTableRowFieldAsDateTimeUtc(row, "ExpiryDate")
}).ToList();
}
Basically whenever you try to insert data through feature file you need to have this.
I came across similar type of question after that. I missed the question perhaps due to the subject.

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.

Visual Studio 2010 Windows Forms Designer Problems

Isn't that a crazy error?
I get this when trying to open a form containing some UserControls from another assebly and using Entity Framework and SQL CE on visual studio designer.
Object of type Namespace.T[] cannot be converted to type Namespace.T[]!!!
Call Stack:
at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast) at System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr) at System.Reflection.RtFieldInfo.InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, Boolean doVisibilityCheck, Boolean doCheckConsistency) at System.Runtime.Serialization.FormatterServices.SerializationSetValue(MemberInfo fi, Object target, Object value) at System.Runtime.Serialization.ObjectManager.CompleteObject(ObjectHolder holder, Boolean bObjectFullyComplete) at System.Runtime.Serialization.ObjectManager.DoNewlyRegisteredObjectFixups(ObjectHolder holder) at System.Runtime.Serialization.ObjectManager.RegisterObject(Object obj, Int64 objectID, SerializationInfo info, Int64 idOfContainingObj, MemberInfo member, Int32[] arrayIndex) at System.Runtime.Serialization.Formatters.Binary.ObjectReader.RegisterObject(Object obj, ParseRecord pr, ParseRecord objectPr, Boolean bIsString) at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ParseObjectEnd(ParseRecord pr) at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Parse(ParseRecord pr) at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run() at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream) at System.Resources.ResXDataNode.GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver) at System.Resources.ResXDataNode.GetValue(ITypeResolutionService typeResolver) at System.Resources.ResXResourceReader.ParseDataNode(XmlTextReader reader, Boolean isMetaData) at System.Resources.ResXResourceReader.ParseXml(XmlTextReader reader)
But its the same name type exactly!
The project builds successfully and runs ok!!!
OK i deleted the .resx file of the form and now i get 2 other errors i thought i have passed.
1st is "The specified named connection, not intended to be used with the EntityClient provider, or not valid"
Call Stack:
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) at System.Data.EntityClient.EntityConnection..ctor(String connectionString) at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString) at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName) at DJPro.Settings.Model.SettingsEntities..ctor() in D:\Visual Studio Projects\DJProAutomation\DJPro.Settings.Model\SettingsSelfTrackModel.Context.cs:line 33 at DJPro.Data.Access.SettingsDataOperations.GetConfiguration() in D:\Visual Studio Projects\DJProAutomation\DJPro.Data.Access\SettingsDataOperations.cs:line 33 at DJPro.Studio.Controls.DeckControl..ctor() in D:\Visual Studio Projects\DJProAutomation\DJPro.Deck.Controls\DeckControl.cs:line 51
2nd is about a control i have on a library saying.
"The variable deckControl1 is either undeclared or was never assigned"
Call Stack:
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
Then restored from a backup the resx file and im going back to the first problem.
So strange errors, everything seems fine in the Entity Data Model libraries and the app.config has all the necessary connection strings. As for the deckControl1 UserControl it seems fine to the library i have created it and opens ok.
I think this gets me crazy enough and stops the development.
Any idea?
It looks like you have a version conflict between the assembly used to generate the ResX and the currently referenced assembly.
Try removing the reference, re-adding it as a project reference, and regenerating the ResX.
Found the problem, if you use in UserControl constructor code that initializes entity framework context provides problems....even problem can occur while trying to initialize context for data operations in the Load event handler.
Tricky!

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