Run a codeCom code in AppDomain in .NET Framework 4.0

380 views Asked by At

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...
    }
}
1

There are 1 answers

0
Panos Rontogiannis On

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:

If you do not specify any attributes, the runtime interprets all code as security-critical, except where being security-critical violates an inheritance rule (for example, when overriding or implementing a transparent virtual or interface method). In those cases, the methods are safe-critical. Specifying no attribute causes the common language runtime to determine the transparency rules for you.

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 and RequestRefuse security actions.