c# – using CSharpCodeProvider to compile strings – Education Career Blog

Trying to figure out how to exploit the CSharpCodeProvider to compile string data at runtime.

In xml, i have what will amount to a predicate condition stored in a string.

I want to be able to, within the current context, execute and get the result of these statements.

for instance when
<Condition>Value=="ABCD1234"</Condition> is read and executed, it should look in the current object scope for value and return true or false based on the evaluation of the statement.

I think i’m going the right direction with CSharpCodeProvider, however all the examples i can find relate to compiling to a .DLL or .EXE, i really just want to compile in memory so i can perform the comparison and return true or false to another part of the app.

Any ideas as to how best to approach this? is CSharpCodeProvider even the best tool for the job?

,

I would highly recommend using FLEE for something like this. It doesn’t know native C# but it has the ability to parse and execute a reasonable subset of functions that looks like it’d be suitable for your use.

I’ve used FLEE on many occasions and found it to be easy to use and plenty fast enough.

,

I would personally rather create a small DSL (domain-specific language) instead of compiling such strings. The problem is that mixing this together into some source code that is compiled opens the door to injection attacks, and checking the syntax is difficult as well. Creating a small parser for simple expressions and predicates is actually pretty easy, so if you don’t depend on LINQ and whatever to work in your conditions then you may be better of with the DSL route.

To get an impression of what I’m talking about, I invite you to have a look at my GOLD Parser Engine which is made for jobs like this: http://code.google.com/p/bsn-goldparser/

The output of the parsing process is a semantic AST (abstract syntax tree), which can then be written to perform an “interpreted” evaluation on the fly or to create MSIL code, so that you get the benefit of fast compiled (JITed) code as well with full control over what is happening.

,

CSharpCodeProvider might be overkill. If your conditions will be basic logical operators (e.g. equals, greater/less than) you may be better off building a few delegates and writing a simple parser to execute the condition. Your parser will determine which operator is used and execute the appropriate delegate:

delegate bool equalsDel(string s1, string s2)
equalsDel = (s1, s2) => {return sq == s2;}
//Get your strings from the file and invoke the delegate
return equalsDel(s1, s2);

Look into the Visitor pattern for ideas on how to write a parser/Visitor that will determine the operator and execute the appropriate delegate. You might be able to get creative with Func<T> to create an efficient system with not much coding.

Leave a Comment