Back to Insights

Evaluating C expressions within your HTML editor

So you need to embed and evaluate C# expressions within your html editor? How do you proceed?

Let's step back a moment and think about how any C# program works. We type in text (hopefully as C# code) and get whatever we typed compiled by the C# compiler to MSIL and the resulting assembly is converted to native code the first time it gets loaded. This is exactly the same process we want to mimic, here's an example:

 class Program
    {
        const string SnippetPattern = "{(.*)}";
        static void Main(string[] args)
        {
            string html = "<h2>{1 + 2}</h2>";
            Match m = Regex.Match(html, SnippetPattern);
            if (m.Success && m.Groups.Count > 0)
            {
                int result = EvaluateAs<int>(m.Groups[1].Value);
                html = Regex.Replace(html, SnippetPattern, Convert.ToString(result));
            }
        }
        public static T EvaluateAs<T>(string code)
        {
            CSharpCodeProvider cp = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters { CompilerOptions = "/t:library", GenerateInMemory = true };
            parameters.ReferencedAssemblies.Add("system.dll");
            string snippet = string.Format("using System; internal static class Evaluator {{ public static {0} Exec() {{ return {1}; }} }}", typeof(T).FullName, code);
            CompilerResults cr = cp.CompileAssemblyFromSource(parameters, snippet);
            if (cr.Errors.Count > 0)
            {
                throw new ApplicationException(cr.Errors[0].ErrorText);
            }
            Assembly a = cr.CompiledAssembly;
            Type t = a.GetType("Evaluator");
            MethodInfo mi = t.GetMethod("Exec");
            return (T)mi.Invoke(null, null);
        }
    }

Share