I want to return a custom class (ex. User
) from a function which created by a Codedom. My User
class in another class library in the same solution with my Windows Application
which I use it for Dynamic Code generation.
CompilerResult returns these errors:
The type or namespace name 'TestApp' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'User' could not be found (are you missing a using directive or an assembly reference?)
Here is my code :
StringBuilder sbCode = new StringBuilder();
sbCode.Append(@"using System.Windows.Forms;");
sbCode.Append(@"using Nikola.BusinessIntelligence.Objects;");
sbCode.Append(@"using System.Collections.Generic;");
sbCode.Append(@"using System.Text;");
sbCode.Append(@"using Microsoft.CSharp;");
sbCode.Append(@"using TestApp.Data;"); // User class is in this Class Lib
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 User Execute()
{
User usr = new User();
return usr;
}