Recently I faced with very strange problem. Consider the following console application which I made in order to reproduce the problem:
If run this code BadImageFormatException will be thrown: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B).
At first I thought that I just build x86 application and double checked that Platform target is set to x64. Then goes strange thing: if you will move SPSecurity.RunWithElevatedPrivileges() outside the method Foo.GetAll() and enclose outer method call, exception will disappear and code will work as expected:
This code runs successfully. I checked stack trace of the exception from 1st example:
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
at ConsoleApplication.Foo.GetAll() in C:\…\ConsoleApplication\ConsoleApplication\Program.cs:line 22
at ConsoleApplication.Program.Main(String args) in C:\…\ConsoleApplication\ConsoleApplication\Program.cs:line 40
at System.AppDomain._nExecuteAssembly(Assembly assembly, String args)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
As you can see problem comes from method of generated class <>c__DisplayClass1.<GetAll>b__0(). When I tried to open this method in Reflector, Reflector failed:
So compiler generated wrong code for us in first example? Problem seems to be related with vtable, because when I removed “virtual” keyword from base method GetAll(), code became working:
This problem is strange, looks like a bug. But I’m not currently sure is it caused by Sharepoint code, by compiler or by something else – will update this post once will have additional info.