Using 'base' keyword in delegate causes System.BadImageFormatException - c#-4.0

I have a weird problem and I would like if someone can enlighten me on why is this happening. I have a protected method in a base abstract class as following:
protected T ForExistingEntity<T>(TEntity entity, object key, Func<Entity, T> action) {
entity = GetByKey(key);
if (entity != null)
return action(entity);
return default(T);
}
My original call from an inherited class was as follows:
return base.ForExistingEntity(
new MyEntity(), key, e => {
e.someFiled = 5;
return base.Update(e);
}
);
When this code executes, an exception get raised at the line that reads:
return action(entity);
in the base abstract class. The exception is:
System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
Now when I modify my call as following:
return base.ForExistingEntity(
new MyEntity(), key, e => {
e.someFiled = 5;
return Update(e);
}
);
it runs normally without any issues.
Edit:
The Update method is located in the base abstract class and looks like this:
public virtual bool Update(TEntity entity) {
Condition.Requires(entity, "entity")
.IsNotNull();
if (ValidateEntity(entity))
return Update(entity, true);
return false;
}
I am starting to think that this is happening because of Update being virtual and the call actually originates in the base class itself? The exception isn't very helpfull anyway.

This seems to be a known C# compiler bug involving calling a base virtual method from an anonymous method within a generic class. Don't hesitate to upvote this bug on connect if you want it solved. Fortunately, the workaround is quite simple here.

I had the same issue. I had .NET 4.5 framework installed. When I uninstalled this and replaced with .NET 4.0 framework, this problem went away (i.e. 4.0.30319 when I look at the top right corner of my VS2010 info)

Related

PostSharp - Applying aspect to mscorlib but prohibit modifying calls in my own class

My aspect:
[Serializable]
class DumbLogger : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Log.Print("Entry: ") + args.Method.Name;
args.FlowBehavior = FlowBehavior.Continue;
}
}
This is what i am using to modify the calls in mscorlib AND trying to exclude them from being modified in my class called LOG
[assembly: MY_PROJECT.DumbLogger(
AttributeTargetTypes = "MY_PROJECT.Log",
AttributeExclude = true,
AttributePriority = 1)]
[assembly: MY_PROJECT.DumbLogger(
AttributeTargetAssemblies = "mscorlib",
AttributePriority = 2)]
But.. This doesnt do the trick because if i look at my LOG class with ILspy decompiler i can see method calls to any class # mscorlib.dll being modified for example:
<>z__Aspects.<System.Object.ToString>b__v(text)
The reason i wanna do this is because when i enter the method Log.Print it will generate a stackoverflow exception and will infinitely call itself.
I am already aware of maybe excluding certain namespaces and classes like string from mscorlib but i have my reasons to do it the way i described.
PostSharp Aspects in general are applied to declarations (assemblies, types, methods, parameters, fields, etc.). When you are applying an MethodLevelAspect (base class of OnMethodBoundaryAspect) on an external method, PostSharp transforms the call site (call instruction in IL), but still thinks of the aspect as being on the declaration itself.
There is currently no way to filter by call site and it would require a different kind of aspect and/or advices. Therefore your AttributeExclude=true specifying attribute on the assembly does not have any effect as it says that the aspect should not be applied on Log type, which it is not.
The common technique that solves exactly this case is to use a ThreadStatic variable to break the recursion cycle as the following code demonstrates:
[Serializable]
class DumbLogger : OnMethodBoundaryAspect
{
[ThreadStatic] private static bool logging;
public override void OnEntry(MethodExecutionArgs args)
{
if (logging)
return;
try
{
logging = true;
Log.Print("Entry: " + args.Method.Name);
args.FlowBehavior = FlowBehavior.Continue;
}
finally
{
logging = false;
}
}
}
Please also note that MethodInterception and OnMethodBoundary aspects are the only aspect that work on external assemblies.

Why is my IPersistenceStore implementation not being respected?

I am trying to create a new implementation of IPersistenceStore.
I understand I need to register my new implementation by using a IServiceLocator which is configured in the glimpse node of my web.config like so:
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd" serviceLocatorType="MyNewServiceLocator, MyAssembly">
However, I am seeing the following behaviour:
The GetInstance method of my IServiceLocator is never hit
The ctor of my new IPersistenceStore is hit at app start up
No other methods on my IPersistenceStore are ever hit (ie the Glimpse data is still being stored in the default impl of IPersistenceStore)
It appears that my IPersistenceStore is not being registered correctly. Why could this be?
It's not clear what could be wrong, as you don't show any of your code related to the IServiceLocator
Something along these lines should suffice to have your custom persistence store returned by your custom service locator:
public class MyNewServiceLocator : IServiceLocator
{
public T GetInstance<T>() where T : class
{
var type = typeof(T);
if (type == typeof(IPersistenceStore))
{
return new CustomPersistenceStore() as T;
}
return null;
}
public ICollection<T> GetAllInstances<T>() where T : class
{
return null;
}
}

Error while building the solution in vs2012?

I've created my project in vs2008.It works fine.But when i opened the solution and try to build it in vs2012 i am getting the following error in TransactionDB.dbml page.
a partial method may not have multiple defining declarations
What could be the problem??
.net supports partial methods.
It means you write a definition in one part of the partial class and the implementation in another. Like this:
partial class MyClass
{
partial void MyPartialMethod(string s);
}
// This part can be in a separate file.
partial class MyClass
{
// Comment out this method and the program will still compile.
partial void MyPartialMethod(string s)
{
Console.WriteLine("Something happened: {0}", s);
}
}
In your case I you have the two definitions of the partial method causing the compiler to fail.
Source MSDN
The defining declaration of a partial method is the part that specifies the method signature, but not the implementation (method body). A partial method must have exactly one defining declaration for each unique signature. Each overloaded version of a partial method must have its own defining declaration.
To correct this error
Remove all except one defining declaration for the partial method.
Example
// cs0756.cs
using System;
public partial class C
{
partial void Part();
partial void Part(); // CS0756
public static int Main()
{
return 1;
}
}

Type parameters - get concrete type from type T : IMyInterface

Suppose I have a List<IMyInterface>...
I have three classes which implement IMyInterface: MyClass1, MyClass2, and MyClass3
I have a readonly Dictionary:
private static readonly Dictionary<Type, Type> DeclarationTypes = new Dictionary<Type, Type>
{
{ typeof(MyClass1), typeof(FunnyClass1) },
{ typeof(MyClass2), typeof(FunnyClass2) },
{ typeof(MyClass3), typeof(FunnyClass3) },
};
I have another interface, IFunnyInteface<T> where T : IMyInterface
I have a method:
public static IFunnyInterface<T> ConvertToFunnyClass<T>(this T node) where T : IMyInterface
{
if (DeclarationTypes.ContainsKey(node.GetType())) {
IFunnyInterface<T> otherClassInstance = (FunnyInterface<T>) Activator.CreateInstance(DeclarationTypes[node.GetType()], node);
return otherClassInstance;
}
return null;
}
I'm trying to call the constructor of FunnyClasses and insert as parameter my MyClass object. I don't want to know which object it is: I just want to instantiate some FunnyClass with MyClass as a parameter.
What happens when I call ConvertToFunnyClass, T is of type IMyInterface, and when I try to cast it to FunnyInterface<T>, it says I can't convert FunnyClass1, for instance, to FunnyInterface<IMyInterface>
My current workaround (not a beautiful one), is this:
public static dynamic ConvertToFunnyClass<T>(this T node) where T : IMyInterface
{
if (DeclarationTypes.ContainsKey(node.GetType())) {
var otherClassInstance = (FunnyInterface<T>) Activator.CreateInstance(DeclarationTypes[node.GetType()], node);
return otherClassInstance;
}
return null;
}
And I don't like it because the return type is dynamic, so when I access it from somewhere else, I have no idea what type it is, and I lose intellisense, and stuff. I don't know about any performance implications either.
Any clues?
Thanks in Advance!
Resolution
As I'm using C# 4.0, I could stop casting errors using covariance (output positions only), and so I changed my IFunnyInterface to
IFunnyInteface<out T> where T : IMyInterface
Thank you all for the replies.
Essentially, your problem is that you are trying to convert FunnyInterface<T> to FunnyInterface<IMyInterface>. As has been mentioned several times (one example is here, more information here), this is not valid in most circumstances. Only in .NET 4, when the generic type is an interface or delegate, and the type parameter has been explicitly declared as variant with in or out, can you perform this conversion.
Is FunnyInterface actually an interface?
thecoop answer points you exactly to why you can't do it.
A cleaner solution to the problem (besides using dynamic) would be a base non-Generics Interface:
public interface IFunnyInterfaceBase
{
}
public interface IFunnyInteface<T> : IFunnyInterfaceBase
where T : IMyInterface
{
}
And you need to move methods signature you use in that code from IFunnyInteface to IFunnyInterfaceBase.
This way you would be able to write something like this:
MyClass2 c2 = new MyClass2();
IFunnyInterfaceBase funnyInstance = c2.ConvertToFunnyClass();
The Exception you said you got in your code is not due to the extension method signature itself (the method is fine)..it is originated by the type of your lvalue (the type of the variable you use to store its return value)!
Obviously this solution applies only if you can modify IFunnyInterface source code!

Is it bad to return same property in get accessor? public string ProjectID { get { return ProjectID; } etc

I have a simple class that I want to implement INotifyPropertyChanged. I don't need to have a private version of this property. The class is being passed via a WCF service and a Silverlight client.
My question: Is it OK to structure the get accessor this way? Just does not seem right to me.
public ProjectID
{
get
{
return this.ProjectID;
}
set
{
ProjectID = value;
NotifyPropertyChanged("ProjectID");
}
}
I think the code above will throw a stack overflow exception, you may have to implement a member to support the interface you want to
That would result in a StackOverflowException, because the get property would keep recursively calling itself.

Resources