Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Enterprise Development » Dynamic Code Generation and Code Compilation

Dynamic Code Generation and Code Compilation

This is a simple application for generating the code dynamically and compiling it dynamically.

Page Views : 4979
Downloads : 56
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
HelloWorldGenerate.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

This is a simple application for generating the code dynamically and compiling it dynamically. I have given two classes, GenerateClass, which generates a class on the fly, and RunClass, which compiles the generated class.

For dynamic code generation and code compilation, we have the CodeDom technology. Before going into the sample, let me give you a short introduction to CodeDom. Some applications need the generation and or compilation of source code at run time. The .NET Framework SDK provides a standard mechanism called the Code Document Object Model(CodeDOM) that enables the output of the source code in multiple programming languagesat run time, based on the single model that represents the code to render. The CodeDom namespace of .NET provides:

1. A single model for rendering the source code. Therefore, we can extend the set of supported languages.
2. A way to represent source code in a language independent object model.
3. Programs can be dynamically created, compiled and executed at run time.

CodeDom architecture can conceptually represent most programming constructs. However there are several limitations to the current CodeDom implementation. A few to mention are variable declaration list, unsafe modifier, aliasing the namespaces, nested namespaces, and others. To represent the constructs that are not provided by CodeDom, we can make use of the Snippet classes. 

To talk about the dynamic code generation and compilation, I have chosen the traditional example, Hello World. I tried to generate a code that will look like the following.

namespace Samples
{
using System;
public class HelloWorld
{
public HelloWorld()
{
writeHelloWorld();
}
private void writeHelloWorld()
{
System.Console.WriteLine("Hello World!!");
}
public static void Main()
{
HelloWorld hw =
new HelloWorld();
}
}
}

Now let us see how to generate the code. To generate the code, we need to create IcodeGenerator and CsharpCodeProvider. Have a TextWriter to write the generated class. 

//output file name
string fileName = "HelloWorld.cs";
//text writer to write the code
TextWriter tw = new StreamWriter(new FileStream(fileName, FileMode.Create));
//code generator and code provider
ICodeGenerator codeGenerator = new CSharpCodeProvider().CreateGenerator();
CSharpCodeProvider cdp =
new CSharpCodeProvider();
codeGenerator = cdp.CreateGenerator();

Declare the namespace for the class and adds the includes to the class.

CodeNamespace Samples = new CodeNamespace("Samples");
Samples.Imports.Add(
new CodeNamespaceImport("System"));

Create the class.

CodeTypeDeclaration Class1 = new CodeTypeDeclaration("HelloWorld");
Samples.Types.Add(Class1);
Class1.IsClass =
true;

The constructor for the created class is 

CodeConstructor cc = new CodeConstructor();
cc.Attributes = MemberAttributes.Public;
cc.Statements.Add(mi1);
Class1.Members.Add(cc);

The method writeHelloWorld can be given as

CodeMemberMethod Method1 = new CodeMemberMethod();
Method1.Name = "writeHelloWorld";
Method1.ReturnType =
new CodeTypeReference(typeof(void));
//Method1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "text"));
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!!"));
Method1.Statements.Add(cs1);
Class1.Members.Add(Method1);

To create an executable, we should mention the entry point of the application. The method, Main is given as

CodeEntryPointMethod Start = new CodeEntryPointMethod();
Start.Statements.Add(
new CodeSnippetStatement("HelloWorld hw = new HelloWorld();"));
Class1.Members.Add(Start);

Finally generate the source code file.

codeGenerator.GenerateCodeFromNamespace(Samples, tw, null);

Now, let us see how to compile and run the code at run time. For this we need the ICodeCompiler.

ICodeCompiler cc = new CSharpCodeProvider().CreateCompiler();

Set all the compiler parameters that you want. Note if you want to compile an assembly, set the GenerateExecutable to false.

CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
//includes
cp.GenerateExecutable = true; //generate executable

After setting the parameters, compile the code and get the results. Check out for errors, if any.

CompilerResults cr = cc.CompileAssemblyFromFile(cp, fileName);
if(cr.Errors.HasErrors)
{
StringBuilder error =
new StringBuilder();
error.Append("Error Compiling Expression: ");
foreach (CompilerError err in cr.Errors)
{
error.AppendFormat("{0}\n", err.ErrorText);
}
throw new Exception("Error Compiling Expression: " + error.ToString());
}

The last step, get the assembly generated and create an instance to run.

Assembly a = cr.CompiledAssembly;
_Compiled = a.CreateInstance("Samples.HelloWorld");

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
mercy_gp
Mercy GP,Software Development Engineer,Dell International Services,Global Development Center,India.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.