Hosting A JavaScript Engine In .NET

Tuesday, September 10, 2013

ClearScript is simple to use and allows me to host either V8 or Chakra. The samples on the home page show just how easy is the interop from C# to JavaScript and vice versa.

I use a simple wrapper because the only API I need is one to Evaluate small script expressions.

public interface IJavaScriptMachine : IDisposable
{
    dynamic Evaluate(string expression);
}

The following implementation sets up a default environment for script execution by loading up some required scripts, like underscore.js. The scripts are embedded resources in the current assembly.

public class JavaScriptMachine : JScriptEngine, 
                                 IJavaScriptMachine
{      
    public JavaScriptMachine()
    {
        LoadDefaultScripts();                
    }
    
    void LoadDefaultScripts()
    {
        var assembly = Assembly.GetExecutingAssembly();
        foreach (var baseName in _scripts)
        {
            var fullName = _scriptNamePrefix + baseName;
            using (var stream = assembly.GetManifestResourceStream(fullName))
            using(var reader = new StreamReader(stream))
            {
                var contents = reader.ReadToEnd();
                Execute(contents);
            }
        }
    }

    const string _scriptNamePrefix = "Foo.Namespace.";
    readonly string[] _scripts = new[]
        {
            "underscore.js", "other.js"
        };       
}

For examples, check out the ClearScript documentation.


Comments
Aaron Tuesday, September 10, 2013
Scott, when would someone want to utilize Clearscript? Can you provide some examples? Thanks!
gravatar PilotBob Tuesday, September 10, 2013
Nice... how much can you sand box this? I am looking for a solution to allow customers to be able to write earning/deduction calculations during payroll calculation. Our current version uses stored procs and the engine is done in TSQL. But, for the new web version the payroll engine will be in C# and the app will have a multi-tenant SaaS mode. So, I want to limit the code that is run to only access what I allow them to... such as only that tenants data, etc. BOb
gravatar Ryan Tuesday, September 10, 2013
Hey Scott, have you ever tried IronJS? It seems like it solves a similar problem, except it uses the Microsoft Dynamic Language Runtime instead of V8 or Chakra: https://github.com/fholm/IronJS I have not gotten around to trying it out, but I listened to a podcast with the developer and Scott Hanselman. He wrote it in F#, because he felt like learning it. Quite an ambitious project while learning a new language.
gravatar Scott Allen Tuesday, September 10, 2013
@PilotBob: Still in the process of testing that out myself, but I'm hoping it sandboxes well for the same reasons you want to use this. If it provides access to V8 isolates, should in great shape, but I'm at least hoping each instance is isolated. @Ryan: I did look at it because I heard that show, too. ClearScript was just so easy to get running (at least with Chakra, and even without a NuGet package).
gravatar Scott Allen Tuesday, September 10, 2013
@Aaron - similar to what PilotBob is looking at, wanting to run some script expressions over business objects on the server. Same script should work in a browser, too.
gravatar David Boike Wednesday, September 11, 2013
This is awesome! It has some great applications for making a plugin or extensibility framework in a multitenant environment, and especially great since JS is getting to be such a ubiquitous language.
gravatar Wayne Friday, September 13, 2013
Also, check out https://v8dotnet.codeplex.com/
gravatar Simon Saturday, September 14, 2013
Note if you only need to interop with chakra (or olders windows jscript engines), you don't need to reference that big project. You only need one C# file as demonstrated here: http://stackoverflow.com/questions/4744105/parse-and-execute-js-by-c-sharp
gravatar Jesse Friday, September 20, 2013
@Scott I just created a nuget package for this in case you're interested: http://www.nuget.org/packages/ClearScript.V8/ I was using Jurassic before I saw your post appear on The Morning Brew (perfect timing), and in my application I saw an approximately 66x perf gain from ClearScript using V8. Awesomeness!
gravatar Scott Sunday, September 22, 2013
@Jesse: Thanks!!
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!