How can I run the compiled code in the current AppDomain in NET Framework 4.0? Below the code that works in net framework 3.5, but objCompilerParameters.Evidence is obsolete in NET Framework 4.0 so how to solve it?
protected void Button1_Click(object sender, EventArgs e)
{
VBCodeProvider objVBCodeProvider = new VBCodeProvider();
CompilerParameters objCompilerParameters = new CompilerParameters();
objCompilerParameters.ReferencedAssemblies.Add("System.dll");
objCompilerParameters.Evidence = AppDomain.CurrentDomain.Evidence;
objCompilerParameters.CompilerOptions = string.Empty;
objCompilerParameters.GenerateExecutable = false;
objCompilerParameters.GenerateInMemory = false;
objCompilerParameters.IncludeDebugInformation = false;
objCompilerParameters.TreatWarningsAsErrors = false;
objCompilerParameters.WarningLevel = 0;
objCompilerParameters.ReferencedAssemblies.Add(this.GetType().Assembly.Location);
// source contains the code, is of type string
CompilerResults cr = objVBCodeProvider.CompileAssemblyFromSource(objCompilerParameters,source);
if (cr.Errors.HasErrors)
{ Console.WriteLine("Error");
foreach (CompilerError err in cr.Errors)
{ Console.WriteLine(err.ErrorText); } }
else
{
// Some things...
}
}
Security policy is no longer applied to applications (Notice that the .NET Framework Configuration tool is gone in Framework 4). Applications that run on the desktop are executed in full-trust. However you can sandbox applications and run them in partial-trust.
You will have to remove references to
CompilerParameters.Evidence
completely.You can use the SecurityRulesAttribute and SecurityTranparentAttribute if you don't want all code to be considered security-critical.
Read about Security-Transparency. In Framework 4 a second level was added.
Taken from the second-level transparency article:
What ChrisWue suggests is another alternative. Sandbox your application. For a quick intro on how to execute an assembly in a sandbox look at the example on SecurityManager.GetStandardSandbox.
PS: As far as I understand the reason they made these changes to the CAS is because it was quite complicated to use correctly. I still get confused by the
RequestMinimum
,RequestOptional
andRequestRefuse
security actions.