示例#1
0
 public void SimpleExpressionException()
 {
     using (JsContext js = jsEngine.CreateContext())
     {
         js.Execute("throw 'xxx'");
     }
 }
示例#2
0
        static void TestCase2()
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //create js engine and context

            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext())
                {
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Start();

                    TestMe1 t1 = new TestMe1();

                    for (int i = 2000; i >= 0; --i)
                    {
                        ctx.SetVariableFromAny("x", t1);
                        object result = ctx.Execute("(function(){if(x.C()){return  x.B();}else{return 0;}})()");
                    }
                    stwatch.Stop();
                    Console.WriteLine("met2 managed reflection:" + stwatch.ElapsedMilliseconds.ToString());
                    //Assert.That(result, Is.EqualTo(100));
                }
        }
示例#3
0
        private void button7_Click(object sender, EventArgs e)
        {
            //1. init html
            var initHtml = "<html><script>function doc_ready(){console.log('doc_ready');}</script><body onload=\"doc_ready()\"><div id=\"a\">A</div><div id=\"b\" style=\"background-color:blue\">B</div><div id=\"c\">c_node</div></body></html>";

            easeViewport.LoadHtmlString("", initHtml);
            //----------------------------------------------------------------
            //after load html page

            //load v8 if ready

#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //===============================================================

            //2. access dom

            var webdoc = easeViewport.GetHtmlDom() as LayoutFarm.WebDom.IHtmlDocument;
            //create js engine and context
            if (myengine == null)
            {
                var jstypeBuilder = new LayoutFarm.Scripting.MyJsTypeDefinitionBuilder();
                myengine = new JsEngine();
                myCtx    = myengine.CreateContext(jstypeBuilder);
            }

            System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
            stwatch.Reset();
            stwatch.Start();
            myCtx.SetVariableAutoWrap("document", webdoc);
            myCtx.SetVariableAutoWrap("console", myWbConsole);
            string simplejs   = @"
                    (function(){
                        console.log('hello world!');
                        var domNodeA = document.getElementById('a');
                        var domNodeB = document.getElementById('b');
                        var domNodeC = document.getElementById('c');

                        var newText1 = document.createTextNode('... says hello world!');
                        domNodeA.appendChild(newText1);

                        for(var i=0;i<10;++i){
                            var newText2= document.createTextNode(i.toString());
                            domNodeA.appendChild(newText2);       
                        } 

                        var newDivNode= document.createElement('div');
                        newDivNode.appendChild(document.createTextNode('new div'));
                        newDivNode.attachEventListener('mousedown',function(){console.log('new div');});
                        domNodeB.appendChild(newDivNode);    
                        
                        domNodeC.innerHTML='<div> from inner html <span> from span</span> </div>';
                        console.log(domNodeC.innerHTML);
                    })();
                ";
            object testResult = myCtx.Execute(simplejs);
            stwatch.Stop();
            Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
        }
示例#4
0
        static void TestColl1()
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //create js engine and context

            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext())
                {
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Start();

                    string[] ta = { "test" };
                    ctx.SetVariableFromAny("ta", ta);
                    object result = ctx.Execute("(function(){return JSON.stringify(ta);})()");

                    //please parse the string with some json lib
                    //(eg Json.net) to check the first elem

                    if ((string)result != "[\"" + ta[0] + "\"]")
                    {
                        throw new Exception("!");
                    }

                    stwatch.Stop();
                    Console.WriteLine("result " + result);
                    Console.WriteLine("met3 managed reflection:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#5
0
        private void button8_Click(object sender, EventArgs e)
        {
            int version = JsBridge.LibVersion;

#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext(new MyJsTypeDefinitionBuilder()))
                {
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Reset();
                    stwatch.Start();

                    var ab = new AboutMe();
                    ctx.SetVariableAutoWrap("x", ab);

                    string testsrc = @"(function(){
                    x.AttachEvent('mousedown',function(evArgs){});
                    x.FireEventMouseDown({});
                })()";
                    object result  = ctx.Execute(testsrc);
                    stwatch.Stop();

                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#6
0
        private void button1_Click(object sender, EventArgs e)
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif

            JsTypeDefinition jstypedef = new JsTypeDefinition("AA");
            jstypedef.AddMember(new JsMethodDefinition("B", args =>
            {
                args.SetResult(100);
            }));
            jstypedef.AddMember(new JsMethodDefinition("C", args =>
            {
                args.SetResult(true);
            }));
            //===============================================================
            //create js engine and context
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext())
                {
                    if (!jstypedef.IsRegisterd)
                    {
                        ctx.RegisterTypeDefinition(jstypedef);
                    }
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Start();

                    TestMe1 t1    = new TestMe1();
                    var     proxy = ctx.CreateWrapper(t1, jstypedef);

                    for (int i = 2000; i >= 0; --i)
                    {
                        ctx.SetVariableFromAny("x", proxy);
                        object result = ctx.Execute("(function(){if(x.C()){return x.B();}else{return 0;}})()");
                    }
                    //for (int i = 1; i >= 0; --i)
                    //{
                    //    ctx.SetVariableFromAny("x", proxy);
                    //    object result = ctx.Execute(@"
                    //    var http = require('http');
                    //    var server = http.createServer(function(req, res) {
                    //    res.writeHead(200);
                    //    res.end('Hello Http');
                    //    });
                    //    server.listen(8080);
                    //    ");
                    //}
                    stwatch.Stop();

                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                    //Assert.That(result, Is.EqualTo(100));
                }
        }
示例#7
0
 internal void InitJsEngine()
 {
     if (myengine == null)
     {
         var jstypeBuilder = new LayoutFarm.Scripting.MyJsTypeDefinitionBuilder();
         myengine = new JsEngine();
         myCtx    = myengine.CreateContext(jstypeBuilder);
     }
     myCtx.SetVariableAutoWrap("document", HtmlDoc);
     myCtx.SetVariableAutoWrap("console", Console);
 }
 public void AddTest()
 {
     using (var engine = new JsEngine())
     {
         using (var context = engine.CreateContext())
         {
             var x = (double)context.Execute("3.14159+2.71828");
             Assert.AreEqual(x, 5.85987);
         }
     }
 }
 public void tellme_Test()
 {
     using (JsEngine js = new JsEngine(4, 32))
     {
         using (JsContext context = js.CreateContext())
         {
             context.Execute("var x = {'answer':42, 'tellme':function (x) { return x+' '+this.answer; }}");
             dynamic x      = context.GetVariable("x");
             var     result = x.tellme("What is the answer to ...?");
             Assert.AreEqual(result, "What is the answer to...? 42");
         }
     }
 }
 public void AccessPropertiesAndCallMethodsTest()
 {
     using (JsEngine js = new JsEngine(4, 32))
     {
         using (JsContext context = js.CreateContext())
         {
             context.SetVariable("m", new Test());
             context.Execute("m.Value = 42");
             var result = context.Execute("m.PrintValue('And the answer is (again!):')");
             Assert.AreEqual(result, "And the answer is (again!): 42");
         }
     }
 }
示例#11
0
        private void button12_Click(object sender, EventArgs e)
        {
            //very basic ***
            //-----------------
            //test tsc.js
            //this needs EspressoHostForTsc
            //-----------------
            string        tsc_esprCode = File.ReadAllText("../../Samples/js_tools/tsc2_5/tsc_espr.js");
            StringBuilder stbuilder    = new StringBuilder();

            stbuilder.Append(tsc_esprCode);
            //-----------------

            int version = JsBridge.LibVersion;

#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext(new MyJsTypeDefinitionBuilder()))
                {
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Reset();
                    stwatch.Start();

                    var my_expr_ext = new EspressoHostForTsc_25();
                    ctx.SetVariableAutoWrap("my_expr_ext", my_expr_ext);

                    string testsrc = @"(function(){
                       
                        // test1: general  compile through commamd line
                        // ts.executeCommandLine(['greeter.ts']);
                        //-------------------------------------------------
                        // test 2: generate ast 
                        var filename=""greeter.ts"";  //example only
                        my_expr_ext.ConsoleLog(filename);
                        //parse
                        const sourceFile = ts.createSourceFile(filename,
                        my_expr_ext.readFile(filename),2, false);
                        //send output as json to managed host
                        my_expr_ext.ConsoleLog(JSON.stringify( sourceFile));
                    })()";
                    stbuilder.Append(testsrc);
                    ctx.Execute(stbuilder.ToString());

                    stwatch.Stop();
                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#12
0
        static void TestCase1()
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif

            JsTypeDefinition jstypedef = new JsTypeDefinition("AA");
            jstypedef.AddMember(new JsMethodDefinition("B", args =>
            {
                args.SetResult(100);
            }));
            jstypedef.AddMember(new JsMethodDefinition("C", args =>
            {
                args.SetResult(true);
            }));
            //===============================================================
            //create js engine and context
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext())
                {
                    if (!jstypedef.IsRegisterd)
                    {
                        ctx.RegisterTypeDefinition(jstypedef);
                    }
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Start();

                    TestMe1 t1    = new TestMe1();
                    var     proxy = ctx.CreateWrapper(t1, jstypedef);

                    for (int i = 2000; i >= 0; --i)
                    {
                        ctx.SetVariableFromAny("x", proxy);
                        object result = ctx.Execute("(function(){if(x.C()){return  x.B();}else{return 0;}})()");
                    }
                    //test value of
                    object re = ctx.Execute("(function(){function myNumberType(n) {    this.number = n;}" +
                                            "myNumberType.prototype.valueOf = function() {    return this.number;};" +
                                            "myObj = new myNumberType(4);" +
                                            "return myObj + 3;" +
                                            "})()");
                    stwatch.Stop();

                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                    //Assert.That(result, Is.EqualTo(100));
                }
        }
示例#13
0
        private void button11_Click(object sender, EventArgs e)
        {
            //very basic ***
            //-----------------
            //test loki.js
            //this needs EspressoHostForTsc
            //-----------------
            string        currentDir   = System.IO.Directory.GetCurrentDirectory();
            string        esprima_code = File.ReadAllText("../../Samples/js_tools/lokijs/lokijs.js");
            StringBuilder stbuilder    = new StringBuilder();

            stbuilder.Append(esprima_code);
            //-----------------

            int version = JsBridge.LibVersion;

#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext(new MyJsTypeDefinitionBuilder()))
                {
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Reset();
                    stwatch.Start();

                    var my_expr_ext = new EspressoHostForLoki();
                    ctx.SetVariableAutoWrap("my_expr_ext", my_expr_ext);
                    string testsrc = @"
                    function require(file){
                        my_expr_ext.Require(file);
                    }
                    (function(){
                       var db = new loki('loki.json');
                       //test log
                       my_expr_ext.ConsoleLog(db);
                       db.save();
                    })()";
                    stbuilder.Append(testsrc);
                    ctx.Execute(stbuilder.ToString());

                    stwatch.Stop();
                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#14
0
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="value">要加密的值</param>
        /// <param name="rsaPublic">rsa公钥</param>
        /// <returns>返回加密后的密码</returns>
        private static string RsaEncrypt(string value, string rsaPublic)
        {
            // 初始化vroom js 才可以工作
            VroomJs.AssemblyLoader.EnsureLoaded(); // windows only

            using (JsEngine engine = new JsEngine())
            {
                using (var context = engine.CreateContext())
                {
                    string encryptJs = Properties.Resources.encrypt;

                    string encryptValue = (string)context.Execute(encryptJs + "encrypt('" + value + "', '" + rsaPublic + "')");

                    return(encryptValue);
                }
            }
        }
示例#15
0
        static void TestOverload()
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //create js engine and context

            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext())
                {
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Start();

                    A <B> a     = new A <B>();
                    Base  base1 = new Base();
                    B     b     = new B();
                    //----
                    Console.WriteLine("pure .net behaviour");
                    //test .net side
                    a.Add(null);          //Add(T a)
                    a.Add(b);             //Add(T a)
                    a.Add(base1);         //Add(Base a)
                    a.Add(new object());  // Add(object a)
                    a.Add(new object[0]); // Add(object a)
                    //----------
                    Console.WriteLine("----------");
                    Console.WriteLine("Espresso behaviour");

                    ctx.SetVariableFromAny("a", a);
                    ctx.SetVariableFromAny("b", b);
                    ctx.SetVariableFromAny("base1", base1);


                    ctx.Execute("(function(){a.Add(null);})()");  //Add(T a)
                    ctx.Execute("(function(){a.Add(b);})()");     //Add(T a)
                    ctx.Execute("(function(){a.Add(base1);})()"); //Add(Base a)
                    ctx.Execute("(function(){a.Add({});})()");    // Add(object a)
                    ctx.Execute("(function(){a.Add([]);})()");    // Add(object a)

                    // if we get to here, we haven't thrown the exception
                    stwatch.Stop();
                    Console.WriteLine("met4 managed reflection:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#16
0
        private void button1_Click(object sender, EventArgs e)
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif

            JsTypeDefinition jstypedef = new JsTypeDefinition("AA");
            jstypedef.AddMember(new JsMethodDefinition("B", args =>
            {
                args.SetResult(100);
            }));
            jstypedef.AddMember(new JsMethodDefinition("C", args =>
            {
                args.SetResult(true);
            }));
            //===============================================================
            //create js engine and context
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext())
                {
                    if (!jstypedef.IsRegisterd)
                    {
                        ctx.RegisterTypeDefinition(jstypedef);
                    }
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Start();


                    TestMe1 t1 = new TestMe1();
                    //wrap t1 with custom js type definition
                    INativeScriptable proxy = ctx.CreateWrapper(t1, jstypedef);
                    ctx.SetVariableFromAny("x", proxy);
                    for (int i = 2000; i >= 0; --i)
                    {
                        object result = ctx.Execute("(function(){if(x.C()){return x.B();}else{return 0;}})()");
                    }

                    stwatch.Stop();

                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#17
0
        private void button9_Click(object sender, EventArgs e)
        {
            //------------------------
            //test esprima package
            //------------------------

            string        esprima_code = File.ReadAllText("d:\\projects\\Espresso\\js_tools\\esprima\\esprima.js");
            StringBuilder stbuilder    = new StringBuilder();

            stbuilder.Append(esprima_code);


            int version = JsBridge.LibVersion;

#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext(new MyJsTypeDefinitionBuilder()))
                {
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Reset();
                    stwatch.Start();

                    var ab = new AboutMe();
                    ctx.SetVariableAutoWrap("aboutme1", ab);

                    string testsrc = @"(function(){
                            var syntax= esprima.parse('var answer = 42');
                            //convert to json format and send to managed side
                            aboutme1.SetResult(JSON.stringify(syntax, null, 4));         
                    })()";
                    stbuilder.Append(testsrc);
                    ctx.Execute(stbuilder.ToString());

                    stwatch.Stop();
                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            VroomJs.AssemblyLoader.EnsureLoaded();
            if (FunctionValidation == null)
            {
                throw new ArgumentNullException("The value is mut be not null");
            }
            bool valid = false;

            using (JsContext context = js.CreateContext())
            {
                String execute = String.Format("var fn = {{ exec: {0} }}", FunctionValidation);
                // Create a global variable on the JS side.
                context.Execute(execute);
                // Get it and use "dynamic" to tell the compiler to use runtime binding.
                dynamic x = context.GetVariable("fn");
                // Call the method and print the result.
                valid = (bool)x.exec(value);
            }

            return(valid);
        }
示例#19
0
        private void ScriptThread(object obj)
        {
            workQueue.Enqueue(InitializeJsGlobals);
            JsEngine.RunJsEngine(Debugger.IsAttached ? new string[] { "--inspect", "hello.espr" } : new string[] { "hello.espr" },
                                 (IntPtr nativeEngine, IntPtr nativeContext) =>
            {
                _engine  = new JsEngine(nativeEngine);
                _context = _engine.CreateContext(nativeContext);

                JsTypeDefinition jstypedef = new JsTypeDefinition("LibEspressoClass");
                jstypedef.AddMember(new JsMethodDefinition("LoadMainSrcFile", args =>
                {
                    args.SetResult(@"
function MainLoop() {
    LibEspresso.Next();
    setImmediate(MainLoop);
}
MainLoop();");
                }));

                jstypedef.AddMember(new JsMethodDefinition("Log", args =>
                {
                    Console.WriteLine(args.GetArgAsObject(0));
                }));

                jstypedef.AddMember(new JsMethodDefinition("Next", args =>
                {
                    //call from js server
                    System.Action work;
                    if (workQueue.TryDequeue(out work))
                    {
                        work();
                    }
                }));
                _context.RegisterTypeDefinition(jstypedef);
                _context.SetVariableFromAny("LibEspresso", _context.CreateWrapper(new object(), jstypedef));
            });
        }
示例#20
0
        public static void Main(string[] args)
        {
            AssemblyLoader.EnsureLoaded();

            while (true)
            {
                using (JsEngine js = new JsEngine(4, 32))
                {
                    using (JsContext context = js.CreateContext())
                    {
                        // Create a global variable on the JS side.
                        context.Execute("var x = {'answer':42, 'tellme':function (x) { return x+' '+this.answer; }}");
                        // Get it and use "dynamic" to tell the compiler to use runtime binding.
                        dynamic x = context.GetVariable("x");
                        // Call the method and print the result. This will print:
                        // "What is the answer to ...? 42"
                        Console.WriteLine(x.tellme("What is the answer to ...?"));
                    }
                    GC.Collect();
                    js.DumpHeapStats();
                }
            }
        }
示例#21
0
        private void initV8()
        {
            Espresso.JsBridge.V8Init();
            _jsEngine  = new JsEngine();
            _jsContext = _jsEngine.CreateContext();

            // load the bootstrap / interface class; EspressV8Interface
            loadJsFile("sanderling-v8-lib/require");
            // _jsContext.Execute("(function(v8AppIface){ require(['sanderling-v8/bootstrap'], function(bootstrap) { bootstrap.init(todo); }); })(todo);");


            // test interface
            var version = "0.0.0";

            //var version = _jsContext.Execute("(function() { var res = null; require(['sanderling-v8/v8/interface/Espresso'], function(EspressoV8Interface) { res = new EspressoV8Interface().getVersion(); } ); return res; })();");
            if (!VERSION.Equals(version))
            {
                throw new Exception("Cannot init espresso: JS class file not loaded or version mismatch.");
            }

            log("JS interface v" + version + " loaded.");
            log("Initialized V8 JS engine.");
        }
示例#22
0
        private void button7_Click(object sender, EventArgs e)
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext(new MyJsTypeDefinitionBuilder()))
                {
                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Reset();
                    stwatch.Start();

                    var ab = new AboutMe();
                    ctx.SetVariableAutoWrap("x", ab);

                    //string testsrc = "x.IsOK;";
                    string testsrc = "x.NewAboutMe();";
                    object result  = ctx.Execute(testsrc);
                    stwatch.Stop();

                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#23
0
        static void Main()
        {
            //-----------------------------------
            //1.
            //after we build nodejs in dll version
            //we will get node.dll
            //then just copy it to another name 'libespr'
            string currentdir = System.IO.Directory.GetCurrentDirectory();
            string libEspr    = @"../../../node-v8.4.0/Release/libespr.dll";

            if (File.Exists(libEspr))
            {
                //delete the old one
                File.Delete(libEspr);
            }
            File.Copy(
                @"../../../node-v8.4.0/Release/node.dll", //from
                libEspr);
            //-----------------------------------
            //2. load libespr.dll (node.dll)

            IntPtr intptr     = LoadLibrary(libEspr);
            int    errCode    = GetLastError();
            int    libesprVer = JsBridge.LibVersion;

#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //------------
            JsEngine.RunJsEngine((IntPtr nativeEngine, IntPtr nativeContext) =>
            {
                JsEngine eng  = new JsEngine(nativeEngine);
                JsContext ctx = eng.CreateContext(nativeContext);
                //-------------
                //this LibEspressoClass object is need,
                //so node can talk with us,
                //-------------
                JsTypeDefinition jstypedef = new JsTypeDefinition("LibEspressoClass");
                jstypedef.AddMember(new JsMethodDefinition("LoadMainSrcFile", args =>
                {
                    string filedata = @"var http = require('http');
                                                (function t(){
	                                                console.log('hello from Espresso-ND');
	                                                var server = http.createServer(function(req, res) {
                                                    res.writeHead(200);
                                                    res.end('Hello! from Espresso-ND');
                                                    });
                                                    server.listen(8080,'localhost');
                                                })();";
                    args.SetResult(filedata);
                }));
                jstypedef.AddMember(new JsMethodDefinition("C", args =>
                {
                    args.SetResult(true);
                }));
                jstypedef.AddMember(new JsMethodDefinition("E", args =>
                {
                    args.SetResult(true);
                }));
                if (!jstypedef.IsRegisterd)
                {
                    ctx.RegisterTypeDefinition(jstypedef);
                }
                //----------
                //then register this as x***
                //this object is just an instance for reference
                ctx.SetVariableFromAny("LibEspresso",
                                       ctx.CreateWrapper(new object(), jstypedef));
            });

            string userInput = Console.ReadLine();
        }
示例#24
0
 public void Setup()
 {
     jsEngine = new JsEngine();
     js = jsEngine.CreateContext();
 }
示例#25
0
        private void button6_Click(object sender, EventArgs e)
        {
            string filename = @"..\..\..\HtmlRenderer.Demo\Samples\ClassicSamples\00.Intro.htm";

            //1. blank html
            var fileContent = "<html><body><div id=\"a\">A</div><div id=\"b\" style=\"background-color:blue\">B</div><div id=\"c\">c_node</div></body></html>";

            easeViewport.LoadHtml(filename, fileContent);
            //----------------------------------------------------------------
            //after load html page

            //load v8 if ready
            JsBridge.LoadV8("..\\..\\dll\\VRoomJsNative.dll");
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //===============================================================

            //2. access dom

            var webdoc = easeViewport.GetHtmlDom() as LayoutFarm.WebDom.IHtmlDocument;
            //create js engine and context
            if (myengine == null)
            {
                var jstypeBuilder = new LayoutFarm.Scripting.MyJsTypeDefinitionBuilder();
                myengine = new JsEngine();
                myCtx    = myengine.CreateContext(jstypeBuilder);
            }

            System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
            stwatch.Reset();
            stwatch.Start();


            myCtx.SetVariableAutoWrap("document", webdoc);
            myCtx.SetVariableAutoWrap("console", myWbConsole);
            string simplejs = @"
                    (function(){
                        console.log('hello world!');
                        var domNodeA = document.getElementById('a');
                        var domNodeB = document.getElementById('b');
                        var domNodeC = document.getElementById('c');

                        var newText1 = document.createTextNode('... says hello world!');
                        domNodeA.appendChild(newText1);
                        for(var i=0;i<10;++i){
                            var newText2= document.createTextNode(i);
                            domNodeA.appendChild(newText2);       
                        } 

                        var newDivNode= document.createElement('div');
                        newDivNode.appendChild(document.createTextNode('new div'));
                        newDivNode.attachEventListener('mousedown',function(){console.log('new div');});
                        domNodeB.appendChild(newDivNode);    
                        
                        domNodeC.innerHTML='<div> from inner html <span> from span</span> </div>';
                        console.log(domNodeC.innerHTML);
                    })();
                ";

            object testResult = myCtx.Execute(simplejs);
            stwatch.Stop();

            Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());



            ////3. get element by id
            //var domNodeA = webdoc.GetElementById("a");
            //var domNodeB = webdoc.GetElementById("b");

            //domNodeA.AddTextContent("Hello from A");
            //domNodeB.AddChild("div", div =>
            //{
            //    div.SetAttribute("style", "background-color:yellow");
            //    div.AddTextContent("Hello from B");
            //});

            //domNodeB.AttachMouseDownEvent(ev =>
            //{
            //    var domB = new EaseDomElement(domNodeB);
            //    domB.SetBackgroundColor(Color.Red);
            //    ev.StopPropagation();
            //    //domNodeB.SetAttribute("style", "background-color:red");
            //});
            //domNodeB.AttachMouseUpEvent(ev =>
            //{
            //    var domB = new EaseDomElement(domNodeB);
            //    domB.SetBackgroundColor(Color.Yellow);
            //    ev.StopPropagation();
            //    //domNodeB.SetAttribute("style", "background-color:red");
            //});
        }
示例#26
0
        private void button5_Click(object sender, EventArgs e)
        {
            //1. init html
            var fileContent = "<html><body><div id=\"a\">A</div><div id=\"b\" style=\"background-color:blue\">B</div></body></html>";

            easeViewport.LoadHtmlString("", fileContent);
            //----------------------------------------------------------------
            //after load html page

            //test javascript ...

#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //===============================================================

            //2. access dom

            var webdoc = easeViewport.GetHtmlDom() as IHtmlDocument;
            //create js engine and context
            var jstypeBuilder = new LayoutFarm.Scripting.MyJsTypeDefinitionBuilder();
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext(jstypeBuilder))
                {
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Reset();
                    stwatch.Start();
                    ctx.SetVariableAutoWrap("document", webdoc);
                    string testsrc1 = "document.getElementById('a');";
                    object domNodeA = ctx.Execute(testsrc1);
                    string testsrc2 = "document.getElementById('b');";
                    object domNodeB = ctx.Execute(testsrc2);
                    stwatch.Stop();
                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                }

            ////3. get element by id
            //var domNodeA = webdoc.GetElementById("a");
            //var domNodeB = webdoc.GetElementById("b");

            //domNodeA.AddTextContent("Hello from A");
            //domNodeB.AddChild("div", div =>
            //{
            //    div.SetAttribute("style", "background-color:yellow");
            //    div.AddTextContent("Hello from B");
            //});

            //domNodeB.AttachMouseDownEvent(ev =>
            //{
            //    var domB = new EaseDomElement(domNodeB);
            //    domB.SetBackgroundColor(Color.Red);
            //    ev.StopPropagation();
            //    //domNodeB.SetAttribute("style", "background-color:red");
            //});
            //domNodeB.AttachMouseUpEvent(ev =>
            //{
            //    var domB = new EaseDomElement(domNodeB);
            //    domB.SetBackgroundColor(Color.Yellow);
            //    ev.StopPropagation();
            //    //domNodeB.SetAttribute("style", "background-color:red");
            //});
        }
示例#27
0
        static void Main()
        {
            //-----------------------------------
            //1.
            //after we build nodejs in dll version
            //we will get node.dll
            //then just copy it to another name 'libespr'
            string currentdir = System.IO.Directory.GetCurrentDirectory();
            string libEspr    = @"../../../node-v8.1.4/Release/libespr.dll";

            if (File.Exists(libEspr))
            {
                //delete the old one
                File.Delete(libEspr);
            }
            File.Copy(
                @"../../../node-v8.1.4/Release/node.dll", //from
                libEspr);
            //-----------------------------------
            //2. load libespr.dll (node.dll)

            IntPtr intptr     = LoadLibrary(libEspr);
            int    errCode    = GetLastError();
            int    libesprVer = JsBridge.LibVersion;

            //change working dir to target app and run
            //test with socket.io's chat sample
            System.IO.Directory.SetCurrentDirectory(@"../../../socket.io/examples/chat");

#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //------------
            JsEngine.RunJsEngine((IntPtr nativeEngine, IntPtr nativeContext) =>
            {
                JsEngine eng  = new JsEngine(nativeEngine);
                JsContext ctx = eng.CreateContext(nativeContext);
                //-------------
                //this LibEspressoClass object is need,
                //so node can talk with us,
                //-------------
                JsTypeDefinition jstypedef = new JsTypeDefinition("LibEspressoClass");
                jstypedef.AddMember(new JsMethodDefinition("LoadMainSrcFile", args =>
                {
                    //since this is sample socket io app
                    string filedata = File.ReadAllText("index.js");
                    args.SetResult(filedata);
                }));
                jstypedef.AddMember(new JsMethodDefinition("C", args =>
                {
                    args.SetResult(true);
                }));
                jstypedef.AddMember(new JsMethodDefinition("E", args =>
                {
                    args.SetResult(true);
                }));
                if (!jstypedef.IsRegisterd)
                {
                    ctx.RegisterTypeDefinition(jstypedef);
                }
                //----------
                //then register this as x***
                //this object is just an instance for reference
                ctx.SetVariableFromAny("LibEspresso",
                                       ctx.CreateWrapper(new object(), jstypedef));
            });

            string userInput = Console.ReadLine();
        }
示例#28
0
        private void button5_Click(object sender, EventArgs e)
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            JsTypeDefinition jstypedef = new JsTypeDefinition("AA");
            jstypedef.AddMember(new JsMethodDefinition("B", args =>
            {
                int argCount = args.ArgCount;
                var thisArg  = args.GetThisArg();
                var arg0     = args.GetArgAsObject(0);
                args.SetResult((bool)arg0);
            }));
            jstypedef.AddMember(new JsMethodDefinition("C", args =>
            {
                args.SetResult(true);
            }));

            //-----------------------------------------------------
            jstypedef.AddMember(new JsPropertyDefinition("D",
                                                         args =>
            {
                var ab = new AboutMe();
                args.SetResultAutoWrap(ab);
            },
                                                         args =>
            {
                //setter
            }));
            jstypedef.AddMember(new JsPropertyDefinition("E",
                                                         args =>
            {       //getter
                args.SetResult(250);
            },
                                                         args =>
            {
                //setter
            }));
            //===============================================================
            //create js engine and context
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext())
                {
                    ctx.RegisterTypeDefinition(jstypedef);

                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Reset();
                    stwatch.Start();


                    TestMe1 t1 = new TestMe1();

                    INativeScriptable proxy = ctx.CreateWrapper(t1, jstypedef);
                    ctx.SetVariable("x", proxy);


                    //string testsrc = "x.B(x.D.IsOK);";
                    string testsrc = "x.B(x.D.GetOK());";
                    object result  = ctx.Execute(testsrc);
                    stwatch.Stop();

                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                }
        }
示例#29
0
        private void button3_Click(object sender, EventArgs e)
        {
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            JsTypeDefinition jstypedef = new JsTypeDefinition("AA");
            jstypedef.AddMember(new JsMethodDefinition("B", args =>
            {
                args.SetResult(100);
            }));
            jstypedef.AddMember(new JsMethodDefinition("C", args =>
            {
                args.SetResult(true);
            }));

            jstypedef.AddMember(new JsPropertyDefinition("D",
                                                         args =>
            {       //getter
                args.SetResult(true);
            },
                                                         args =>
            {
                //setter
            }));
            jstypedef.AddMember(new JsPropertyDefinition("E",
                                                         args =>
            {       //getter
                args.SetResult(250);
            },
                                                         args =>
            {
                //setter
            }));

            //===============================================================
            //create js engine and context
            using (JsEngine engine = new JsEngine())
                using (JsContext ctx = engine.CreateContext())
                {
                    ctx.RegisterTypeDefinition(jstypedef);

                    GC.Collect();
                    System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                    stwatch.Reset();
                    stwatch.Start();

                    TestMe1 t1    = new TestMe1();
                    var     proxy = ctx.CreateWrapper(t1, jstypedef);

                    //for (int i = 2000; i >= 0; --i)
                    //{
                    ctx.SetVariableFromAny("x", proxy);
                    //object result = ctx.Execute("(function(){if(x.C()){return  x.B();}else{return 0;}})()");
                    object result = ctx.Execute("(function(){if(x.D){ x.E=300; return  x.B();}else{return 0;}})()");

                    //}
                    stwatch.Stop();

                    Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                    //Assert.That(result, Is.EqualTo(100));
                }
        }
示例#30
0
 public void Setup()
 {
     jsEngine = new JsEngine();
     js       = jsEngine.CreateContext();
 }
示例#31
0
        public static void Main(string[] args)
        {
            // string lodash = File.ReadAllText(@"c:\lodash.js");
            using (JsEngine engine = new JsEngine())
            {
                //Stopwatch watch = new Stopwatch();
                //	watch.Start();
                JsScript script = engine.CompileScript("3+3", "<unnamed>");
                using (JsContext ctx = engine.CreateContext())
                {
                    ctx.Execute(script);
                }
            }

            debugtest dbg = new debugtest();

            //	Delegate.CreateDelegate()
            //Dictionary<string, object> values = new Dictionary<string, object>();

            //values["test"] = 333;
            while (true)
            {
                using (JsEngine js = new JsEngine(4, 32))
                {
                    using (JsContext context = js.CreateContext())
                    {
                        //context.SetVariable("dbg", dbg);
                        //object result = context.Execute("dbg.Write(dbg.valueOf());");
                        context.SetVariableFromAny("Debug", typeof(debugtest));

                        object result = context.Execute("Debug.BoolTest(3,4);");
                    }
                    GC.Collect();
                    js.DumpHeapStats();
                }
            }


            //context.SetVariable("values", values);
            //object result = context.Execute("dbg.runFunc(); values.test ? true : false;");



            //	object result =
            //	context.Execute("var obj = { test: 0 }; obj.ft = function (v) { dbg.Write(v); return 'from JS'; }; dbg.runFunc(obj.ft); dbg.write(obj.test);");

            //int a = 1;

            //	context.SetFunction("runfunc", new Func<int, bool>(Activate));
            //object result = context.Execute("runfunc(2);");
            //  }

            //		}
            //}

            /*using (JsEngine js = new JsEngine()) {
             *  using (JsContext context = js.CreateContext()) {
             *      using (JsScript script = js.CompileScript("3 * 4")) {
             *          object result = context.Execute(script, TimeSpan.FromHours(200));
             *          Console.WriteLine(result);
             *      }
             *  }
             * }*/

            //return;

            /*
             * using (JsEngine js = new JsEngine()) {
             *  using (JsContext context = js.CreateContext()) {
             *      for (int i = 0; i < 10; i++) {
             *          context.SetVariable("a", new Simple { N = i, S = (i * 10).ToString() });
             *          Console.WriteLine(context.Execute("a.N+' '+a.S"));
             *      }
             *      Console.WriteLine(context.Execute("a.N+' '+a.X"));
             *  }
             * }*/
        }