Easy way to code gen in .net

Excerpt from Inject Controller Libraries Dynamically at Runtime in ASP.NET Web API using Custom Assembly Resolvers

Next we have the crux of the dll, the code to generate dll at runtime. The CreateDll method is in the WebApiGenerator.dll itself.

– We initialize the Compiler Version to v.4

– Next we initialize the C# CodDomProvider.

– We use the name passed to use, to use it as the name of the dll

– We create a CompilerParameters instance and set them up to
•  Generate a dll (as opposed to an Exe)
•  Provide the name of the output dll
•  Add Assembly references. These need to be present in the folder where the dynamic dll is being compiled. So be sure to add reference to the Dlls below. You can use the Package Manager Console as follows

PM> install-package Microsoft.Net.Http

PM> install-package Microsoft.AspNet.WebApi.Core

– Finally we add the source code to codeProvider. Note we have used the _controllerName passed into the WebApiGenerator as the class name and also reflected it in the Message.

– The CompileAssemblyFromSource call tries to compile the code into a Dll and if it fails all the Build errors are listed out.

– On success, a Build Succeeded message is shown.

– This completes our Code generator.

public void CreateDll()
{
IDictionary compParams =
new Dictionary() { { “CompilerVersion”, “v4.0” } };
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider(“CSharp”, compParams);
string outputDll = _controllerName + “.dll”;

System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = outputDll;
parameters.ReferencedAssemblies.Add(@”System.Net.Http.dll”);
parameters.ReferencedAssemblies.Add(@”System.Net.Http.WebRequest.dll”);
parameters.ReferencedAssemblies.Add(@”System.Net.Http.Formatting.dll”);
parameters.ReferencedAssemblies.Add(@”System.Web.Http.dll”);
string code = new StringBuilder()
.AppendLine(“using System.Web.Http;”)
.AppendLine(“namespace ControllerLibrary”)
.AppendLine(“{“)
.AppendLine(string.Format(“public class {0} : ApiController”, _controllerName))
.AppendLine(” {“)
.AppendLine(” public string Get()”)
.AppendLine(” {“)
.AppendLine(string.Format(“return \”Hi from a Dynamic controller library- {0} !\”;”, _controllerName))
.AppendLine(” }”)
.AppendLine(” }”)
.AppendLine(“}”)
.ToString();
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code);
if (results.Errors.Count > 0)
{
Console.WriteLine(“Build Failed”);
foreach (CompilerError CompErr in results.Errors)
{
Console.WriteLine(
“Line number ” + CompErr.Line +
“, Error Number: ” + CompErr.ErrorNumber +
“, ‘” + CompErr.ErrorText + “;” +
Environment.NewLine + Environment.NewLine);
}
}
else
{
Console.WriteLine(“Build Succeeded”);
return Assembly.LoadFrom(outputDll);
}
Console.ReadLine();
return null;
}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s