Thursday, March 3, 2016

Execute arbitrary c# code at runtime, like a script

Here, we are compiling the c# code at runtime, and executing the result directly from in memory. The class is instantiated, and the method is called dynamically. The result, in this case a string is read back after the code executes

using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

        public string RunCodeSnippet(string sCSharpCodeSnippet)
        {
            string sCSharpSource =
            @"using System;
              namespace com.mycomp
              {
                  public class MyClass
                  {
                     public string RunCSharpScript()
                     {
                        return(" + sCSharpCodeSnippet + @");
                     }
                  }
              }";

            Dictionary<string, string> csProviderOptions = new Dictionary<string, string> { { "CompilerVersion", "v3.5" } };
            CSharpCodeProvider csProvider = new CSharpCodeProvider(csProviderOptions);

            CompilerParameters csCompilerParams = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false };

            CompilerResults csCompresults = csProvider.CompileAssemblyFromSource(csCompilerParams, sCSharpSource);


            if (csCompresults.Errors.HasErrors)
            {
                throw new Exception("Compile Error! - " + csCompresults.Errors[0] + Environment.NewLine + sCSharpSource);
            }

            object o = csCompresults.CompiledAssembly.CreateInstance("com.mycomp.MyClass");
            MethodInfo mi = o.GetType().GetMethod("RunCSharpScript");
            var dataout = mi.Invoke(o, null);
            return (string)dataout;
        }

Sample Usage:
            try
            {
                string sResult = RunCodeSnippet("\"The time now is : \" + DateTime.Now.ToString()");
            }
            catch (Exception ex)
            {
                sError = ex.Message;
            }

No comments:

Turn on Windows 11 Fast Boot

If windows starting is slow, to enable windows 11 fast startup/boot,  Press Windows + R, type powercfg.cpl, and hit Enter.  This will direct...