I have this javasccript expression code as a string in my C# code, I need to evaluate it (execute it) using Microsoft.JScript.Eval.JScriptEvaluate (c#) and get result back.
string code = @"var roles=[];
roles.push('LOC_IND');
roles.push('MANAGERL3');
var country='CANADA';
var age=80;
eval(""roles.indexOf('Administrator')>=0||roles.indexOf('LOC_IND')>=0&&country=='CANADA'"")";
// Calling JScript.Eval to execute that code
var engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
var result = Microsoft.JScript.Eval.JScriptEvaluate(code, engine);
The javascript code itself works fine, if you execute it in browser console, and returns "true", as expected:
var roles=[];
roles.push('LOC_IND');
roles.push('MANAGERL3');
var country='CANADA';
var age=80;
eval("roles.indexOf('Administrator')>=0||roles.indexOf('LOC_IND')>=0&&country=='CANADA'")
However, when I call it from C# Eval.JScriptEvaluate(code, engine); I get this exception:
Function expected.
I am not sure what function it expects and what do I have to do to fix that? At the end Eval.JScriptEvaluate(code, engine) must return true.
Thanks a lot doggy :)
I found an easier way, using another library - Jint.
This location is the right one: https://github.com/sebastienros/jint
string code = @"var roles=[];
roles.push('LOC_IND');
roles.push('MANAGERL3');
var country='CANADA';
var age=80;
function foo(){return roles.indexOf('Administrator')>=0||roles.indexOf('LOC_IND')>=0&&country=='CANADA';}";
// Using Jint - Javascript Interpreter for .NET
var result = new Jint.Engine().Execute(code).Invoke("foo");
P.S. Another option is to use self-invoking function, but it is more difficult to get to the return bool result:
string code = @"var roles=[];
roles.push('LOC_IND');
roles.push('MANAGERL3');
var country='CANADA';
var age=80;
(function(){return roles.indexOf('Administrator')>=0||roles.indexOf('LOC_IND')>=0&&country=='CANADA';})();";
var result = new Jint.Engine()
.Execute(code)
.Boolean
.PrototypeObject
.PrimitiveValue
.AsBoolean();