Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 5 Dec 2009
Rate this:
Please Sign up or sign in to vote.
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.

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:

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

Share

About the Author

Martijn Boeker
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 PinmemberRadox3-Oct-13 23:19 
AnswerRe: Variables definition PinmemberMartijn Boeker4-Oct-13 9:00 
GeneralMy vote of 5 PinmemberClifford Nelson9-Feb-12 7:19 
GeneralMy vote of 5 Pinmemberlinda831027-Sep-10 23:14 
GeneralThanks a lot Pinmembereijiyq10-Dec-09 21:50 
General5. Pinmemberring_06-Dec-09 18:15 
General5 From me PinmemberMoim Hossain6-Dec-09 0:07 
GeneralRe: 5 From me PinmemberMartijn Boeker6-Dec-09 9:42 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 6 Dec 2009
Article Copyright 2009 by Martijn Boeker
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid