cagin
cagin

Reputation: 5920

How to impelement referenced assemblies to codedom in C#

I want to use CodeDom technology. But, I couldn't find the correct way to impelement referenced assemblies to my dynamic code. Everything is ok if I write just simple declaration code (e.x return "test"). But when I want to use MessabeBox compiler result error contains The name 'MessageBox' does not exist in the current context

 StringBuilder sbCode = new StringBuilder();

 sbCode.Append("public class Test {");
 sbCode.Append(tbCode.Text);
 sbCode.Append("}");
var cp = new CompilerParameters()
{
   GenerateInMemory = true,
   GenerateExecutable = false,
   ReferencedAssemblies =
    {
     "System.dll",
      "System.Core.dll",
      "System.Windows.dll",
      "System.Windows.Forms.dll"
    }
  };

  using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
   {
     CompilerResults res = codeProvider.CompileAssemblyFromSource(cp, sbCode.ToString());
     var type = res.CompiledAssembly.GetType("Test"); 
     var obj = Activator.CreateInstance(type);
     var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
   }

And here is my sample code which I write in tbCode text box:

public string Execute()
{
 MessageBox.Show("adsf");
return "asdf";
}

Upvotes: 0

Views: 504

Answers (1)

MedBechir
MedBechir

Reputation: 88

You should add the required "using" statements at the begining of the class declaration:

using System.Windows.Forms;

You can also call the MessageBox using the full namespace:

public string Execute()
{
 System.Windows.Forms.MessageBox.Show("adsf");
return "asdf";
}

Upvotes: 2

Related Questions