Advertisement
agmike

RuntimeCodeCompiler

Apr 15th, 2014
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | None | 0 0
  1. using System;
  2. using System.CodeDom.Compiler;
  3. using System.Reflection;
  4. using System.Text;
  5.  
  6. namespace DPlot
  7. {
  8.     public static class RuntimeCodeCompiler
  9.     {
  10.         const string ScriptPrefix = @"
  11. using System;
  12. using Replotter;
  13.  
  14. public static class Script
  15. {
  16.    public static void Main(this CommandContext ctx)
  17.    {
  18. ";
  19.         const string ScriptSufix = @"
  20.    }
  21. }";
  22.  
  23.         public static Assembly CompileCode(string code, out string compilerOutput)
  24.         {
  25.             Assembly assembly = null;
  26.             compilerOutput = "";
  27.             try {
  28.  
  29.                     var provider = CodeDomProvider.CreateProvider("CSharp");
  30.  
  31.                     var cp = new CompilerParameters {
  32.                         GenerateExecutable = false,
  33.                         GenerateInMemory = true,
  34.                         TreatWarningsAsErrors = false
  35.                     };
  36.  
  37.                     // Add references to all the assemblies we might need.
  38.                     var executingAssembly = Assembly.GetExecutingAssembly();
  39.                     cp.ReferencedAssemblies.Add(executingAssembly.Location);
  40.                     cp.ReferencedAssemblies.Add("System.Core.dll");
  41.                     cp.ReferencedAssemblies.Add("System.dll");
  42.                     //foreach (AssemblyName assemblyName in executingAssembly.GetReferencedAssemblies())
  43.                         //cp.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);
  44.  
  45.                     // Invoke compilation of the source file.
  46.                     var cr = provider.CompileAssemblyFromSource(cp, ScriptPrefix + code + ScriptSufix);
  47.  
  48.                     if (cr.Errors.Count > 0) {
  49.                         // Display compilation errors.
  50.                         StringBuilder builder = new StringBuilder();
  51.                         foreach (CompilerError ce in cr.Errors) {
  52.                             builder.Append(ce.ToString());
  53.                             builder.Append("\n");
  54.                         }
  55.                         compilerOutput = builder.ToString();
  56.                     }
  57.                     else
  58.                         assembly = cr.CompiledAssembly;
  59.             }
  60.             catch (Exception e) {
  61.                 compilerOutput = e.ToString();
  62.             }
  63.             return assembly;
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement