CodeDomProvider code crash in web project but not console app

I am using CodeDomProvider to compile C # code in memory and then execute the code. Everything works fine when I run the code in a console application. It compiles and I can execute it and get the result.

However, this same exact code fails when I try to run it in a web application. I am getting BadImageFormatException and the inner exception is Bad IL Format.

Are there any web or console app restrictions that I am not aware of?

Thanks for any suggestions.

I am running .NET 4.0.

Edit: I noticed that everything works until I add a reference to another assembly from the project. So I have a class library with a project reference that contains my entity model. I add it as a link, for example:

CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cp = new CompilerParameters();

cp.GenerateInMemory = true;
cp.ReferencedAssemblies.Add("mscorlib.dll");
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Core.dll");
cp.ReferencedAssemblies.Add("System.Data.Linq.dll");
cp.ReferencedAssemblies.Add("System.Data.Entity.dll");
cp.ReferencedAssemblies.Add("MyApp.Data.dll");

var results = provider.CompileAssemblyFromSource(cp, source);
var assm = results.CompiledAssembly;

      

If I just make my class the only method that returns a string and removes the reference to the MyApp.Data.dll reference, then everything works. Once I add that this link is coming back, it doesn't work.

Any ideas?

+1


source to share


2 answers


Since it was unable to add an assembly link, I did some Binging and came across this discussion . It was mainly an issue with the need to use Server.MapPath so the code could find the DLL.

cp.ReferencedAssemblies.Add(HttpContext.Current.Server.MapPath("bin\\MyApp.Data.dll"));

      



Now it works! So it was a simple mistake. :)

0


source


I create code on the fly from web applications in almost every project I have done in the last year, so it is definitely possible / practical.

Security would be a possible difference, but you might not get a permission exception BadImageFormatException

.



Another difference is that the default build profile for a console application is x86 4.0 Client Profile

, while the default for a web application isAny CPU, 4.0.

You can post your actual code; someone might detect the problem.

0


source







All Articles