Problems after migrating to Entity Framework 5 - entity-framework-5

We just moved all of our entities into a new solution so that we could start developing EF5/MVC4/net4.5. However, I have an issue that is really baffling me and I have searched relentlessly for a possible cause, but have found nothing.
Using Code-First, migrations were created, database tables were populated with no issue.
The Problem is that no matter what entity I attempt to query against, I get the following error:
System.Data.EntityCommandCompilationException
{"The given key was not present in the dictionary."}
Here is the StackTrack:
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Data.Mapping.ViewGeneration.Structures.MemberDomainMap.GetDomainInternal(MemberPath path)
at System.Data.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateIsOfTypeCondition(MemberPath currentPath, IEnumerable`1 derivedTypes, MemberDomainMap domainMap)
at System.Data.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateVariableConstraintsRecursion(EdmType edmType, MemberPath currentPath, MemberDomainMap domainMap, EdmItemCollection edmItemCollection)
at System.Data.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateVariableConstraintsRecursion(EdmType edmType, MemberPath currentPath, MemberDomainMap domainMap, EdmItemCollection edmItemCollection)
at System.Data.Mapping.ViewGeneration.ViewgenContext..ctor(ViewTarget viewTarget, EntitySetBase extent, IEnumerable`1 extentCells, CqlIdentifiers identifiers, ConfigViewGenerator config, MemberDomainMap queryDomainMap, MemberDomainMap updateDomainMap, StorageEntityContainerMapping entityContainerMapping)
at System.Data.Mapping.ViewGeneration.ViewGenerator.CreateViewgenContext(EntitySetBase extent, ViewTarget viewTarget, CqlIdentifiers identifiers)
at System.Data.Mapping.ViewGeneration.ViewGenerator.GenerateQueryViewForExtentAndType(StorageEntityContainerMapping entityContainerMapping, CqlIdentifiers identifiers, KeyToListMap`2 views, EntitySetBase entity, EntityTypeBase type, ViewGenMode mode)
at System.Data.Mapping.ViewGeneration.ViewGenerator.GenerateQueryViewForSingleExtent(KeyToListMap`2 views, CqlIdentifiers identifiers, EntitySetBase entity, EntityTypeBase type, ViewGenMode mode)
at System.Data.Mapping.ViewGeneration.ViewgenGatekeeper.GenerateTypeSpecificQueryView(StorageEntityContainerMapping containerMapping, ConfigViewGenerator config, EntitySetBase entity, EntityTypeBase type, Boolean includeSubtypes, Boolean& success)
at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.TryGenerateQueryViewOfType(EntityContainer entityContainer, EntitySetBase entity, EntityTypeBase type, Boolean includeSubtypes, GeneratedView& generatedView)
at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGeneratedViewOfType(Pair`2 arg)
at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.TryGetGeneratedViewOfType(MetadataWorkspace workspace, EntitySetBase entity, EntityTypeBase type, Boolean includeSubtypes, GeneratedView& generatedView)
at System.Data.Metadata.Edm.MetadataWorkspace.TryGetGeneratedViewOfType(EntitySetBase extent, EntityTypeBase type, Boolean includeSubtypes, GeneratedView& generatedView)
at System.Data.Query.PlanCompiler.PreProcessor.ExpandView(Node node, ScanTableOp scanTableOp, IsOfOp& typeFilter)
at System.Data.Query.PlanCompiler.PreProcessor.ProcessScanTable(Node scanTableNode, ScanTableOp scanTableOp, IsOfOp& typeFilter)
at System.Data.Query.PlanCompiler.PreProcessor.Visit(FilterOp op, Node n)
at System.Data.Query.InternalTrees.FilterOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)
at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n)
at System.Data.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n)
at System.Data.Query.InternalTrees.ProjectOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)
at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n)
at System.Data.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n)
at System.Data.Query.InternalTrees.ProjectOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)
at System.Data.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)
at System.Data.Query.InternalTrees.BasicOpVisitorOfNode.VisitPhysicalOpDefault(PhysicalOp op, Node n)
at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.Visit(PhysicalProjectOp op, Node n)
at System.Data.Query.InternalTrees.PhysicalProjectOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Query.PlanCompiler.PreProcessor.Process(Dictionary`2& tvfResultKeys)
at System.Data.Query.PlanCompiler.PreProcessor.Process(PlanCompiler planCompilerState, StructuredTypeInfo& typeInfo, Dictionary`2& tvfResultKeys)
at System.Data.Query.PlanCompiler.PlanCompiler.Compile(List`1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set`1& entitySets)
at System.Data.EntityClient.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree)
At first I thought that is could be our new implementation of enums or other complex types, but since even the simplest entity with no relationships throws the same error, I am at a loss. Thanks in advance for any input.

Related

NPE when retrieving from HashMap even though containsKey() returns true in multithreaded environment

We are trying to store unique object for a particular key. When getMyObject is called in multithreaded environment we are getting null ptr exception at the time of return statement
object SampleClass
{
fun getMyObject(Id : String) : MyObject
{
if(!myMap.containsKey(Id))
{
synchronized(SampleClass)
{
if(!myMap.containsKey(Id))
{
myMap[Id] = MyObject()
}
}
}
return myMap[Id]!!
}
private val myMap = HashMap<String,MyObject>()
}
It seems even though contains method returns true when we try to get the value the value is returned null.
I am not sure what is the reason behind it.
This is the kind of trouble you get into if you try to outsmart the memory model. If you look at HashMap's source, you'll find containsKey implemented as:
public boolean containsKey(Object key) {
return getNode(key) != null;
}
Note that it returns true only if there's a HashMap.Node object corresponding to the given key. Now, this is how get is implemented:
public V get(Object key) {
Node<K,V> e;
return (e = getNode(key)) == null ? null : e.value;
}
What you're seeing is an instance of the unsafe publication problem. Let's say 2 threads (A & B) call getMyObject for a non-existent key. A is slightly ahead of B, so it gets into the synchronized block before B calls containsKey. Particularly, A calls put before B calls containsKey. The call to put creates a new Node object and puts it into the hash map's internal data structures.
Now, consider the case when B calls containsKey before A exists the synchronized block. B might see the Node object put by A, in such case containsKey returns true. At this point, however, the node is unsafely published, because it is accessed by B concurrently in a non-synchronized manner. There's no guarantee its constructor (the one setting its value field) has been called. Even if it was called, there's no guarantee the value reference (or any references set by the constructor) is published along with the node reference. This means B can see an incomplete node: the node reference but not its value or any of its fields. When B proceeds to get, it reads null as the value of the unsafely published node. Hence the NullPointerException.
Here's an ad-hoc diagram for visualizing this:
Thread A Thread B
- Enter the synchronized block
- Call hashMap.put(...)
- Insert a new Node
- See the newly inserted (but not yet
initialized from the perspective of B)
Node in HashMap.containsKey
- Return node.value (still null)
from HashMap.get
- !! throws a `NullPointerException`
...
- Exit the synchronized block
(now the node is safely published)
The above is just one scenario where things can go wrong (see comments). To avoid such hazards, either use a ConcurrentHashMap (e.g. map.computeIfAbsent(key, key -> new MyObject())) or never access your HashMap concurrently outside of a synchronized block.

Misleading exception message in GatewayMethodInboundMessageMapper with un-annotated parameters

The following code throws a MessagingException with message At most one parameter (or expression via method-level #Payload) may be mapped to the payload or Message. Found more than one on method [public abstract java.lang.Integer org.example.PayloadAndGatewayHeader$ArithmeticGateway.add(int,int)].
#MessagingGateway
interface ArithmeticGateway {
#Gateway(requestChannel = "add.input", headers = #GatewayHeader(name = "operand", expression = "#args[1]"))
Integer add(#Payload final int a, final int b);
}
The desired functionality could be achieved with something like:
#MessagingGateway
interface ArithmeticGateway {
#Gateway(requestChannel = "add.input", headers = #GatewayHeader(name = "operand", expression = "#args[1]"))
#Payload("#args[0]")
Integer add(final int a, final int b);
}
Should the first version also work? Nevertheless I believe the error message could be improved.
A sample project can be found here. Please check org.example.PayloadAndGatewayHeader and org.example.PayloadAndGatewayHeaderTest.
EDIT
The purpose of #GatewayHeader was to show why one may want to have additional parameters that will not be part of the payload but I am afraid it created confusion. Here is a more streamlined example:
#MessagingGateway
interface ArithmeticGateway {
#Gateway(requestChannel = "identity.input")
Integer identity(#Payload final int a, final int unused);
}
Shouldn't the unused parameter be ignored since there is already another one that is annotated with #Payload?
You can't mix parameter annotations (which are static) with expressions (which are dynamic) because the static code analysis can't anticipate what the dynamic expression will resolve to at runtime. It is probably unlikely, but there theoretically could be conditions in the expression. In any case, it can't determine at analysis time that the expression will provide a value for #args[1] at runtime (it could, of course for this simple case, but not all cases are this simple).
Use one or the other; use your second approach or
Integer add(#Payload final int a, #Header("operand") final int b);

Try to build a Java program to convert from Alloy instance to any language code

I am working on a research project that an Alloy generated instance holds entities (such as Signatures, Fields, Relations or Tuples) that resemble a programming language (such as java, c, etc).
For example, there are entities for Arithmetic operations (such as Add, Sub, Multiply, etc), for Relational operations (such equals, greater than, less than or equal, etc.) for variables, constants, and so on.
A tree view and graph view examples (max of two integers algorithm) of the model solution (instance found) are showing next. Those figures were extracted from Alloy Analyzer GUI.
My question is there a quick way to convert that alloy instance to any common language source code (Java would be the preferred language)?
Or should I do everything (Sigs, Fields, Atoms, language brackets, indentation, etc) by starting this way (going through an A4Solution) to build a kind of translator?
The main goal here is to build a Java program that is able to convert an Alloy instance to a Java source code file ready to compile and run.
//max of 2 integers' java source code at mymax2.java file
class MyMax2 {
public static void main(String[] args) {
int x;
int y;
int res;
if(y <= X) {
res = x;
} else {
res = y;
}
}
}
Finally, convert from XML to Java, by starting this way is not a desired option.
Thank you for help me on :)
Yours is really a formatted printing problem, with a tree as the data input. The tree is roughly an Abstract Syntax Tree (AST).
Do a post-order transversal of the tree, adding in the sensible text to each node as you travel back up the tree.
This means your "text for the node" function will look like a visitor, with lots of "policies" for each node type; however, there will be some wrinkles to address when it comes to variable scoping. Basically, the position of the declaration seems to be lost in your AST, and so you will have to write some code to cache the variable names in play, and define them in the upper blocks.
Since it might be ambiguous which block you would "unroll" your "variables to be declared" as you collapse your tree from the bottom up, your code will not be 100% identical to the input code. For example
public static void main(String[] args) {
int x;
if (x > 3) {
int y = 3 + x;
return x + y;
} else {
return 4;
}
}
might (after a full round trip of being converted to AST and back) read as
public static void main(String[] args) {
int x;
int y;
if (x > 3) {
y = 3 + x;
return x + y;
} else {
return 4;
}
}
Also, this assumes your AST has a pretty tight fit to the target programming language. For example, if you wanted to convert the presented AST to Prolog; you would quickly find out that the constructs in your AST are a poor fit for Prolog generation.
Should you need some direction, look into Pretty Printers which leverage most of the components of a compiler, with the exception that after they have their AST, they process it back out as source code.
There are a few wrinkles, but nothing too severe (provided your AST isn't missing a critical piece of information for the reverse back to source code).

Optional Parameter in C# 4.0

List<DynamicBusinessObject> dbo = SearchController.Instance.GetSearchResultList(search, null, "date", startRow - 1, ucDataPager1.PageSize, state);
The above line of code is calling the GetSearchResultList method which up until now had 5 arguments.
I added a 6th argument but wanted to make this argument optional so that all the other pages that call this function don't need to be updated just yet.
So i changed the function to look like this:
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
public List<DynamicBusinessObject> GetSearchResultList(Search search, List<CategoryAttribute> listCatAttrib, string sortBy, int startRow, int pageSize, [Optional, DefaultParameterValue("")] string state)
{
StorageQuery qry = new QrySearchResult(
search.ID,
(listCatAttrib != null && listCatAttrib.Count > 0) ? listCatAttrib[0].Attribute.ID : -1,
(listCatAttrib != null && listCatAttrib.Count > 1) ? listCatAttrib[1].Attribute.ID : -1,
(listCatAttrib != null && listCatAttrib.Count > 2) ? listCatAttrib[2].Attribute.ID : -1,
1, sortBy, startRow, pageSize, state);
List<DynamicBusinessObject> list = BusinessObject.Search(qry);
return list;
}
However, when i try to build, it gives me the error that GetSearchResultList has no overload method and takes 5 arguments.
I also tried doing string state = "" instead of using [Optional]
Anyone got any ideas why it's complaining about me not passing 6 arguments when i make the call if the 6th argument is optional?
Those attributes are not how you define an optional parameter in c#.
Rather, the syntax is just the parameter plus = <value>.
So your method signature becomes:
public List<DynamicBusinessObject> GetSearchResultList(
Search search,
List<CategoryAttribute> listCatAttrib,
string sortBy,
int startRow,
int pageSize,
string state = "")
Although I'd recommend using null instead of an empty string, the default types are more natural fits if these signatures are consumed by external libraries.
Optional parameters are like constants, they are baked into referencing assemblies at compile-time.
Let's say you have another library which calls this method using the optional parameter, like so:
myObj.GetSearchListResult(search, listCatAttrib, sortBy, startRow, pageSize);
At the time you compile this library, the call will actually be written in your library as:
myObj.GetSearchListResult(search, listCatAttrib, sortBy, startRow, pageSize, "");
Then, if you change the declaration of your method to be:
public List<DynamicBusinessObject> GetSearchResultList(
Search search,
List<CategoryAttribute> listCatAttrib,
string sortBy,
int startRow,
int pageSize,
string state = "some value")
The call in the first library will still pass an empty string, not the new value. You have to recompile the all callers of your method to make sure the new value takes.
That said, this is why if you are exposing this method outside of your assembly, you use overloads instead of default values; if you change the value passed to the method in the overload, you only have to distribute the assembly where the method is defined, you don't have to distribute and have all the callers against that method recompiled.
You should be able to use:
..., string state = "") {
One possible issue is that your project is targeting an older version of .NET. Check the project properties to make sure it is pointing at the correct version.

Can CompareExchange be implemented with CompareAndSwap?

Assuming that CompareAndSwap (or CAS) never fails spuriously, can CompareExchange be implemented with CAS?
CompareExchange both take a pointer, an expected value, and a new value and atomically set the memory referenced by the pointer to the new value if it matches the expected value. The difference between the two is that CompareExchange returns the previous value of the memory area and CompareAndSwap returns a bool indicating success or failure.
It's trivial to implement CAS with CompareExchange:
int CompareExchange (int* p, int expected, int newvalue);
bool CAS (int* p, int expected, int newvalue)
{
return CompareExchange (p, expected, newvalue) != expected;
}
... but is it possible to implement CompareExchange with CAS? All the attempts I've seen either have race conditions or don't guarantee lockless properties. I don't believe it's possible.
I don't see how it's possible. For the case where CAS fails, you'll need a separate operation to get the previous value. This separate operation will not be atomic relative to the CAS.
You can get part way there:
int CompareExchnage(int *p, int expected, int newvalue)
{
if (CAS(p, expected, newvalue))
return expected;
else
???;
}
It's the case where CAS fails where you have the problems. Getting *p to find what the previous value is will not be atomic relative to CAS so you either have a race condition or you would have to lock around the CAS and the *p dereference.
You can, and it is lock-free, but it is not wait-free:
int CompareExchange(int *p, int expected, int newvalue)
{
for (;;) {
oldValue = *p;
if (oldValue != expected)
return oldValue;
if (CAS(p, expected, newvalue))
return expected;
}
}
The idea is that a modification of *p after returning from CompareExchange is indistinguishable from a modification between the two ifs.
Similarly, you can implement atomic exchange and atomic fetch-and-OP based on CAS, but it will not be wait-free.

Resources