It is ridiculously simple to compile code dynamically using the .NET Framework. Most of the code is merely setting up the parameters you need to pass to the compiler. Once that is done, basically, you have a 2-liner on your hands. We are using the technique to provide formulas to a bidding system that we are working on. Essentially, the code looks like this:
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace AppUtils
{
public class Compiler
{
private static readonly CompilerParameters parameters;
static Compiler()
{
parameters = CreateCompilerParameters();
}
public static CompilerResults Compile(string code)
{
var provider = new CSharpCodeProvider();
return provider.CompileAssemblyFromSource(parameters, code);
}
private static CompilerParameters CreateCompilerParameters()
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
var options = new CompilerParameters
{GenerateInMemory = true, GenerateExecutable = false, IncludeDebugInformation = true};
foreach (Assembly loadedAssemblies in assemblies)
{
options.ReferencedAssemblies.Add(loadedAssemblies.Location);
foreach (AssemblyName reference in loadedAssemblies.GetReferencedAssemblies())
{
Assembly referencedAssembly = Assembly.Load(reference);
options.ReferencedAssemblies.Add(referencedAssembly.Location);
}
}
return options;
}
}
}
Our "formulas" are just code with a friendly name (e.g. "Turnkey Days + 1"). The extensibility points in our system are maintained by developers, so this is not a problem. However, in situations where I would want to provide the user the ability to enter formulas, I still think it would be easy to write some kind of pre-processor that could expand simple formulas into C# which could then be forwarded to the compiler at runtime.