CodeSnips

Thursday, March 21, 2013

Javascript from C#, JInt, Jurrasic

Just a quick code snippet. I was interested in executing javascript from C#. So far, the two clear winners for a framework to do this are JInt and Jurrasic.  Needless to say, the V8 Javascript.Net project is dead and doesn't even try to pretend otherwise...
JScript .Net has been dead a long time - let's not even go there.

Jurassic takes a bit more effort to integrate existing .Net objects into scripts as parameters, but makes perhaps is faster.

JInt is the easiest to use and integrate (takes objects directly as parameters) - and for quick DSL-like scripting using Javascript - wins my vote.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jint;
using Jurassic;
using Newtonsoft.Json;

namespace RunJSInt
{
    public class Program
    {

        static void Main(string[] args)
        {
            JintExample();
            JurrasicExample();
            Console.ReadLine();
        }

        public class Developer
        {
            public string Name { get; set; }
            public string Title { get; set; }
        }

        public class DeveloperObjectInstance : Jurassic.Library.ObjectInstance
        {
            public DeveloperObjectInstance(ScriptEngine engine) : 
                base(engine)
            {

            }
            public void init(Developer dev)
            {
                this["Name"] = dev.Name;
                this["Title"] = dev.Title;
            }
        }

        private static void JurrasicExample()
        {
            var dev = new Developer { Name = "Mike", Title = "Developer" };
            var engine = new Jurassic.ScriptEngine();
            var obj = new DeveloperObjectInstance(engine);
            obj.init(dev);
            engine.Evaluate(@"function test(a) { 
                                  return 'Jurrasic says, hello ' + a.Name; 
                            }");
            Console.WriteLine(engine.CallGlobalFunction("test",obj));
        }


        static void JintExample()
        {
            var dev = new Developer { Name = "Mike", Title = "Developer" };
            JintEngine engine = new JintEngine();
            engine.SetParameter("message", dev);
            var result = engine.Run(@"
                return 'Jint says, hello ' + message.Name;");
            Console.WriteLine(result);
        }
    }
}

No comments:

Post a Comment