I'm working on a feature where user defined, anonymous, javascript functions retrieved from a database need to be executed server side in the context of ASP.Net application.
I'm evaluating Jint for this purpose (Latest version from NuGet). I have been able to run functions that do basic operations and return values without an issue as below.
public void Do()
{
var jint = new Engine();
var add = jint.Execute(@"var f = " + GetJsFunction()).GetValue("f");
var value = add.Invoke(5, 4);
Console.Write("Result: " + value);
}
private string GetJsFunction()
{
return "function (x,y) {" +
" return x+y;" +
"}";
}
My question is whether Jint facilitates the execution of javascript functions which uses third party libraries like lodash? If so, how would I go about making the Jint engine aware of it (i.e third party library)?
An example would be the execution of following function.
private string GetFunction()
{
return "function (valueJson) { " +
" var value = JSON.parse(valueJson);" +
" var poi = _.find(value,{'Name' : 'Mike'});" +
" return poi; " +
"}";
}
Thanks a lot in advance.
I think I have figured this out. It's no different to executing a custom function. You just read the third party library from a file (project resource) and invoke execute on Jint engine. See below;
private void ImportLibrary(Engine jint, string file)
{
const string prefix = "JintApp.Lib."; //Project location where libraries like lodash are located
var assembly = Assembly.GetExecutingAssembly();
var scriptPath = prefix + file; //file is the name of the library file
using (var stream = assembly.GetManifestResourceStream(scriptPath))
{
if (stream != null)
{
using (var sr = new StreamReader(stream))
{
var source = sr.ReadToEnd();
jint.Execute(source);
}
}
}
}
We can call this function for all the third party libraries that needs to be added.