Skip to content
James Craig edited this page May 15, 2014 · 1 revision

The code generation portion of CUL is mostly used internally for generating code for AOP. Really this is done using Roslyn and puts a wrapper on top of it for simplification. That said it can be tied into and used for your own purposes.

The main, and really only, class of any importance in this portion of the system is the Compiler class. This class can be used in the following manner:

using (Utilities.DataTypes.CodeGen.Compiler Test = new Utilities.DataTypes.CodeGen.Compiler("Test", ".", true))
{
    Type ObjectType = Test.CreateClass("A", "public class A{ public string Value1{get;set;}}", null, typeof(object).Assembly);
}

The code above creates a new DLL called Test.dll in the default directory for your application. In the case of web applications, the /bin directory. For desktop apps, the application's base directory. It then creates a class A with the property Value1. You can also specify usings and assemblies that the class will need. In this case just the System assembly is specified.

Now the code above has a slight issue. First, the compiler attempts to be intelligent when it comes to regenerating the DLL. If you run this code multiple times, the Object type that is returned will be null after the first run. The reason for this is that the compiler will only regenerate the DLL if any of the other DLLs have a newer modified date. If they do, it will regenerate Test.dll. However any classes that are generated using the Compiler class are automatically loaded into the Classes list property:

using (Utilities.DataTypes.CodeGen.Compiler Test = new Utilities.DataTypes.CodeGen.Compiler("Test", ".", true))
{
    Type ObjectType = Test.Classes[0];
}

Like I said, this is mainly a system used internally. I would highly recommend just taking a look at Roslyn itself. It's truly wonderful and easy to tie into for code generation.

Clone this wiki locally