Introduction
Sometimes in the life of a C# programmer, you may want to evaluate a non-hard-coded expression in C#. There are several ways to do this:
- Use Flee (Fast Lightweight Expression Evaluator)
- Write your own expression parser with or without the help of existing tools and/or libraries
- Generate C# code on the fly, compile it at runtime and use it through Reflection
- The solution described in this article
This article describes how to evaluate expressions from C# using JavaScript's eval()
method. This is a very simple method but it can support many different scenarios. For example, it can be used to evaluate mathematical expressions as well as boolean expression. It can also be used to process or generate strings.
The idea of this article is not unique. I found references to this idea in several user groups. However, I couldn't find an article describing it step by step.
Please note that this method may not be very secure. I recommend to use it only if the expressions being evaluated are somewhat controlled and not directly entered by just any user.
Using the Code
The JavaScript File
MB.JsEvaluator.js contains a very simple wrapper around a method that wraps around JavaScript's eval()
.
package MB.JsEvaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr, "unsafe");
}
}
}
Compiling the JavaScript File
CompileEvaluator.bat contains the command for compiling the .js file into a .NET assembly named "MB.JsEvaluator.dll". The batch file must be run from the Visual Studio command prompt. The source code already contains a copy of this assembly, so you don't have to do this.
REM Run from Visual Studio prompt.
jsc /target:library MB.JsEvaluator.js
Using the MB.JsEvaluator Assembly
In your project, you must reference both "MB.JsEvaluator.dll" and "Microsoft.JScript". The code below shows the meat of the very simple demo application:
Console.WriteLine("Enter an expression:");
string expression = Console.ReadLine();
MB.JsEvaluator.Evaluator evaluator = new MB.JsEvaluator.Evaluator();
string result = evaluator.Eval(expression);
Console.WriteLine("Result:");
Console.WriteLine(result);
How I Used This
In my application, I use this for evaluating boolean expressions. The user enters an expression that may contain 'and', 'or', and certain variable names. Before I feed the expression to JavaScript, I replace 'and' with '&&', 'or' with '||' and the variable names with literals. The security risks are low in my case, because the users entering the expressions will be the people configuring the system, which are employees of our company. Our application is also not a server application, so the worst thing that could happen is that the end user messes up his/her own computer.
I think Flee could also have been a viable option, but I didn't know about it during that time.
History
- 5 Dec 2009 - Initial version