Click here to Skip to main content
Click here to Skip to main content

Dynamic Creation of Assemblies/Apps

, 27 Jan 2008
Rate this:
Please Sign up or sign in to vote.
How to use CodeDOM and CompilerServices to dynamically create assemblies/apps.

Introduction

This is a bit of a strange article, and may not be that useful, but I think it's a very interesting subject that some will probably not even be aware of. This article will cover some of the less known namespaces within .NET. Such as System.CodeDom and System.CodeDom.Compiler. What I will be demonstrating in this article, is just how neat these namespaces are and what can be done with them. Specifically, I will be demonstrating that we are able to build entirely new source code files at runtime using the System.CodeDom namespace, and the use of the System.CodeDom.Compiler namespace classes to even compile this newly created source code into a runnable application. This will all be created at runtime. My aim for this article is to provide a simple introduction into these two namespaces; you will not be an expert at the end of this article, but will have been exposed to enough, to realise what these two namespaces allow you to achieve.

Why Would I Want to Create New Source Code and Applications at Runtime

Well, the reason that I started looking into this was dynamic code generation for Data Access Layer (DAL) /Business Access Layer (BAL) code based on an initial schema. So that's one possible area where it may be useful to create code at runtime; basically, have an application create a bunch of auto generated source code files that can then be used within another project. That's just where we (at work) found a use for this stuff.

This led me onto investigating the System.CodeDom.Compiler namespace classes, and as such, I thought I would spend a bit of time talking about the possibilities that are available by using these classes.

The rest of this article will be split roughly between a discussion about the System.CodeDom namespace and the System.CodeDom.Compiler namespace. And finally, a short discussion of the attached demo application.

System.CodeDom

The System.CodeDom namespace contains classes, interfaces, and enumerations that can be used to create source code at runtime. The general idea is that a newly constructed Document Object Model is being created, where methods, constructors using directives, variables, are all creatable using the System.CodeDom namespace. Where CodeDOM really comes into its own is that it is language agnostic, and simply provides a CodeCompileUnit which can then be used by the System.CodeDom.Compiler namespace which uses this CodeCompileUnit to create the source code in any of the .NET languages.

I shall demonstrate a few examples of using the CodeDOM.

Creating Namespaces

CodeNamespace ns = new CodeNamespace("TestApp");
ns.Imports.Add(new CodeNamespaceImport("System"));
ns.Imports.Add(new CodeNamespaceImport("System.Text"));
compileUnit.Namespaces.Add(ns);

Creating a Class

CodeTypeDeclaration ctd = new CodeTypeDeclaration(Name);
ctd.IsClass = true;
ctd.Attributes = MemberAttributes.Public;
compileUnit.Namespaces[0].Types.Add(ctd);

Creating a Main Method

CodeEntryPointMethod method = new CodeEntryPointMethod();
method.Attributes = MemberAttributes.Public |
MemberAttributes.Static;
ctd.Members.Add(method);

Obviously, this only gives you a very small example of what CodeDOM is like to work with. I have to say the syntax is very verbose, but the fact that you can create any .NET source from CodeDOM makes it quite appealing. There are also some good wrappers around CodeDOM which shorten the syntax. I have included a list of related articles at the bottom of this article, should you wish to read around this subject a bit more.

System.CodeDom.Compiler

If you want to be able to use the System.CodeDom.Compiler namespace to compile the result of building a CodeDOM object, you need to make sure that wherever we build our CodeDOM object (using the syntax as shown above), we return a CodeCompileUnit. It is by using this CodeCompileUnit that we are able to use the System.CodeDom.Compiler namespace, to create the source code in any of the .NET languages.

For example, this excerpt of the demo application code shows how we built a new source code file using the System.CodeDom and System.CodeDom.Compiler namespaces.

/// <summary>
/// Generates the source code by calling the
/// <see cref="CodeDomExample">GenerateCode</see> method
/// </summary>
private void picGenerate_Click(object sender, EventArgs e)
{

    CodeDomProvider domProvider = (CodeDomProvider)getCodeEditorSyntaxOrProvdiderForLanguage
        (cmbPickLanguage.SelectedItem.ToString(),false);

    //create the code
    cde.GenerateCode(domProvider, cde.BuildSimpleAdder());
    // Display the generated source code file
    using (StreamReader sr = new StreamReader(getSourceFileName(domProvider)))
    {
        txtCode.Document.Text = sr.ReadToEnd();
        sr.Close();
    }
}

....
....

/// <summary>
/// Returns either a SyntaxLanguage or a CodeDomProvider based on the selectedLanguage
/// </summary>
/// <param name="selectedLanguage">A string
/// respresenting the selected language</param>
/// <param name="syntaxObjectRequired">True if this method
/// should return a SyntaxLanguage object</param>
/// <returns></returns>
private object getCodeEditorSyntaxOrProvdiderForLanguage(string selectedLanguage, 
                                                         bool syntaxObjectRequired)
{
    switch (selectedLanguage)
    {
        case "CSharp":
            if (syntaxObjectRequired)
                return SyntaxLanguage.CSharp;
            else
                return CodeDomProvider.CreateProvider("CSharp");
        case "Visual Basic":
            if (syntaxObjectRequired)
                return SyntaxLanguage.VBNET;
            else
                return CodeDomProvider.CreateProvider("VisualBasic");
        default:
            if (syntaxObjectRequired)
                return SyntaxLanguage.CSharp;
            else
                return CodeDomProvider.CreateProvider("CSharp");
    }
}

....
....

/// <summary>
/// Returns a string respresenting the filename for the generated app, which is based
/// on the extension of the current
/// <see cref="CodeDomProvider">CodeDomProvider</see>
/// </summary>
/// <param name="domProvider">The current
/// <see cref="CodeDomProvider">CodeDomProvider</see></param>
/// <returns>A string respresenting the filename for the generated app</returns>
private string getSourceFileName(CodeDomProvider domProvider)
{
    if (domProvider.FileExtension[0] == '.')
    {
        return "app" + domProvider.FileExtension;
    }
    else
    {
        return "app." + domProvider.FileExtension;
    }
}

....
....

/// <summary>
/// Uses the CodeDom classes to create a simply
/// built in run time source code file (graph). And returns
/// a <see cref="CodeCompileUnit">CodeCompileUnit</see>
/// that can be used by the <see cref="CompilerParameters">
/// CompilerParameters</see> to build an actual 
/// <see cref="Assembly">Assembly</see>
/// </summary>
/// <returns></returns>
public CodeCompileUnit BuildSimpleAdder()
{

    CodeCompileUnit compileUnit = new CodeCompileUnit();
    compileUnit.Namespaces.Add(InitializeNameSpace("TestApp"));
    CodeTypeDeclaration ctd = CreateClass("SimplePrint");
    // Add the class to the namespace
    compileUnit.Namespaces[0].Types.Add(ctd);
    CodeEntryPointMethod mtd = CreateMainMethod();
    ctd.Members.Add(mtd);
    CodeVariableDeclarationStatement VariableDeclaration =
        DeclareVariables(typeof(StringBuilder), "sbMessage");
    // Add the variable declaration to the method 
    mtd.Statements.Add(VariableDeclaration);
    //and print the results
    mtd.Statements.Add(new CodeSnippetExpression(
        "Console.WriteLine(sbMessage.Append(\"the result of adding (1+2) is \" + " +
        "(1+2).ToString()))"));
    // Build a call to System.Console.ReadLine, to keep console window alive to see results
    CodeTypeReferenceExpression csSystemConsoleType = 
        new CodeTypeReferenceExpression("System.Console");
    CodeMethodInvokeExpression csReadLine = 
        new CodeMethodInvokeExpression(csSystemConsoleType, "ReadLine");

    //// Add the ReadLine statement.
    mtd.Statements.Add(csReadLine);

    //lastly return it all
    return compileUnit;
}

....
....

/// <summary>
/// Generates the code using either a CSharp or Visual Basic 
/// CodeDomProvider. This generated code uses the 
/// <see cref="CodeCompileUnit">CodeCompileUnit</see> that was created
/// by the BuildSimpleAdder method
/// </summary>
/// <param name="domProvider">The CodeDomProvider to use,
/// CSharp or Visual Basic CodeDomProviders in our case</param>
/// <param name="compileunit">A 
/// <see cref="CodeCompileUnit">CodeCompileUnit</see> that can be used by
/// the System.CodeDom.Compiler classes</param>
public void GenerateCode(CodeDomProvider domProvider, CodeCompileUnit compileunit)
{
    //builds the source based on the selected language
    String srcFile;
    if (domProvider.FileExtension[0] == '.')
    {
        srcFile = "app" + domProvider.FileExtension;
    }
    else
    {
        srcFile = "app." + domProvider.FileExtension;
    }
    //we want a nice indemtable output file
    using (IndentedTextWriter tw = 
           new IndentedTextWriter(new StreamWriter(srcFile, false), "    "))
    {
        // Create the source code
        domProvider.GenerateCodeFromCompileUnit(compileunit, tw, 
                    new CodeGeneratorOptions());
        tw.Close();
    }
}

Doing this is enough to create a new source code file, in any of the .NET languages. This is all thanks to the CodeDomProvider class, which is able to create providers for all of the .NET languages. So providing we use the relevant CodeDomProvider for CodeCompileUnit that came out of using CodeDOM, we can generat source code in any of the .NET languages. Neat, huh?

So what have we got so far? Well, we created a DOM representing a new class, which eventually gave us a CodeCompileUnit that we then used to create the relevant source code by using the specific CodeDomProvider class, for the language we wanted to generate.

So that's cool, we have a source code file. But at the top of this article, I also said that I would show you how to compile source code into an Assembly or an Exe. So let's continue to look at that.

Again, I think the best thing to show you is the relevant source code.

/// <summary>
/// Compile the source code by calling the
/// <see cref="CodeDomExample">Compile</see> method
/// </summary>
private void picCompile_Click(object sender, EventArgs e)
{
    CodeDomProvider domProvider = 
      (CodeDomProvider)getCodeEditorSyntaxOrProvdiderForLanguage(
       cmbPickLanguage.SelectedItem.ToString(), false);
    // Compile the source file into an executable output file.
    string srcFile = getSourceFileName(domProvider);
    CompilerResults cr = cde.Compile(domProvider,srcFile,"app.exe");
    string message = string.Empty;

    if (cr.Errors.Count > 0)
    {
        // Display compilation errors.
        message+= "Errors encountered while building " +
                        srcFile + " into " + cr.PathToAssembly + ": \r\n\n";
        foreach (CompilerError ce in cr.Errors)
            message +=ce.ToString() + "\r\n";
        picRun.Enabled = false;
        MessageBox.Show(message);
    }
    else
    {
        message += "Source " + srcFile + " built into " +
                        cr.PathToAssembly + " with no errors.";
        picRun.Enabled = true;
        MessageBox.Show(message);
    }
}

....
....

/// <summary>
/// Returns either a SyntaxLanguage or a CodeDomProvider
/// based on the selectedLanguage
/// </summary>
/// <param name="selectedLanguage">A string
/// respresenting the selected language</param>
/// <param name="syntaxObjectRequired">True if this
/// method should return a SyntaxLanguage object</param>
/// <returns></returns>
private object getCodeEditorSyntaxOrProvdiderForLanguage(string selectedLanguage, 
                                                         bool syntaxObjectRequired)
{
    switch (selectedLanguage)
    {
        case "CSharp":
            if (syntaxObjectRequired)
                return SyntaxLanguage.CSharp;
            else
                return CodeDomProvider.CreateProvider("CSharp");
        case "Visual Basic":
            if (syntaxObjectRequired)
                return SyntaxLanguage.VBNET;
            else
                return CodeDomProvider.CreateProvider("VisualBasic");
        default:
            if (syntaxObjectRequired)
                return SyntaxLanguage.CSharp;
            else
                return CodeDomProvider.CreateProvider("CSharp");
    }
}
....
....
/// <summary>
/// Returns a string respresenting the filename for the generated app, which is based
/// on the extension of the current <see cref="CodeDomProvider">CodeDomProvider</see>
/// </summary>
/// <param name="domProvider">The current
/// <see cref="CodeDomProvider">CodeDomProvider</see></param>
/// <returns>A string respresenting the filename for the generated app</returns>
private string getSourceFileName(CodeDomProvider domProvider)
{
    if (domProvider.FileExtension[0] == '.')
    {
        return "app" + domProvider.FileExtension;
    }
    else
    {
        return "app." + domProvider.FileExtension;
    }
}
....
....
/// <summary>
/// Uses the <see cref="CompilerParameters">CompilerParameters</see>
/// to compile the the source file, creating the output file
/// </summary>
/// <param name="domProvider">The CodeDomProvider to use,
/// CSharp or Visual Basic CodeDomProviders in our case</param>
/// <param name="srcFile">The source file</param>
/// <param name="exeFile">The name for the output file</param>
/// <returns>The actual <see cref="CompilerResults">CompilerResults</see>
/// which will holds the compiled <see cref="Assembly">Assembly</see></returns>
public CompilerResults Compile(CodeDomProvider domProvider, String srcFile,String exeFile)
{
    // Configure a CompilerParameters that links System.dll
    // and produces the specified executable file.
    String[] referenceAssemblies = { "System.dll" };
    CompilerParameters cp = new CompilerParameters(referenceAssemblies,exeFile, false);
    //make sure we create an EXE not a Dll, and then compile
    cp.GenerateExecutable = true;
    CompilerResults compiledResults = domProvider.CompileAssemblyFromFile(cp, srcFile);
    return compiledResults;
}

And that is enough to get us a EXE created for the source code that we created earlier. Remember, this is all being done at runtime. I think that's pretty cool actually. Create a new source code and compile and run it at runtime. That's neat.

The Demo Application

Anyway, let's just have a quick chat about the demo app. I use the fantastic Fireball code highlighter, available right here at CodeProject. And the basic program that I am trying to create at runtime is as follows:

Namespace TestApp {
    using System;
    using System.Text;
    
    
    Public Class SimplePrint {
        
        Public Static void Main() {
            System.Text.StringBuilder sbMessage = new System.Text.StringBuilder();
            Console.WriteLine(sbMessage.Append(
               "the result of adding (1+2) is " + (1+2).ToString()));
            System.Console.ReadLine();
        }
    }
}

Which when generated in Visual Basic .NET, looks as follows:

Option Strict Off
Option Explicit On

Imports System
Imports System.Text

Namespace TestApp
    
    Public Class SimplePrint
        
        Public Shared Sub Main()
            Dim sbMessage As System.Text.StringBuilder = _
                          New System.Text.StringBuilder
            Console.WriteLine(sbMessage.Append("the result of adding (1+2) is " + _
                                              (1+2).ToString()))
            System.Console.ReadLine
        End Sub
    End Class
End Namespace

And the demo application looks like this, where there are three buttons:

  • Generate button: generates the source code
  • Compile button: compiles the source code
  • Run: runs the newly compiled app

Here is a screenshot of the demo app, just after a generate and compile is performed, where the selected .NET language was Visual Basic:

And here is the actual newly created application running:

And that's about it. Like I say, you are by no means an expert from reading this, but I hope it has given you an idea about what can be done with these two very cool namespaces.

Other CodeDOM Resources

Future Work

I may end up elaborating on this article in the future to discuss how the process of code generation can be handled more efficiently using some of the Visual Studio SDK tools.

History

  • 27/01/08: Initial issue.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)
 
- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence
 
Both of these at Sussex University UK.
 
Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions

 
QuestionOption strict PinmemberMarla Sukesh22-Feb-13 1:20 
GeneralSyntax Problem PinmemberMegaGigsLtd29-Aug-10 10:07 
QuestionCan not build extension methods Pinmemberquychau6-Oct-09 22:13 
AnswerRe: Can not build extension methods PinmvpSacha Barber11-Oct-09 14:46 
GeneralNice intro PinmemberSyed Mehroz Alam31-Jan-08 0:15 
GeneralRe: Nice intro PinmvpSacha Barber31-Jan-08 1:06 
GeneralThanks, Sacha PinmemberBillWoodruff28-Jan-08 15:00 
GeneralRe: Thanks, Sacha PinmvpSacha Barber28-Jan-08 20:53 
GeneralCode Dom PinmemberBob Carter28-Jan-08 4:09 
GeneralRe: Code Dom PinmvpSacha Barber28-Jan-08 5:09 
GeneralNice Article PinmvpKarl Shifflett27-Jan-08 13:52 
GeneralRe: Nice Article PinmvpSacha Barber28-Jan-08 5:09 
GeneralNice demo PinmvpDaniel Vaughan27-Jan-08 12:48 
GeneralRe: Nice demo PinmvpSacha Barber28-Jan-08 5:09 
GeneralExcellent PinmemberPaul Conrad27-Jan-08 6:51 
GeneralRe: Excellent PinmvpSacha Barber27-Jan-08 9:45 
GeneralRe: Excellent PinmemberPaul Conrad27-Jan-08 9:55 
GeneralRe: Excellent PinmvpSacha Barber28-Jan-08 23:19 
GeneralA couple additional resources PinprotectorMarc Clifton27-Jan-08 3:00 
GeneralRe: A couple additional resources PinmvpSacha Barber27-Jan-08 4:28 
QuestionWhy am I not surprised? PinmemberMustafa Ismail Mustafa27-Jan-08 2:00 
AnswerRe: Why am I not surprised? PinmvpSacha Barber27-Jan-08 2:41 
GeneralRe: Why am I not surprised? PinmvpDaniel Vaughan27-Jan-08 12:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 27 Jan 2008
Article Copyright 2008 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid