Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to compile and execute new code at runtime in .NET?

Note: Mathematical expression evaluation is not the focus of this question. I want to compile and execute new code at runtime in .NET. That being said...

I would like to allow the user to enter any equation, like the following, into a text box:

x = x / 2 * 0.07914
x = x^2 / 5

And have that equation applied to incoming data points. The incoming data points are represented by x and each data point is processed by the user-specified equation. I did this years ago, but I didn't like the solution because it required parsing the text of the equation for every calculation:

float ApplyEquation (string equation, float dataPoint)
{
    // parse the equation string and figure out how to do the math
    // lots of messy code here...
}

When you're processing boatloads of data points, this introduces quite a bit of overhead. I would like to be able to translate the equation into a function, on the fly, so that it only has to be parsed once. It would look something like this:

FunctionPointer foo = ConvertEquationToCode(equation);
....
x = foo(x);  // I could then apply the equation to my incoming data like this

Function ConvertEquationToCode would parse the equation and return a pointer to a function that applies the appropriate math.

The app would basically be writing new code at run time. Is this possible with .NET?

like image 300
raven Avatar asked Oct 24 '08 16:10

raven


People also ask

How .NET code is compiled and executed?

The . Net framework has one or more language compilers, such as Visual Basic, C#, Visual C++, JScript, or one of many third-party compilers such as an Eiffel, Perl, or COBOL compiler. Anyone of the compilers translates your source code into Microsoft Intermediate Language (MSIL) code.

Is it possible to dynamically compile and execute C# code fragments?

Yeah, the nice thing with CodeDOM is that it can generate the assembly for you in memory (as well as providing error messages and other info in an easily readable format). @Noldorin, The C# CodeDOM implementation doesn't actually generate an assembly in memory.

How is .NET code compiled?

Your source code is compiled into a byte code known as the common intermediate language (CIL) or MSIL (Microsoft Intermediate Language). Metadata from every class and every methods (and every other thing :O) is included in the PE header of the resulting executable (be it a dll or an exe).


3 Answers

Yes! Using methods found in the Microsoft.CSharp, System.CodeDom.Compiler, and System.Reflection name spaces. Here is a simple console app that compiles a class ("SomeClass") with one method ("Add42") and then allows you to invoke that method. This is a bare-bones example that I formatted down to prevent scroll bars from appearing in the code display. It is just to demonstrate compiling and using new code at run time.

using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Reflection;  namespace RuntimeCompilationTest {     class Program     {         static void Main(string[] args) {             string sourceCode = @"                 public class SomeClass {                     public int Add42 (int parameter) {                         return parameter += 42;                     }                 }";             var compParms = new CompilerParameters{                 GenerateExecutable = false,                  GenerateInMemory = true             };             var csProvider = new CSharpCodeProvider();             CompilerResults compilerResults =                  csProvider.CompileAssemblyFromSource(compParms, sourceCode);             object typeInstance =                  compilerResults.CompiledAssembly.CreateInstance("SomeClass");             MethodInfo mi = typeInstance.GetType().GetMethod("Add42");             int methodOutput =                  (int)mi.Invoke(typeInstance, new object[] { 1 });              Console.WriteLine(methodOutput);             Console.ReadLine();         }     } } 
like image 107
raven Avatar answered Sep 20 '22 20:09

raven


You might try this: Calculator.Net

It will evaluate a math expression.

From the posting it will support the following:

MathEvaluator eval = new MathEvaluator(); //basic math double result = eval.Evaluate("(2 + 1) * (1 + 2)"); //calling a function result = eval.Evaluate("sqrt(4)"); //evaluate trigonometric  result = eval.Evaluate("cos(pi * 45 / 180.0)"); //convert inches to feet result = eval.Evaluate("12 [in->ft]"); //use variable result = eval.Evaluate("answer * 10"); //add variable eval.Variables.Add("x", 10);             result = eval.Evaluate("x * 10"); 

Download Page And is distributed under the BSD license.

like image 32
Brian Schmitt Avatar answered Sep 20 '22 20:09

Brian Schmitt


Yes, definitely possible to have the user type C# into a text box, then compile that code and run it from within your app. We do that at my work to allow for custom business logic.

Here is an article (I haven't more than skimmed it) which should get you started:

http://www.c-sharpcorner.com/UploadFile/ChrisBlake/RunTimeCompiler12052005045037AM/RunTimeCompiler.aspx

like image 40
rice Avatar answered Sep 17 '22 20:09

rice