c# CODE TO EXECUTE A STRING AS SNIPPET

// CODE TO EXECUTE A STRING AS SNIPPET
            /*var watch = System.Diagnostics.Stopwatch.StartNew();
            string sourceTemplate =
            @"using System;
              using System.Windows.Forms;
              namespace Foo {
                    public static class Bar {
                    public static void Execute() {
                        @Placeholder
                    }
              }
              }";

            string snippet = "int i = 2; int j = 3; int result = i + j; MessageBox.Show(result.ToString());";
            string sourceCode = sourceTemplate.Replace("@Placeholder", snippet);
            CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(sourceCode);

            using (CSharpCodeProvider provider =
                new CSharpCodeProvider(new Dictionary<String, String> { { "CompilerVersion", "v3.5" } }))
            {
                CompilerParameters parameters = new CompilerParameters();
                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                parameters.GenerateExecutable = false;
                parameters.GenerateInMemory = true;
                parameters.IncludeDebugInformation = false;

                CompilerResults results = provider.CompileAssemblyFromDom(parameters, snippetCompileUnit);

                if (!results.Errors.HasErrors)
                {
                    Type type = results.CompiledAssembly.GetType("Foo.Bar");
                    MethodInfo method = type.GetMethod("Execute");
                    method.Invoke(null, new object[] { });
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CompilerError compilerError in results.Errors)
                        sb.AppendFormat("Error in line {0}:\n\n{1}", compilerError.Line, compilerError.ErrorText);
                    MessageBox.Show(sb.ToString(), "Compiler Error");
                }
                watch.Stop();
                MessageBox.Show("Total Time Taken:" + watch.ElapsedMilliseconds);

            }*/

Comments