Recently I was looking for a solution for dynamic code compiling. I came cross Microsoft Roslyn and had a test. It’s perfect solution for dynamic code compilation and execution. You will have to have .net 4.0, Visual Studio 2010 sp1, Visual Studio 2010 SDK sp1, and Microsoft Roslyn installed in order to make this happen.
Here is my test code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Reflection.Emit; using System.Threading; using Roslyn.Compilers; using Roslyn.Compilers.CSharp; using Roslyn.Services; using Roslyn.Services.CSharp; namespace ConsoleApplication1 { class MyTest { static void Main(string[] args) { SyntaxTree tree = SyntaxTree.ParseCompilationUnit( @"using System; using System.Collections.Generic; using System.Text; namespace Hello { public class HelloClass { public static void Main() { Console.WriteLine(""Main: Wow!...""); } public static void Test() { Console.WriteLine(""Test1: Wow1!...""); } } }"); var compilation = Compilation.Create("Hello") .AddReferences(new AssemblyNameReference("mscorlib")) .AddSyntaxTrees(tree); ModuleBuilder helloModuleBuilder = AppDomain.CurrentDomain .DefineDynamicAssembly(new AssemblyName("HelloAssembly"), AssemblyBuilderAccess.RunAndCollect) .DefineDynamicModule("HelloModule"); var result = compilation.Emit(helloModuleBuilder); if (!result.Success) { foreach(var d in result.Diagnostics) { Console.WriteLine(d); } Console.WriteLine("Error. Press any key to exit"); Console.ReadKey(); return; } Type helloClass = helloModuleBuilder.GetType("Hello.HelloClass"); MethodInfo mainMethod = helloClass.GetMethod("Main"); MethodInfo testMethod = helloClass.GetMethod("Test"); mainMethod.Invoke(null, null); object helloObject = Activator.CreateInstance(helloClass, null, null); testMethod.Invoke(helloObject, null); Console.WriteLine("done"); Console.ReadKey(); } } }
The really cool thing is the line highlighted above, AssemblyBuilderAccess.RunAndCollect. This is a new value introduced in .net 4.0 in which it allows an loaded assembly to be unloaded where it’s deemed to be impossible before. This definitely very helpful in application designs. I intended to load it into SQL Server 2012 environment and run such feature in CLR procedure and functions, but failed due to the fact that many dependent assemblies are not supported in the integrated environment. Microsoft Roslyn now is still on CTP, but will be release with Visual Studio 2012. I realy look forward to that and hope it can be supported within SQL Server 2012 integrated environment.