0

Example:

Condition:

IF A > B THEN

PRINT B

ELSE

PRINT A

This condition is written as a string in coloumn of the table in SQL.

I want to fetch this condition from the table and convert this condition to the C# Code as

If(A > B )

{

print B...........

}

else

{

print A...........

}

Where A and B are the Dynamic values passed from the solution Suppose A=10 and B=20 then

execute the code which will return 10 or 20 base on the condition.

3 Answers3

0

It depends a bit on what you want to do with this, but one possible way to solve this is to use the Microsoft.JScript assembly. Although JScript is a tad different from c#, much of the syntax is the same or similar. What's more, JScript is based on a global scope, so no need to wrap the code you generated in a method either.

In steps you would do the following:

  • modify the code you got from the database to be valid JScript (using string methods and probably a lot of Regex)
  • Get an instance of a JScript compiler
  • Compile the code to an assembly
  • Run the assembly with some inputs.

But since this is rather heavy on the creation of types/assemblies (that might not be unloadable), I would recommend (using the above method) compiling a simple wrapper for the jscript eval() function, and simply providing your jscript to that code. Then you won't have to worry about compilation etc.

Be carefull when creating dynamic code though. The whole of the .Net framework would be avaliable for use, so unless you absolutely trust the source of the conditions, or restricted the compiled assembly, nasty stuff™ could happen.

Captain Coder
  • 747
  • 4
  • 12
0

You can use Emit or CodeDOM to generate dynamic code but it's better say why you saved them so may be there is better way to reproduce them.

0

There is an answer here on SO that explain how to reuse the Javascript engine DLL that's shipped with every Windows installation: parse and execute JS by C#.

It has a sample with a function that you could adapt to your need.

Community
  • 1
  • 1
Simon Mourier
  • 117,251
  • 17
  • 221
  • 269