On The Fly Code Compilation & Execution in C#

by Chinmay 6. August 2010 06:12

I have moved to a different position since last one month and I get to do some R&D and I am trying to coming up with tools which can help Developers to finish their tasks as soon as possible without facing any road blocks.

I was trying to figure out a way to compile and execute code on the fly without storing the output to disk, and after looking at some examples on MSDN I came up with this code.

namespace CrmXpress.CodeDom

{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

public partial class CodeDomForm : Form
{
public CodeDomForm()
{
InitializeComponent();
}

private void AddButton_Click(object sender, EventArgs e)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
ICodeCompiler ICC = provider.CreateCompiler();

// You have to add all the valid references here i.e. all the assemblies which you are going to use in your code
var parameters = new CompilerParameters(new[] { "System.Windows.Forms.dll" });

// Generate the assembly in memory
parameters.GenerateInMemory = true;

// This is a class stub
  string code = "namespace Skynet{class XXX{public void Execute(){{0}}}}";

// Replace the placeholder with actual code that you have written in CodeTextBox
code = code.Replace("{0}", this.CodeTextBox.Text);

// Compile the code
CompilerResults result = ICC.CompileAssemblyFromSource(parameters, code);

// If there are any errors, display a message to end user
if (result.Errors.Count > 0)
{
MessageBox.Show(result.Errors[0].ErrorText);
}
else
{
// Otherwise using reflection, create instance of XXX class in memory and call the Execute method
Assembly assmebly = result.CompiledAssembly;
  object target = assmebly.CreateInstance("Skynet.XXX");
target.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, target, null);

// you can use this sample code to run minor test. If you copy this code right, on click of Add button you should see : "GFYS : 11".
/*int x = 5;
int y = 6;
System.Windows.Forms.MessageBox.Show("GFYS : " + (x + y));*/
}

}

}
}

Comments/Questions are welcome.

Tags: , , ,

.Net | Tutorial | C# | Code

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Me

I've been working on CRM since last 6 years and I am mesmerized by the sheer capabilities of this product. This blog is a medium via which I will try to share my various experiences on CRM, .Net, DHTML and a lot more. If you like my blog please leave a comment and/or rating on the posts.

#1
#2
#3
Questions Answered
Overall Points
quot;


Subscribe in a reader

Calendar

<<  May 2013  >>
MoTuWeThFrSaSu
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

View posts in large calendar