static void OriginalMain()
        {
            var done = false;
            var sw = new Stopwatch();

            sw.Start();
            for (var i = 0; i < N; i++)
            {
                var jintEngine = new Jint.Engine();
                jintEngine.Execute(currentScript);
                done = jintEngine.GetValue("done").AsBoolean();
            }
            sw.Stop();
            Console.WriteLine("jint: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                var ironjsEngine = new IronJS.Hosting.CSharp.Context();
                ironjsEngine.Execute(currentScript);
                done = ironjsEngine.GetGlobalAs<bool>("done");
            }
            sw.Stop();
            Console.WriteLine("ironjs: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                using (var jsNetEngine = new Noesis.Javascript.JavascriptContext())
                {
                    jsNetEngine.Run(currentScript);
                    done = (bool)jsNetEngine.GetParameter("done");
                }
            }
            sw.Stop();
            Console.WriteLine("js.net: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                var jurassicEngine = new Jurassic.ScriptEngine();
                jurassicEngine.Execute(currentScript);
                done = jurassicEngine.GetGlobalValue<bool>("done");
            }
            sw.Stop();
            Console.WriteLine("jurassic: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                using (var clearscriptV8 = new Microsoft.ClearScript.V8.V8ScriptEngine())
                {
                    clearscriptV8.Execute(currentScript);
                    done = clearscriptV8.Script.done;
                }
            }
            sw.Stop();
            Console.WriteLine("clearscriptV8: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            using (var clearscriptV8 = new Microsoft.ClearScript.V8.V8Runtime())
            {
                var compiled = clearscriptV8.Compile(currentScript);
                for (var i = 0; i < N; i++)
                {
                    using (var engine = clearscriptV8.CreateScriptEngine())
                    {
                        engine.Evaluate(compiled);
                        done = engine.Script.done;
                    }
                }
            }
            sw.Stop();
            Console.WriteLine("clearscriptV8 compiled: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                var nilcontext = new NiL.JS.Core.Context();
                nilcontext.Eval(currentScript);
                done = (bool)nilcontext.GetVariable("done");
            }
            sw.Stop();
            Console.WriteLine("niljs: " + sw.ElapsedMilliseconds / N + " - " + done);

            Console.Read();
        }
Exemple #2
0
        void test1()
        {
            var v = new IronJS.Hosting.CSharp.Context();

            //   创建JS方法
            v.Execute("function sayHello(str){ return {msg:'Hello ,' + str};}");

            // 通过JS代码调用JS方法返回值
            dynamic dy = v.Execute("sayHello('JS Call');");

            Console.WriteLine(dy.msg);



            // 创建JS方法
            v.Execute("function sayHello2(str){ return {msg:'Hello ,' + str.msg};}");

            //  映射JS方法到指定的delegate上
            dy = v.GetFunctionAs <GetWithMyClass>("sayHello2");

            //   调用JS方法
            dy = dy(new MyClass()
            {
                msg = "C# Call"
            });

            Console.WriteLine(dy.msg);
        }
    static void Main(string[] args)
    {
        var    ctx = new IronJS.Hosting.CSharp.Context();
        string json;

        using (TextReader reader = File.OpenText("array_items.txt"))
        {
            json = reader.ReadToEnd();
        }
        CommonObject result = (CommonObject)ctx.Execute("var x=" + json);
        Dictionary <uint, BoxedValue> indexes = new Dictionary <uint, BoxedValue>();

        result.GetAllIndexProperties(indexes, uint.MaxValue);
        List <Place> places = new List <Place>();

        foreach (uint idx in indexes.Keys)
        {
            Place p = new Place();
            p.ID        = (int)idx;
            p.Name      = (string)indexes[idx].Object.Members["Name"];
            p.Latitude  = (double)indexes[idx].Object.Members["Latitude"];
            p.Longitude = (double)indexes[idx].Object.Members["Longitude"];
            places.Add(p);
        }
        foreach (Place place in places)
        {
            Console.WriteLine("ID = {0}", place.ID);
            Console.WriteLine("Name = {0}", place.Name);
            Console.WriteLine("Latitude = {0}", place.Latitude);
            Console.WriteLine("Longitude = {0}", place.Longitude);
        }
        Console.ReadKey();
    }
        void test2()
        {
            var v = new IronJS.Hosting.CSharp.Context();

            MyClass myClass = new MyClass() { msg = "C#实例" };

              //   将实例映射到JS变量
            v.SetGlobal("myClass", myClass);

             //    创建JS方法
            v.Execute("function sayHello(){ return {msg:'Hello ,' + myClass.msg};}");

               //  通过JS代码调用JS方法返回值
            dynamic dy = v.Execute("sayHello();");

             Console.WriteLine(dy.msg);
        }
 static void XMain(string[] args)
 {
     var ctx = new IronJS.Hosting.CSharp.Context();
     dynamic hello = ctx.Execute("(function (){ return {msg:'你好,IronJS'};})();");
     string ss = hello.msg;
     Console.Out.WriteLine(hello.msg);
     //Console.Out.WriteLine(hello.noexist);
     Console.ReadKey(true);
 }
        public void Main()
        {
            var jsCode = File.ReadAllText("./../../../Js/JsMain.js");

            IronJS.Hosting.CSharp.Context ctx = new IronJS.Hosting.CSharp.Context();

            var res = ctx.Execute(jsCode);

            Console.WriteLine(res);
        }
        static void XMain(string[] args)
        {
            var     ctx   = new IronJS.Hosting.CSharp.Context();
            dynamic hello = ctx.Execute("(function (){ return {msg:'你好,IronJS'};})();");
            string  ss    = hello.msg;

            Console.Out.WriteLine(hello.msg);
            //Console.Out.WriteLine(hello.noexist);
            Console.ReadKey(true);
        }
Exemple #8
0
        void test2()
        {
            var v = new IronJS.Hosting.CSharp.Context();

            MyClass myClass = new MyClass()
            {
                msg = "C#实例"
            };

            //   将实例映射到JS变量
            v.SetGlobal("myClass", myClass);

            //    创建JS方法
            v.Execute("function sayHello(){ return {msg:'Hello ,' + myClass.msg};}");

            //  通过JS代码调用JS方法返回值
            dynamic dy = v.Execute("sayHello();");

            Console.WriteLine(dy.msg);
        }
Exemple #9
0
        private static IronJS.Hosting.CSharp.Context CreateContext()
        {
            var ctx = new IronJS.Hosting.CSharp.Context();

            Func<BoxedValue, bool> fnExists = f => f.IsFunction;
            var fnExistsFunc = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, fnExists);
            ctx.SetGlobal("fnExists", fnExistsFunc);

            ctx.Execute("var currentTest; var ES5Harness = { registerTest: function (test) { currentTest = test; } };");

            return ctx;
        }
Exemple #10
0
        private static IronJS.Hosting.CSharp.Context CreateContext()
        {
            var ctx = new IronJS.Hosting.CSharp.Context();

            Func <BoxedValue, bool> fnExists = f => f.IsFunction;
            var fnExistsFunc = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, fnExists);

            ctx.SetGlobal("fnExists", fnExistsFunc);

            ctx.Execute("var currentTest; var ES5Harness = { registerTest: function (test) { currentTest = test; } };");

            return(ctx);
        }
        void test1()
        {
            var v = new IronJS.Hosting.CSharp.Context();

              //   创建JS方法
            v.Execute("function sayHello(str){ return {msg:'Hello ,' + str};}");

            // 通过JS代码调用JS方法返回值
            dynamic dy = v.Execute("sayHello('JS Call');");

             Console.WriteLine(dy.msg);

            // 创建JS方法
            v.Execute("function sayHello2(str){ return {msg:'Hello ,' + str.msg};}");

               //  映射JS方法到指定的delegate上
            dy = v.GetFunctionAs<GetWithMyClass>("sayHello2");

              //   调用JS方法
            dy = dy(new MyClass() { msg = "C# Call" });

             Console.WriteLine(dy.msg);
        }
Exemple #12
0
        protected override TestResult ExecuteTest(IronJS.Hosting.CSharp.Context ctx, string test)
        {
            var errors = new StringBuilder();

            Action <string> appendError = err =>
            {
                if (errors.Length > 0)
                {
                    errors.AppendLine();
                }

                errors.Append(err);
            };

            var score = string.Empty;

            Action <string, string> notifyResult = (name, result) => { };
            Action <string, string> notifyError  = (name, error) => appendError(name + ": " + error);
            Action <string>         notifyScore  = s => score = s;

            ctx.SetGlobal("NotifyResult", IronJS.Native.Utils.CreateFunction(ctx.Environment, 2, notifyResult));
            ctx.SetGlobal("NotifyError", IronJS.Native.Utils.CreateFunction(ctx.Environment, 2, notifyError));
            ctx.SetGlobal("NotifyScore", IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, notifyScore));

            try
            {
                ctx.ExecuteFile(test);
                ctx.Execute(@"BenchmarkSuite.RunSuites({ NotifyResult: NotifyResult,
                                                         NotifyError: NotifyError,
                                                         NotifyScore: NotifyScore });");
            }
            catch (Exception ex)
            {
                appendError("Exception: " + ex.GetBaseException().Message);
            }

            if (errors.Length > 0)
            {
                return(new TestResult {
                    Error = errors.ToString()
                });
            }
            else
            {
                return(new TestResult {
                    Score = score
                });
            }
        }
        public bool Evaluate(string conditionScript, IWorkflowRuntime runtime)
        {
            if (conditionScript == null)
                throw new ArgumentNullException("conditionScript");
            if (runtime == null)
                throw new ArgumentNullException("runtime");

            var context = new IronJS.Hosting.CSharp.Context();
            context.SetGlobal("input", runtime.Input);
            foreach (var providerRuntimeResult in runtime.ProviderResults)
            {
                if (providerRuntimeResult.ProviderStatus == EWorkflowProviderRuntimeStatus.Success)
                    context.SetGlobal(providerRuntimeResult.ProviderName, providerRuntimeResult.Result);
            }
            conditionScript = "(function(){ " + conditionScript + "})()";
            return context.Execute<bool>(conditionScript);
        }
Exemple #14
0
        private static IronJS.Hosting.CSharp.Context CreateContext(string libPath, Action <string> errorAction)
        {
            var ctx = new IronJS.Hosting.CSharp.Context();

            Action <string> failAction    = error => { throw new Exception(error); };
            Action <string> printAction   = message => Debug.WriteLine(message);
            Action <string> includeAction = file => ctx.Execute(GetInclude(libPath, file));

            var errorFunc   = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, errorAction);
            var failFunc    = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, failAction);
            var printFunc   = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, printAction);
            var includeFunc = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, includeAction);

            ctx.SetGlobal("$FAIL", failFunc);
            ctx.SetGlobal("ERROR", errorFunc);
            ctx.SetGlobal("$ERROR", errorFunc);
            ctx.SetGlobal("$PRINT", printFunc);
            ctx.SetGlobal("$INCLUDE", includeFunc);
            return(ctx);
        }
        private static IronJS.Hosting.CSharp.Context CreateContext(Action<string> errorAction)
        {
            var ctx = new IronJS.Hosting.CSharp.Context();

            Action<string> failAction = error => Assert.Fail(error);
            Action<string> printAction = message => Trace.WriteLine(message);
            Action<string> includeAction = file => ctx.Execute(GetInclude(file));

            var errorFunc = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, errorAction);
            var failFunc = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, failAction);
            var printFunc = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, printAction);
            var includeFunc = IronJS.Native.Utils.CreateFunction(ctx.Environment, 1, includeAction);

            ctx.SetGlobal("$FAIL", failFunc);
            ctx.SetGlobal("ERROR", errorFunc);
            ctx.SetGlobal("$ERROR", errorFunc);
            ctx.SetGlobal("$PRINT", printFunc);
            ctx.SetGlobal("$INCLUDE", includeFunc);

            return ctx;
        }
Exemple #16
0
        void test3()
        {
            var v = new IronJS.Hosting.CSharp.Context();

            string strJson = " var json ={参数1:'json参数1',参数2:{参数21:1,参数22:2},参数3:[1,2,3]};" +
                             " var json2 ={参数1:'json2参数1',参数2:{参数21:1,参数22:2},参数3:[1,2,3]};";

            //  运行代码,获取最后一个变量。(本例中返回Json2)
            dynamic dy2 = v.Execute(strJson);

            //   获取指定JS变量值
            dynamic dy1 = v.GetGlobalAs <dynamic>("json");

            //    打印数据
            Print(dy1);

            //   打印数据
            Print(dy2);

            Console.ReadKey(true);
        }
Exemple #17
0
        static void Main(string[] args)
        {
            var context = new IronJS.Hosting.CSharp.Context();

            var writeLine = IronJS.Native.Utils.createHostFunction<Action<string>>(context.Environment,
                x => {
                    Console.WriteLine("Console: " + x);
                });

            context.SetGlobal("WriteLine", writeLine);

            var setTitle = IronJS.Native.Utils.createHostFunction<Action<string>>(context.Environment,
                x =>
                {
                    Console.Title = x;
                });

            context.SetGlobal("SetTitle", setTitle);

            Console.WriteLine("Type a JS expression below and press enter. (Blank line to quit.)");

            Console.Write("js-console> ");
            string command = Console.ReadLine();

            while (command != "" && command != "exit")
            {
                try
                {
                    Console.WriteLine(context.Execute(command));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Oops. Got an error: \n" + ex.Message);
                }
                Console.Write("\njs-console> ");
                command = Console.ReadLine();
            }
        }
Exemple #18
0
        /**
         * implements require() for importing js files/namespaces
         *
         * file - the literal expression passed to require() in js.
         * Might be abs or rel path + filename.
         */
        public static IronJS.CommonObject Require(string file)
        {
            // TODO: could possibly break this by doing require('undefined');
            if (String.IsNullOrWhiteSpace(file) || String.IsNullOrEmpty(file) || file == "undefined")
            {
                throw new Exception("invalid file spec passed to require()");
            }

            // for compiled-in functionality, return existing references.
            // TODO: clean up the global namespace, `http' et al. are directly visible
            if (file == "http")
            {
                // TODO: re-add after httpserver.cs is converted to IJS 0.2
                // return httpObj;
            }
            if (file == "net")
            {
                return(netObj);
            }

            // otherwise invoke CommonJS search rules
            commonjs.SetRequireStack(file);
            string filename = Path.GetFileName(file);

            FileStream fs;
            string     filepath = commonjs.FindFile(filename);

            fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);

            string code = new StreamReader(fs).ReadToEnd();

            // extra semicolon provided after file contents.. just in case
            code = "var exports = {}; " + code + "; exports;";
            IronJS.CommonObject retval = ctx.Execute <IronJS.CommonObject>(code);
            commonjs.RequireStack.Pop();
            return(retval);
        }
        public bool Evaluate(string conditionScript, IWorkflowRuntime runtime)
        {
            if (conditionScript == null)
            {
                throw new ArgumentNullException("conditionScript");
            }
            if (runtime == null)
            {
                throw new ArgumentNullException("runtime");
            }

            var context = new IronJS.Hosting.CSharp.Context();

            context.SetGlobal("input", runtime.Input);
            foreach (var providerRuntimeResult in runtime.ProviderResults)
            {
                if (providerRuntimeResult.ProviderStatus == EWorkflowProviderRuntimeStatus.Success)
                {
                    context.SetGlobal(providerRuntimeResult.ProviderName, providerRuntimeResult.Result);
                }
            }
            conditionScript = "(function(){ " + conditionScript + "})()";
            return(context.Execute <bool>(conditionScript));
        }
        static void Main()
        {
            const bool runIronJs   = true;
            const bool runJint     = true;
            const bool runJurassic = true;

            const int  iterations  = 1000;
            const bool reuseEngine = false;

            var watch = new Stopwatch();


            if (runIronJs)
            {
                IronJS.Hosting.CSharp.Context ironjs;
                ironjs = new IronJS.Hosting.CSharp.Context();
                ironjs.Execute(Script);
                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        ironjs = new IronJS.Hosting.CSharp.Context();
                    }

                    ironjs.Execute(Script);
                }

                Console.WriteLine("IronJs: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }

            if (runJint)
            {
                Engine jint;
                jint = new Engine();
                jint.Execute(Script);

                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        jint = new Jint.Engine();
                    }

                    jint.Execute(Script);
                }

                Console.WriteLine("Jint: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }

            if (runJurassic)
            {
                Jurassic.ScriptEngine jurassic;
                jurassic = new Jurassic.ScriptEngine();
                jurassic.Execute(Script);

                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        jurassic = new Jurassic.ScriptEngine();
                    }

                    jurassic.Execute(Script);
                }

                Console.WriteLine("Jurassic: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }
        }
 private static void ExecuteWithIronJs(Test test)
 {
     Execute("ironjs", test, () =>
     {
         var ironjsEngine = new IronJS.Hosting.CSharp.Context();
         ironjsEngine.Execute(test.Content);
     });
 }
        void test3()
        {
            var v = new IronJS.Hosting.CSharp.Context();

            string strJson = " var json ={参数1:'json参数1',参数2:{参数21:1,参数22:2},参数3:[1,2,3]};" +
                             " var json2 ={参数1:'json2参数1',参数2:{参数21:1,参数22:2},参数3:[1,2,3]};";

               //  运行代码,获取最后一个变量。(本例中返回Json2)
            dynamic dy2 = v.Execute(strJson);

              //   获取指定JS变量值
            dynamic dy1 = v.GetGlobalAs<dynamic>("json");

             //    打印数据
            Print(dy1);

              //   打印数据
            Print(dy2);

            Console.ReadKey(true);
        }
Exemple #23
0
        static void Main()
        {
            const bool runIronJs = true;
            const bool runJint = true;
            const bool runJurassic = true;

            const int iterations = 1000;
            const bool reuseEngine = false;

            var watch = new Stopwatch();


            if (runIronJs)
            {
                IronJS.Hosting.CSharp.Context ironjs;
                ironjs = new IronJS.Hosting.CSharp.Context();
                ironjs.Execute(Script);
                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        ironjs = new IronJS.Hosting.CSharp.Context();
                    }

                    ironjs.Execute(Script);
                }

                Console.WriteLine("IronJs: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }

            if (runJint)
            {
                Engine jint;
                jint = new Engine();
                jint.Execute(Script);

                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        jint = new Jint.Engine();
                    }

                    jint.Execute(Script);
                }

                Console.WriteLine("Jint: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }

            if (runJurassic)
            {
                Jurassic.ScriptEngine jurassic;
                jurassic = new Jurassic.ScriptEngine();
                jurassic.Execute(Script);

                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        jurassic = new Jurassic.ScriptEngine();
                    }

                    jurassic.Execute(Script);
                }

                Console.WriteLine("Jurassic: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }
        }
Exemple #24
0
        void runSources(Stack <string> sources)
        {
            if (jsThread != null)
            {
                return;
            }

            doWithoutTextChange(() =>
            {
                inputText.Focusable  = false;
                inputText.Background = Brushes.WhiteSmoke;
            });

            jsThread = new Thread(() =>
            {
                try
                {
                    if (sources.Count > 0)
                    {
                        Dispatcher.Invoke(new Action(() => breakPointLabel.Content = "Running..."));

                        var result         = context.Execute(sources.Pop());
                        var resultAsString = TypeConverter.ToString(BoxingUtils.JsBox(result));

                        Dispatcher.Invoke(new Action(() =>
                                                     consoleOutput.Text += "\r\nLast statement: " + resultAsString));
                    }
                }
                catch (Exception exn)
                {
                    Dispatcher.Invoke(new Action(() => printException(exn)));
                }
                finally
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        doWithoutTextChange(() =>
                        {
                            inputText.Focusable  = true;
                            inputText.Background = Brushes.Transparent;
                        });

                        displayGlobalVariables(context.Globals);
                    }));

                    jsThread = null;

                    if (sources.Count > 0)
                    {
                        Dispatcher.Invoke(new Action(() =>
                        {
                            runSources(sources);
                        }));
                    }
                    else
                    {
                        Dispatcher.Invoke(new Action(() => breakPointLabel.Content = ""));
                    }
                }
            });

            jsThread.Start();
        }