Click here to Skip to main content
15,867,141 members
Articles / Programming Languages / Javascript

Evaluate Expressions from C# using JavaScript's Eval() Function

Rate me:
Please Sign up or sign in to vote.
4.70/5 (13 votes)
5 Dec 2009CPOL2 min read 68.9K   749   27   8
This article describes how to wrap Eval() in a tiny JScript class, compile it into an assembly and call it from C# to evaluate expressions at runtime.
Image 1

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().

C#
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:

C#
// Ask user to enter expression.
Console.WriteLine("Enter an expression:");
string expression = Console.ReadLine();

// Evaluate expression.
MB.JsEvaluator.Evaluator evaluator = new MB.JsEvaluator.Evaluator();
string result = evaluator.Eval(expression);

// Print 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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Phi International
Canada Canada
Grew up in Amsterdam, now living in downtown Vancouver. There are definitely more mountains here.

My first internship was with the first company in the Netherlands to teach C++ (www.datasim.nl). During this internship I got to know Object Oriented Design, which kept my interest until this day. In the mean time, I have worked for different companies in the Netherlands and Canada. I have done most of my recent work in C#, developing Database/Web/Desktop applications.

I am currently working as a freelance Software Developer for PHI International in Amsterdam.

The CodeProject rocks!

Comments and Discussions

 
QuestionVariables definition Pin
Radox3-Oct-13 23:19
Radox3-Oct-13 23:19 
AnswerRe: Variables definition Pin
Martijn Boeker4-Oct-13 9:00
Martijn Boeker4-Oct-13 9:00 
GeneralMy vote of 5 Pin
Clifford Nelson9-Feb-12 7:19
Clifford Nelson9-Feb-12 7:19 
GeneralMy vote of 5 Pin
linda831027-Sep-10 23:14
linda831027-Sep-10 23:14 
GeneralThanks a lot Pin
eijiyq10-Dec-09 21:50
eijiyq10-Dec-09 21:50 
General5. Pin
ring_06-Dec-09 18:15
ring_06-Dec-09 18:15 
General5 From me Pin
Moim Hossain6-Dec-09 0:07
Moim Hossain6-Dec-09 0:07 
Useful stuff mate. Thanks

Moim Hossain
R&D Project Manager
BlueCielo ECM Solutions BV

GeneralRe: 5 From me Pin
Martijn Boeker6-Dec-09 9:42
Martijn Boeker6-Dec-09 9:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.