EF Core 2.1 InvalidCastException on DbContext.Query<T>() - ef-core-2.1

Given:
public class MyClass
{
public MyClass(ApplicationDbContext db)
{
var query = db.Query<IdentityUser>();
}
}
Using ASP.NET Core 2.1, I am getting this exception on the db.Query<IdentityUser>() call:
System.InvalidCastException: 'Unable to cast object of type 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet\`1[Microsoft.AspNetCore.Identity.IdentityUser]' to type 'Microsoft.EntityFrameworkCore.DbQuery\`1[Microsoft.AspNetCore.Identity.IdentityUser]'.'
I ran into this with my own entities and reproduced it with minimal code using the canned ApplicationDbContext/IdentityUser. Is this a bug in .NET Core 2.1 or am I doing something incorrectly?
This is the source code from github for DbContext.Query<T>():
public virtual DbQuery<TQuery> Query<TQuery>()
where TQuery : class
=> (DbQuery<TQuery>)((IDbQueryCache)this)
.GetOrAddQuery(DbContextDependencies.QuerySource, typeof(TQuery));
It appears to be throwing the exception casting ((IDbQueryCache)this).GetOrAddQuery(DbContextDependencies.QuerySource, typeof(TQuery)) to (DbQuery<TQuery>)
I've opened an issue on github since this seems to be a bug from what I can tell.

Comment on my github issued had the solution:
You cannot call Query<> method for EntityTypes. You must use Set<>
method.
It might be helpful for TQuery to be more constrained than just class if that is possible.

Related

Custom error classes not extending correctly [duplicate]

I'm trying to throw a custom error with my "CustomError" class name printed in the console instead of "Error", with no success:
class CustomError extends Error {
constructor(message: string) {
super(`Lorem "${message}" ipsum dolor.`);
this.name = 'CustomError';
}
}
throw new CustomError('foo');
The output is Uncaught Error: Lorem "foo" ipsum dolor.
What I expect: Uncaught CustomError: Lorem "foo" ipsum dolor.
I wonder if that can be done using TS only (without messing with JS prototypes)?
Are you using typescript version 2.1, and transpiling to ES5? Check this section of the breaking changes page for possible issues and workaround: https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
The relevant bit:
As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.
class FooError extends Error {
constructor(m: string) {
super(m);
// Set the prototype explicitly.
Object.setPrototypeOf(this, FooError.prototype);
}
sayHello() {
return "hello " + this.message;
}
}
However, any subclass of FooError will have to manually set the prototype as well. For runtimes that don't support Object.setPrototypeOf, you may instead be able to use __proto__.
Unfortunately, these workarounds will not work on Internet Explorer 10 and prior. One can manually copy methods from the prototype onto the instance itself (i.e. FooError.prototype onto this), but the prototype chain itself cannot be fixed.
The problem is that Javascript's built-in class Error breaks the prototype chain by switching the object to be constructed (i.e. this) to a new, different object, when you call super and that new object doesn't have the expected prototype chain, i.e. it's an instance of Error not of CustomError.
This problem can be elegantly solved using 'new.target', which is supported since Typescript 2.2, see here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
class CustomError extends Error {
constructor(message?: string) {
// 'Error' breaks prototype chain here
super(message);
// restore prototype chain
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); }
else { this.__proto__ = actualProto; }
}
}
Using new.target has the advantage that you don't have to hardcode the prototype, like some other answers here proposed. That again has the advantage that classes inheriting from CustomError will automatically also get the correct prototype chain.
If you were to hardcode the prototype (e.g. Object.setPrototype(this, CustomError.prototype)), CustomError itself would have a working prototype chain, but any classes inheriting from CustomError would be broken, e.g. instances of a class VeryCustomError < CustomError would not be instanceof VeryCustomError as expected, but only instanceof CustomError.
See also: https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
As of TypeScript 2.2 it can be done via new.target.prototype.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example
class CustomError extends Error {
constructor(message?: string) {
super(message); // 'Error' breaks prototype chain here
this.name = 'CustomError';
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
}
}
It works correctly in ES2015 (https://jsfiddle.net/x40n2gyr/). Most likely, the problem is that the TypeScript compiler is transpiling to ES5, and Error cannot be correctly subclassed using only ES5 features; it can only be correctly subclassed using ES2015 and above features (class or, more obscurely, Reflect.construct). This is because when you call Error as a function (rather than via new or, in ES2015, super or Reflect.construct), it ignores this and creates a new Error.
You'll probably have to live with the imperfect output until you can target ES2015 or higher...
I literally never post on SO, but my team is working on a TypeScript project, and we needed to create many custom error classes, while also targeting es5. It would have been incredibly tedious to do the suggested fix in every single error class. But we found that we were able to have a downstream effect on all subsequent error classes by creating a main custom error class, and having the rest of our errors extend that class. Inside of that main error class we did the following to have that downstream effect of updating the prototype:
class MainErrorClass extends Error {
constructor() {
super()
Object.setPrototypeOf(this, new.target.prototype)
}
}
class SomeNewError extends MainErrorClass {}
...
Using new.target.prototype was the key to getting all of the inheriting error classes to be updated without needing to update the constructor of each one.
Just hoping this saves someone else a headache in the future!
I ran into the same problem in my typescript project a few days ago. To make it work, I use the implementation from MDN using only vanilla js. So your error would look something like the following:
function CustomError(message) {
this.name = 'CustomError';
this.message = message || 'Default Message';
this.stack = (new Error()).stack;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
throw new CustomError('foo');
It doesn't seem to work in SO code snippet, but it does in the chrome console and in my typescript project:
I was having this problem in a nodejs server. what worked for me was to transpile down to es2017 in which these issues seems to be fixed.
Edit tsconfig to
"target": "es2017"
Try this...
class CustomError extends Error {
constructor(message: string) {
super(`Lorem "${message}" ipsum dolor.`)
}
get name() { return this.constructor.name }
}
throw new CustomError('foo')

Resolve caste windsor failing

Recently upgraded to version 3.2.1 of castle windsor and receiving an error when attempting to resolve a service that previously didn't occur in version 3.0 of the windsor framework.
IWindsorContainer container = new WindsorContainer();
The following code no longer works
// Throws component not found exception
InstallerHelper.ProcessAssembliesInBinDirectory(
assembly => container.Register(
Classes
.FromAssembly(assembly)
.BasedOn<IWindsorInstaller>()
.WithService.FromInterface()
.LifestyleSingleton()
));
var installers = container.ResolveAll<IWindsorInstaller>();
container.Install(installers);
// Fails here, is it related to a hashcode mismatch in SimpleTypeEqualityComparer?
var credentialCache = container.Resolve<ICredentialCache>()
// works fine if explicity install installers individually
container.Install(new CredentialsInstaller());
var credentialCache = container.Resolve<ICredentialCache>()
Where ProcessAssembliesInBinDir is:
public static void ProcessAssembliesInBinDirectory(Action<Assembly> action)
{
var directoryName = GetDirectoryName();
foreach (var dll in Directory.GetFiles(directoryName, "*.dll"))
{
var fileInfo = new FileInfo(dll);
if (!IgnoreList.Any(x=>fileInfo.Name.StartsWith(x)))
{
var assembly = Assembly.LoadFile(dll);
action(assembly);
}
}
}
Where credential installer is:
public class CredentialsInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<ICredentidalCache>()
.ImplementedBy<CredentidalCache>()
.LifestyleSingleton()
);
// This works fine
var credentialCache = container.Resolve<ICredentialCache>()
}
}
Class implementation
public interface ICredentidalCache {}
public class CredentidalCache : ICredentidalCache{}
This is being run from an MVC application
version 4.5 of the .net framework
the credential installer lives inside another assembly, referenced by the website
using the Windsor source, the successful attempt to resolve occurs when the typeof(ICredentialCache).GetHashCode() is the same as what has been registered. For some reason when returning out of the installer the hashcode has changed for the type. Putting a debug line inside SimpleTypeEqualityComparer.GetHashCode(Type obj) shows that hashcodes are different for the same Type.
inspecting the container inside the debugger shows the ICredentialCache successfully installed.
Edit
Manage to move forward by manually registering installers, ie. not relying on the resolve<IwindsorInstaller>() and use container.install(new Installer(), ...). If i find out more I'll update the SO question.
This works fine for me:
public sealed class AppServiceFactory
{
...
public T Create<T>()
{
return (T)container.Resolve(typeof(T));
}
...
}
AppServiceFactory.Instance.Create<IYourService>();
The problem is caused by the InstallerHelper and how it goes about loading an assembly. This SO post pointed me in the right direction,
https://stackoverflow.com/a/6675227/564957
essentially the way the assembly was loaded was failing using Assembly.LoadFile(string fileName) was causing the problem, changing this to be Assembly.Load(string assemblyName) rectified the issue.
#Eric Lippert does a good job explaining
[when] loading an assembly by its path, and one via loading the same
assembly by its assembly name... reflection will
consider types from the two loadings of the same assembly to be
different types. Any assembly loaded from its path is considered to be
distinct from an assembly loaded by its assembly name.

jaxbcontext.newinstance() with eclipselink MOXy hangs

disclaimer: I'm incredibly amateur at all of this
I'm trying to get the project I'm working on to output JSON in addition the XML.
Originally the prior method to do so involved a method that took in an argument of Element and recursively inserted things into an object of type net.sf JSONObject to create the JSON output, and used the normal JAXBContext's Marshaller to marshal into XML.
What I wanted was to use MOXy as my JAXB provider, and then marshal out both XML and JSON from the bindings.
Originally, when the XML was marshalled, I had:
jc = JAXBContext.newInstance("packageA:packageB:packageC...etc.");
public static String marshal(JAXBContext context, JAXBElement<?> je) throws JAXBException {
StringWriter sout = new StringWriter();
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
m.marshal(je, sout);
return sout.toString();
}
and then
JAXBElement<myObject> jaxb =
new JAXBElement<myObject>(myObject_QNAME, myObject.class, null, value);
return XmlResponseMessage(marshal(jc, jaxb));
}
(this is probably important, so I should mention that the application I'm working on uses the spring framework.)
Also, I've read every single one of Blaise's blog posts regarding EclipseLink. Some multiple times. I just have a very shallow understanding of it and would appreciate if instead of linking me to one of his pages you explained whatever solution on it is and why it works
That being said, I tried just including the jaxb.properties file in one of the packages to try to get MOXy as opposed to JAXBElement to get my bindings.
however, JAXBContext.newInstance("my list of : delimited packages") just makes the program hang. not even an error, just hangs it. stepping through just shows the call to the EclipseLink newInstance method hanging.
I've looked for many hours for solutions online. I have much too many classes to just include in a Class[], and so can't set the property by using an array of classes. which is also the reason I couldn't use the native moxy API instead of using the property file. I think i have EclipseLink set up correctly: I've set eclipselink_home in my environment variables, and added the eclipselink.jar to my buildpath.
UPDATE #2
A fix for this issue has been checked into the EclipseLink 2.4.2 and 2.5.0 streams and a nightly build containing the fix can be downloaded from the following link starting March 12, 2013:
http://www.eclipse.org/eclipselink/downloads/nightly.php
UPDATE #1
After a couple of email exchanges I think the problem you are encountering is due to the following bug. You can use the link to track our progress on this issue.
http://bugs.eclipse.org/402801
I'll demonstrate how it manifests itself below:
ObjectFactory
For the problem to occur you need to have an #XmlElementDecl annotation where thename is the same as the substitutionHeadName.
#XmlRegistry
public class ObjectFactory {
#XmlElementDecl(name="foo", substitutionHeadName="foo")
public JAXBElement<Foo> createBar(Foo foo) {
return new JAXBElement<Foo>(new QName("foo"), Foo.class, foo);
}
}
Domain Object (Foo)
Then on one of your domain objects you need to have an #XmlElementRef annotation referencing the element we defined in the #XmlElementDecl.
public class Foo {
#XmlElementRef(name="foo")
public Foo foo;
}
Demo
You will see the problem when you create the JAXBContext.
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class, ObjectFactory.class);
System.out.println(jc.getClass());
}
}
Trace
MOXy gets in an infinite loop adding the reference element.
...
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
at org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor.addReferencedElement(AnnotationsProcessor.java:3740)
...
ORIGINAL ANSWER
You could try using the following to create your JAXBContext. It bypasses the standard JAXB impl lookup code by using native MOXy code.
JAXBContext jc = org.eclipse.persistence.jaxb.JAXBContextFactory.createContext("packageA:packageB:packageC...etc.");
If that works we'll know the problem is related to the impl look up code and we can go from there.

Basic Windsor Constructor Injection

I am new to Windsor and am trying to implement the most basic constructor injection. Apparently the API has changed so much over the recent versions that the documentation that is for the current version seems to assume you already know how to do it, and the documentation for the old versions is outdated.
I have a simple test component:
public class ConstructorInjectedComponent
{
public IMyComponent Component { get; set; }
public ConstructorInjectedComponent(IMyComponent component)
{
Component = component;
}
}
There is a simple implementation of IMyComponent:
public class AMyComponent : IMyComponent
{
public string Name { get; set; }
public AMyComponent()
{
Name = Guid.NewGuid().ToString("N");
}
}
And I want to somehow register my types with Windsor such that I can get back an instance of ConstructorInjectedComponent that contains an instance of its dependency: IMyComponent.
I've register AMyComponent like so:
_container.Register(Component.For(typeof(AMyComponent)));
I've register ConstructorInjectedComponent like this:
_container.Register(Component.For(typeof(ConstructorInjectedComponent)));
and tried to resolve it with
_container.Resolve(typeof(ConstructorInjectedComponent));
But that fails with "can't create component ConstructorInjectedComponent because it has dependencies which need to be satisfied.
so I try to pass in an IDictionary of dependencies for the ConstructorInjectedComponent ... and this is where the documentation fails me.
I have no idea how to define that dictionary. I can find no documentation which explains it. I've tried this:
var d = new Dictionary<string, string>() {{"IMyComponent", "AMyComponent"}};
_container.Register(Component.For(typeof(ConstructorInjectedComponent))
.DependsOn(dependencies));
But that fails with the same "has dependencies that need to be resolved" error.
What am I doing wrong?
First it's crucial to make sure you understand the basic concepts, namely what a component is, what a service is, and what a dependency is.
The documentation about it is quite good.
The documentation about how to use registration API should help you get going.
The tl;dr asnwer is: since ConstructorInjectedComponent depends on IMyComponent make sure you register AMyComponent to expose IMyComponent as a service.
_container.Register(Component.For<IMyComponent>().ImplementedBy<AMyComponent>());

Jibx always gives "Error during validation: null"

I'm really stumped on this incredibly simple mapping. It looks just like one of the examples even. If I comment out the internal structure, it'll run the binding compiler successfully. If I put the internal structure back in, it fails. Note that the internal structure is just defining the XML. This is basically example5 of the JIBX tutorial examples.
<binding>
<mapping name="RequestTransaction" class="TransactionRequest">
<value name="version" set-method="setVersion" get-method="getVersion" style="attribute" />
<structure name="transHeader">
<value name="requestCount" set-method="setRequestCount" get-method="getRequestCount"/>
</structure>
</mapping>
<binding>
Then I get the following error on the jibx compile:
Error: Error during validation: null; on mapping element at (line 2, col 97, in jibx-binding.xml)
I'm absolutely stumped and out of ideas. Google shows nothing useful.
The <structure> is arguably the most important concept in JiBX binding because it allows you to map arbitrary XML to your Java classes without forcing you to create bloated and ugly layers of nested Java objects and classes to match the XML design.
In this case your binding declares that you have an XML element named <transHeader> that will not be present in your Java class.
With some slight fixes to your XML format, your binding works perfectly. I assume the fact that your binding has two <binding> open tags rather than and open and close <binding></binding> is a typo, because you said you got it to work without the structure. Also add <?xml version="1.0"?> at the top of your binding file. Those two XML mods allow the JiBX 1.2 binding compiler to work with the following Java class:
(Note: you didn't provide the Java class this binding is for so I had to reconstruct it from the info you put in the binding file. The obvious side effect of this is that I reconstructed a class that will work with this binding. But the simple fact is that a JiBX binding by design contains all the info you need to know about the class and the XML.)
public class TransactionRequest {
private String version;
private int requestCount;
public void setVersion(String ver) {
version = ver;
}
public String getVersion() {
return version;
}
public void setRequestCount(int count) {
requestCount = count;
}
public int getRequestCount() {
return requestCount;
}
}
compile the class then run the binding compiler with:
>java -jar jibx-bind.jar jibx-binding.xml
To test it I used the following sample.xml:
(Note: you also didn't provide the XML you are trying to map so again I created a sample based on what you did provide)
<?xml version="1.0"?>
<RequestTransaction version="0.1">
<transHeader>
<requestCount>3</requestCount>
</transHeader>
</RequestTransaction>
Running the test uses the following code:
public static void main(String[] argz) {
String fileName = "./sample.xml";
IBindingFactory bfact = null;
IUnmarshallingContext uctx = null;
TransactionRequest sample = null;
try {
bfact = BindingDirectory.getFactory(TransactionRequest.class);
uctx = bfact.createUnmarshallingContext();
InputStream in = new FileInputStream(fileName);
sample = (TransactionRequest)uctx.unmarshalDocument(in, null);
System.out.println(sample.getRequestCount());
System.out.println(sample.getVersion());
}
catch (Exception e) {
e.printStackTrace();
}
}
And it runs successfully.
It's been a while now, but I found it was related to inheritance. I needed to give mappings for everything in the inheritance tree, including interfaces as I recall.
I ended up creating a wrapper object, which I've found seems to be the easiest way to use JIBX in general. Trying to map a true domain class causes tendrils into every class that class touches and I have to unjar everything so JIBX can find the classes, including 3rd party libs.