Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.CodeDom.Compiler;
- using System.Reflection;
- using System.Text;
- namespace DPlot
- {
- public static class RuntimeCodeCompiler
- {
- const string ScriptPrefix = @"
- using System;
- using Replotter;
- public static class Script
- {
- public static void Main(this CommandContext ctx)
- {
- ";
- const string ScriptSufix = @"
- }
- }";
- public static Assembly CompileCode(string code, out string compilerOutput)
- {
- Assembly assembly = null;
- compilerOutput = "";
- try {
- var provider = CodeDomProvider.CreateProvider("CSharp");
- var cp = new CompilerParameters {
- GenerateExecutable = false,
- GenerateInMemory = true,
- TreatWarningsAsErrors = false
- };
- // Add references to all the assemblies we might need.
- var executingAssembly = Assembly.GetExecutingAssembly();
- cp.ReferencedAssemblies.Add(executingAssembly.Location);
- cp.ReferencedAssemblies.Add("System.Core.dll");
- cp.ReferencedAssemblies.Add("System.dll");
- //foreach (AssemblyName assemblyName in executingAssembly.GetReferencedAssemblies())
- //cp.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);
- // Invoke compilation of the source file.
- var cr = provider.CompileAssemblyFromSource(cp, ScriptPrefix + code + ScriptSufix);
- if (cr.Errors.Count > 0) {
- // Display compilation errors.
- StringBuilder builder = new StringBuilder();
- foreach (CompilerError ce in cr.Errors) {
- builder.Append(ce.ToString());
- builder.Append("\n");
- }
- compilerOutput = builder.ToString();
- }
- else
- assembly = cr.CompiledAssembly;
- }
- catch (Exception e) {
- compilerOutput = e.ToString();
- }
- return assembly;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement