adhokshaj

Compile C# On the Fly

Aug 16th, 2012
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.78 KB | None | 0 0
  1. using System;
  2. using System.CodeDom.Compiler;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using Microsoft.CSharp;
  8.  
  9. namespace Adhokshaj
  10. {
  11.     public static class DynamicCompiler
  12.     {
  13.         /// <summary>
  14.         /// Executes the passed code on the fly
  15.         /// </summary>
  16.         /// <param name="code">The code that should be executed</param>
  17.         /// <param name="libraries">Paths to libraries the passed code uses</param>
  18.         /// <param name="usings">Namespaces the code needs</param>
  19.         /// <param name="compilerVersion">The version of the used compiler. Default version is 3.5</param>
  20.         /// <returns>The result of the executed code. Any return statements inside the code will set the result object. If the code does not contain a return statement, result will be null</returns>
  21.  
  22.         public static object Execute(string code, string[] libraries, string[] usings, string compilerVersion = "v3.5")
  23.         {
  24.             CSharpCodeProvider cscp = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", compilerVersion } });
  25.             CompilerParameters cp = new CompilerParameters(libraries);
  26.             cp.GenerateExecutable = false;
  27.             cp.GenerateInMemory = true;
  28.             cp.IncludeDebugInformation = false;
  29.             cp.OutputAssembly = "TempAssembly";
  30.             CompilerResults cr = cscp.CompileAssemblyFromSource(cp, BuildMethod(code, usings));
  31.             if (cr.Errors.HasErrors)
  32.             {
  33.                 string errorString = "";
  34.                 foreach (CompilerError error in cr.Errors)
  35.                 {
  36.                     errorString += "- " + error.ErrorText + "\n\r";
  37.                 }
  38.                 throw new ArgumentException("The code is invalid:\n\r" + errorString);
  39.             }
  40.             MethodInfo mi = cr.CompiledAssembly.GetType("TempProj.TempClass").GetMethod("TempMethod", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
  41.             object result = null;
  42.             result = mi.Invoke(null, null);
  43.             return result;
  44.         }
  45.        
  46.         private static string BuildMethod(string code, string[] usings)
  47.         {
  48.             string fullCode = "";
  49.             if (usings != null)
  50.             {
  51.                 foreach (string s in usings)
  52.                 {
  53.                     fullCode += "using " + s + ";\n\r";
  54.                 }
  55.             }
  56.             fullCode += "\n\rnamespace TempProj\n\r{\n\rpublic static class TempClass\n\r{\n\rpublic static object TempMethod()\n\r{\n\r";
  57.             if (!code.Contains("return"))
  58.                 code += "return null;\n\r";
  59.             fullCode += code;
  60.             fullCode += "\n\r}\n\r}\n\r}";
  61.             return fullCode;
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment