Tuesday, February 18, 2014

Jint tutorial 001 - embeding JavaScript in a C# application

The is the first post of a series where I will show how to embed and execute JavaScript in a C# application using the JavaScript runtime Jint.

Jint is a Javascript v 5 interpreter written in C# 4.0 using the Portable Library Standard and run or will run on the following platforms:
  • Windows (using Microsoft stack) 
  • MacOS (using Mono or Xamarin stack)
  • iOS (using Xamarin stack)
  • Android (using Xamarin stack)
  • Linux (using Mono stack)
As we progress in the different tutorials, I will show
  • How to write C# classes and objects that can be exposed to the JavaScript world.
  • How to write asynchronous API and call back function
Generally I am interested in interoperability between C# and JavaScript.

At this time of this writing, the developers of Jint are focusing on Windows. I will personally soon test on iOS and MacOS.

How do I do it?

In this sample, I created a C# console app that
  • Instantiate a Jint engine
  • Create a JavaScript function print() so we can output object to the console
  • Execute a Script
  • Get the script return value
 
    class Program
    {
        static Jint.Engine _engine;

        public static void Print(object s)
        {
            if (s == null)
                s = "null";
            Console.WriteLine(s.ToString());
        }

        private static Jint.Engine CreateEngine()
        {
            return new Engine().SetValue("print", new Action<object>(Print));
        }

        static void Main(string[] args)
        {
            var source = @"
                var s = 'Hello World From JavaScript ';

                for(var i=0; i<4; i++) {
                    print(s + i);
                }                
                s; // Evaluate and return the expression
            ";
            var s = CreateEngine().Execute(source).GetCompletionValue();
            Console.WriteLine(s.AsString());
            Console.ReadLine();
        }
    }

3 comments:

  1. Great!
    All the other documents are old and out of date, this is fresh.
    Thank you!

    ReplyDelete
  2. Thanks for the good examples.

    How can I execute a JS function passing 2 strings as parameters and receive a json object as result?

    I tried:
    dim jsonResult = engine.Invoke("calcKm", "100;300", "120;350")

    but I receive an error: ActiveXObject is not defined

    Thanks in advance.
    Alessandro

    ReplyDelete
  3. Thank you for providing JavaScript in a C# application. It is very latest and updated code which can help c# programmers. I was searching for this topic in C# tutorial and during this process found and open this link, when I read and use this code then I surprised.

    ReplyDelete