コード例 #1
1
        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();
        }
コード例 #2
0
        void RunScript(string script, bool isDevServer, ReactScript scriptObj, List <TextAsset> preload = null, Action callback = null)
        {
            if (string.IsNullOrWhiteSpace(script))
            {
                return;
            }

            Clean();

            if (engine == null)
            {
                CreateEngine();
            }
            unityContext = new UnityUGUIContext(Root, engine, Globals, scriptObj, isDevServer);
            CreateLocation(engine, scriptObj);

            List <Action> callbacks = new List <Action>()
            {
                callback
            };

            engine.SetValue("addEventListener", new Action <string, Action>((e, f) =>
            {
                if (e == "DOMContentLoaded")
                {
                    callbacks.Add(f);
                }
            }));

            engine.SetValue("Unity", new ReactUnityAPI(engine));
            engine.SetValue("RootContainer", unityContext.Host);
            engine.SetValue("Globals", Globals);
            try
            {
                if (preload != null)
                {
                    preload.ForEach(x => engine.Execute(x.text));
                }
                engine.Execute(script);
                callbacks.ForEach(x => x?.Invoke());
            }
            catch (ParserException ex)
            {
                Debug.LogError($"Parser exception in line {ex.LineNumber} column {ex.Column}");
                Debug.LogException(ex);
            }
            catch (Jint.Runtime.JavaScriptException ex)
            {
                Debug.LogError($"JS exception in line {ex.LineNumber} column {ex.Column}");
                Debug.LogException(ex);
            }
            catch (Jint.Runtime.JintException ex)
            {
                Debug.LogException(ex);
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
            }
        }
コード例 #3
0
        protected override object InnerEvaluate(string expression)
        {
            OriginalJsValue resultValue;

            try
            {
                resultValue = _jsEngine.Execute(expression).GetCompletionValue();
            }
            catch (OriginalParserException e)
            {
                throw ConvertParserExceptionToJsRuntimeException(e);
            }
            catch (OriginalJsException e)
            {
                throw ConvertJavaScriptExceptionToJsRuntimeException(e);
            }
            catch (OriginalRecursionDepthOverflowException e)
            {
                throw ConvertRecursionDepthOverflowExceptionToJsRuntimeException(e);
            }
            catch (OriginalStatementsCountOverflowException e)
            {
                throw ConvertStatementsCountOverflowExceptionToJsRuntimeException(e);
            }
            catch (TimeoutException e)
            {
                throw ConvertTimeoutExceptionToJsRuntimeException(e);
            }

            object result = MapToHostType(resultValue);

            return(result);
        }
コード例 #4
0
 void CreatePolyfills(Jint.Engine engine)
 {
     // Load polyfills
     engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/promise").text);
     engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/base64").text);
     engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/fetch").text);
 }
コード例 #5
0
ファイル: ScriptPlugin.cs プロジェクト: mldYM/IW4M-Admin
 public Task OnEventAsync(GameEvent E, Server S)
 {
     lock (ScriptEngine)
     {
         ScriptEngine.SetValue("_gameEvent", E);
         ScriptEngine.SetValue("_server", S);
         ScriptEngine.SetValue("_IW4MAdminClient", Utilities.IW4MAdminClient(S));
         return(Task.FromResult(ScriptEngine.Execute("plugin.onEventAsync(_gameEvent, _server)").GetCompletionValue()));
     }
 }
コード例 #6
0
ファイル: QQEncryptor.cs プロジェクト: huoshan12345/iQQ.Net
 /// <summary>
 /// 获取好友列表时计算的Hash参数 v2014.06.14更新
 /// </summary>
 /// <param name="uin"></param>
 /// <param name="ptwebqq"></param>
 /// <returns></returns>
 public static string GetHash(string uin, string ptwebqq)
 {
     const string url = "https://raw.githubusercontent.com/im-qq/webqq-core/master/src/main/resources/hash.js";
     var js = Resource.LoadResourceAsync("hash.js", url, item => item.ToString(Encoding.UTF8)).Result;
     object[] args = { uin, ptwebqq };
     var code = string.Format("hash('{0}','{1}')", args);
     var engine = new Jint.Engine();
     engine.Execute(js);
     var s = engine.Execute(code).GetCompletionValue().AsString();
     return s;
 }
コード例 #7
0
        private static string RsaQQ(long uin, string password, string verifyCode)
        {
            var js = Resource.LoadLocalResource("encrypt.js", stream => stream.ToString(Encoding.UTF8));

            object[] args   = { password, uin, verifyCode.ToUpper(), IsMd5(password).ToString().ToLower() };
            var      code   = string.Format("getEncryption('{0}','{1}','{2}',{3})", args);
            var      engine = new Jint.Engine();

            engine.Execute(js);
            var s = engine.Execute(code).GetCompletionValue().AsString();

            return(s);
        }
コード例 #8
0
        void CreateLocation(Jint.Engine engine)
        {
            engine.SetValue("location", context.Location);

            engine.Execute(@"WebSocket = function(url) { return new WebSocket.original(Context, url); }");
            engine.Execute(@"XMLHttpRequest = function() { return new XMLHttpRequest.original(Context, location.origin); }");
            (engine.GetValue(@"WebSocket") as FunctionInstance)
            .FastSetProperty("original", new Jint.Runtime.Descriptors.PropertyDescriptor(TypeReference.CreateTypeReference(engine, typeof(WebSocketProxy)), false, false, false));
            (engine.GetValue(@"XMLHttpRequest") as FunctionInstance)
            .FastSetProperty("original", new Jint.Runtime.Descriptors.PropertyDescriptor(TypeReference.CreateTypeReference(engine, typeof(XMLHttpRequest)), false, false, false));

            engine.SetValue("document", new DocumentProxy(context, this.ExecuteScript, context.Location.origin));
        }
コード例 #9
0
 void CreateScheduler(Jint.Engine engine)
 {
     scheduler = new UnityScheduler();
     engine.SetValue("UnityScheduler", scheduler);
     engine.Execute("global.setTimeout = function setTimeout(fun, delay) { return UnityScheduler.setTimeout(new Callback(fun), delay); }");
     engine.Execute("global.setInterval = function setInterval(fun, delay) { return UnityScheduler.setInterval(new Callback(fun), delay); }");
     engine.Execute("global.setImmediate = function setImmediate(fun) { return UnityScheduler.setImmediate(new Callback(fun)); }");
     engine.Execute("global.requestAnimationFrame = function requestAnimationFrame(fun) { return UnityScheduler.requestAnimationFrame(new Callback(fun)); }");
     engine.SetValue("clearTimeout", new Action <int?>(scheduler.clearTimeout));
     engine.SetValue("clearInterval", new Action <int?>(scheduler.clearInterval));
     engine.SetValue("clearImmediate", new Action <int?>(scheduler.clearImmediate));
     engine.SetValue("cancelAnimationFrame", new Action <int?>(scheduler.cancelAnimationFrame));
 }
コード例 #10
0
ファイル: ReactUnityRunner.cs プロジェクト: gaozhou/core-1
        void CreateEngine()
        {
            engine = new Jint.Engine(x =>
            {
                x.AllowClr(
                    typeof(System.Convert).Assembly,
#if UNITY_EDITOR
                    typeof(UnityEditor.EditorWindow).Assembly,
                    typeof(UnityEngine.GUILayout).Assembly,
                    typeof(UnityEngine.UIElements.StyleLength).Assembly,
#endif
                    typeof(UnityEngine.Vector3).Assembly,
                    typeof(UnityEngine.Component).Assembly,
                    typeof(ReactUnityRunner).Assembly
                    );
                x.CatchClrExceptions(ex =>
                {
                    Debug.LogException(ex);
                    return(true);
                });
            });

            engine.SetValue("log", new Func <object, object>((x) => { Debug.Log(x); return(x); }));
            engine.Execute("__dirname = '';");
            engine.Execute("WeakMap = Map;");
            engine.Execute("globalThis = global = window = parent = this;");
            engine.Execute("setTimeout = setInterval = clearTimeout = clearInterval = null;");
            engine.Execute("btoa = atob = null;");
            engine.Execute("process = { env: { NODE_ENV: 'production' }, argv: [], on: () => {} };");

            engine.SetValue("Engine", engine);
            engine.SetValue("Callback", typeof(Callback));

            CreateConsole(engine);
            CreateLocalStorage(engine);
            CreateScheduler(engine, context);

            engine.SetValue("importType", new ClrFunctionInstance(
                                engine,
                                "importType",
                                func: (thisObj, arguments) => TypeReference.CreateTypeReference(engine,
                                                                                                ReflectionHelpers.FindType(TypeConverter.ToString(arguments.At(0)),
                                                                                                                           arguments.Length > 1 ? TypeConverter.ToBoolean(arguments.At(1)) : false))));

            engine.SetValue("UnityEngine", new Jint.Runtime.Interop.NamespaceReference(engine, "UnityEngine"));
            engine.SetValue("ReactUnity", new Jint.Runtime.Interop.NamespaceReference(engine, "ReactUnity"));
            engine.SetValue("Facebook", new Jint.Runtime.Interop.NamespaceReference(engine, "Facebook"));
#if UNITY_EDITOR
            engine.SetValue("UnityEditor", new Jint.Runtime.Interop.NamespaceReference(engine, "UnityEditor"));
#endif

            // Load polyfills
            engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/promise").text);
            engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/base64").text);
            engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/fetch").text);
        }
コード例 #11
0
        /// <summary>
        /// 获取好友列表时计算的Hash参数 v2014.06.14更新
        /// </summary>
        /// <param name="uin"></param>
        /// <param name="ptwebqq"></param>
        /// <returns></returns>
        public static string GetHash(string uin, string ptwebqq)
        {
            const string url = "https://raw.githubusercontent.com/im-qq/webqq-core/master/src/main/resources/hash.js";
            var          js  = Resource.LoadResourceAsync("hash.js", url, item => item.ToString(Encoding.UTF8)).Result;

            object[] args   = { uin, ptwebqq };
            var      code   = string.Format("hash('{0}','{1}')", args);
            var      engine = new Jint.Engine();

            engine.Execute(js);
            var s = engine.Execute(code).GetCompletionValue().AsString();

            return(s);
        }
コード例 #12
0
        public void string_add()
        {
            var engine = new Jint.Engine();

            // load js
            engine.Execute(js);
            var answer = engine
                         .Execute("stradd(1,2);")
                         .GetCompletionValue()
                         .ToObject()
                         .ToString();

            answer.Should().Be("1 2");
        }
コード例 #13
0
ファイル: ReactUnityRunner.cs プロジェクト: gaozhou/core-1
        void CreateLocation(Jint.Engine engine)
        {
            var location = new DomProxies.Location(context);

            engine.SetValue("location", location);

#if UNITY_EDITOR || REACT_DEV_SERVER_API
            engine.SetValue("ctx", context);
            engine.SetValue("oldWebSocket", typeof(WebSocketProxy));
            engine.Execute(@"WebSocket = function() { return new oldWebSocket(ctx, ...arguments); }");
            engine.SetValue("oldXMLHttpRequest", typeof(XMLHttpRequest));
            engine.Execute(@"XMLHttpRequest = function() { return new oldXMLHttpRequest('" + location.origin + @"'); }");
#endif
            engine.SetValue("document", new DocumentProxy(context, this.ExecuteScript, location.origin));
        }
コード例 #14
0
ファイル: pacparser.cs プロジェクト: ststeiger/TelSearch
        public static void Test()
        {
            string pacFile = @"D:\username\Downloads\PacProxyUsage_src\Proxy.pac";

            System.Uri uri = new System.Uri("https://www.microsoft.com/foobar.htm");

            string proxy = null;


            Jint.Engine engine = new Jint.Engine()
                                 .SetValue("dnsResolve", new System.Func <string, string>(dnsResolve))
                                 .SetValue("isInNet", new System.Func <string, string, string, bool>(isInNet))
                                 .SetValue("isPlainHostName", new System.Func <string, string>(dnsResolve))
                                 .SetValue("localHostOrDomainIs", new System.Func <string, string>(dnsResolve))
                                 .SetValue("dnsDomainIs", new System.Func <string, string>(dnsResolve))
                                 .SetValue("myIpAddress", new System.Func <string, string>(dnsResolve))
                                 //.SetValue("log", new System.Action<object>(Console.WriteLine))
                                 // .SetValue("log", new System.Action<string>(delegate (object obj) { System.Console.WriteLine(obj); }))
                                 .SetValue("getProxy", new System.Action <string>(delegate(string obj) { proxy = obj; }))
            ;



            string script = null;

            using (System.IO.StreamReader streamReader = new System.IO.StreamReader(pacFile))
            {
                script = streamReader.ReadToEnd();
                streamReader.Close();
            }
            engine.Execute(script);
            // https://developer.mozilla.org/en-US/docs/Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_(PAC)_file
            engine.Execute(string.Format(@"getProxy(FindProxyForURL('{0}', '{1}'));", uri.Authority, uri.Host));
            System.Console.WriteLine(proxy);



            // engine.Execute(@"
            // log(dnsResolve('www.perdu.com'));
            // log(isInNet('198.95.249.79', '198.95.249.79', '255.255.255.255'));
            // log(isInNet('198.95.249.79', '198.95.0.0', '255.255.0.0'));
            // log(isInNet('198.95.249.12', '198.95.249.79', '255.255.255.255'));
            // log(isInNet('198.95.249.12', '198.95.0.0', '255.255.0.0'));
            // log(isInNet('198.12.249.79', '198.95.0.0', '255.255.0.0'));
            // ");

            //Console.Read();
        }
コード例 #15
0
ファイル: GameActor.cs プロジェクト: MehYam/ScryptTheCrypt
 public void SetScrypt(string js)
 {
     jint = new Jint.Engine();
     jint.SetValue("Alignment_Mob", Alignment.Mob);
     jint.SetValue("Alignment_Player", Alignment.Player);
     jint.Execute(js);
 }
コード例 #16
0
        static void basics()
        {
            var engine = new Jint.Engine();

            engine.SetValue("log", new Action <object>(Console.WriteLine));
            engine.Execute("log('hello from Jint')");

            engine.Execute("var foo = 'bar';");
            engine.Execute("log(foo)");

            engine.Execute(@"
            var array = [ 1, 2, 3 ];
            var array2 = array.filter(function(i) { return i > 1; });
            log('filtered array length: ' + array2.length);
            ");
        }
コード例 #17
0
        public void JintCanAccessGame()
        {
            // This is a less valid test now vs. when we were using Moonsharp/Lua.  Then,
            // we were testing that the classes were registered correctly in the script
            // engine, now, we're just sort of testing that Jint works.
            var script = new Jint.Engine();

            script.Execute(@"
                function fireGameEvent(events, game)
                {
                    events.RoundStart_Fire(game);
                }
            ");

            var  game  = new Game();
            bool fired = false;

            GameEvents.Instance.RoundStart += g =>
            {
                fired = true;
                Assert.AreEqual(game, g);
            };
            script.Invoke("fireGameEvent", GameEvents.Instance, game);
            Assert.IsTrue(fired);
        }
コード例 #18
0
ファイル: ScriptEngineService.cs プロジェクト: tgiachi/Neon
 public void LoadFile(string fileName, bool immediateExecute)
 {
     try
     {
         _logger.LogInformation($"Loading file {fileName}...");
         _filesContents.Add(fileName, File.ReadAllText(fileName));
         if (immediateExecute)
         {
             _engine.Execute(_filesContents[fileName]);
         }
     }
     catch (Exception ex)
     {
         _logger.LogError($"Error during load file {fileName} => {ex}");
     }
 }
コード例 #19
0
        public void Run_Code(FrmApp pApp, string run_codestr1)
        {
            p_Engine = new Jint.Engine();


            //非静态变量
            p_Engine.SetValue("s_sys", pApp.pSYS);
            p_Engine.SetValue("s_ui", pApp.pUI);


            //静态变量,只有一个
            p_Engine.SetValue("s_tcp", FrmApp.pTCP);
            p_Engine.SetValue("s_index", FrmApp.pIndex);// new C_Index(pApp));

            //其他
            p_Engine.SetValue("s_math", new S_Math());
            p_Engine.SetValue("s_string", new C_String());
            p_Engine.SetValue("s_net", new C_Net(pApp));
            p_Engine.SetValue("s_time", pApp.pTime);
            p_Engine.SetValue("s_xml", new C_XML());
            p_Engine.SetValue("s_file", new C_File(pApp));
            p_Engine.SetValue("s_au3", new C_AU3(pApp));


            try
            {
                p_Engine.Execute(run_codestr1);
            }
            catch (Exception eee)
            {
                MessageBox.Show("error in script run:" + eee.Message + eee.StackTrace);
            }
        }
コード例 #20
0
        /// <summary>
        /// Executes the provided string on the Javascript engine.
        /// </summary>
        /// <param name="script">The script to execute.</param>
        /// <param name="safe">Whether to run the script safely.</param>
        /// <returns></returns>
        public object RunScript(string script, bool safe = true)
        {
            if (safe)
            {
                script = "(function () { return " + script + "; })()";
            }

            try
            {
                // Run the script and get the response.
                object scriptResponse = _interpreter.Execute(script).GetCompletionValue();

                // If it isn't empty log it.
                if (scriptResponse != null)
                {
                    Debugger.Log(MessageType.Info, MessageSource.ScriptingEngine, "Script executed, result: " + scriptResponse);
                }

                // Return the response.
                return(scriptResponse);
            }
            catch (Exception ex)
            {
                // Check if timeout, and if not throw an exception.
                if (ex.Message != "The operation has timed out." && Context.Settings.StrictScripts)
                {
                    throw ex;
                }

                Debugger.Log(MessageType.Error, MessageSource.ScriptingEngine, "Scripting error: " + ex);
                Debugger.Log(MessageType.Error, MessageSource.ScriptingEngine, " " + script);

                return(null);
            }
        }
コード例 #21
0
        public bool Process(FileInfo file)
        {
            Jint.Engine engine = new Jint.Engine(cfg => cfg.AllowClr(
                                                     Assembly.GetAssembly(typeof(TagLib.File))
                                                     ));
            engine.SetValue("file", file);

            var delegates = ProcessorExtensions.Delegates;

            foreach (Delegate dele in delegates)
            {
                engine.SetValue(dele.Method.Name, dele);
            }

            try
            {
                Jint.Engine proceed = engine.Execute(Script);
                return(proceed.GetCompletionValue().AsBoolean());
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                return(false);
            }
        }
コード例 #22
0
        private static void Router_Jint(Client Sender, RouteEventArgs E)
        {
            string FilePath = Path.Combine(WebDirectory, E.Request.Path.TrimStart('/'));

            Boolean Exists    = File.Exists(FilePath);
            Boolean WithinDir = Path.GetFullPath(FilePath).Contains(WebDirectory);
            Boolean IsDir     = Directory.Exists(FilePath);

            if (!(Exists && WithinDir && !IsDir))
            {
                Sender.Send(Response.SendStatus(400));
                return;
            }

            //Sender.Send(Response.SendFile(FilePath, false));
            string JS = File.ReadAllText(E.Request.Path);

            Jint.Engine Engine = new Jint.Engine(cfg => cfg.AllowClr(typeof(Server).Assembly).CatchClrExceptions());

            Engine.SetValue("Request", E.Request);
            Engine.SetValue("Response", new Response());

            /* try
             * {
             *   Engine.Execute(JS);
             * }
             * catch (Exception Ex)
             * {
             *   Console.WriteLine("Uncaught exception! " + Ex.Message);
             *
             *   Req.Client.Send(Response.SendText("500 - Internal Error").GetBytes());
             * }*/
            Engine.Execute(JS);
        }
コード例 #23
0
        public static object ExeConfig(Models.Code code, WebSite site)
        {
            RenderContext context = new RenderContext();

            context.WebSite = site;
            var engine   = new Jint.Engine(JintSetting.SetOption);
            var kcontext = new k(context);

            engine.SetValue("k", kcontext);

            var k = engine.GetValue("k");

            kcontext.ReturnValues.Clear();
            try
            {
                engine.Execute(code.Config);
            }
            catch (System.Exception ex)
            {
            }

            if (kcontext.ReturnValues.Count() > 0)
            {
                return(kcontext.ReturnValues.Last());
            }
            return(null);
        }
コード例 #24
0
        static void classAccessExceptions()
        {
            var engine  = new Jint.Engine();
            var someObj = new SomeClass(21, "12");

            engine.SetValue("someObj", someObj);
            engine.SetValue("callback", new Action <string>(s => { Console.WriteLine($"callback from js: {s}"); }));

            void runJs(string js)
            {
                try
                {
                    engine.Execute(js);
                    Console.WriteLine($"script <{js}> ran without issue");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"script <{js}> threw {e.GetType()}: {e.Message}");
                }
            }

            runJs("callback(someObj)");
            runJs("callback(someObj.privateReadonlyString");
            runJs("someObj.publicReadonlyString = 'foo'");
            runJs("callback(someObj.publicReadonlyString)");
            Console.WriteLine($"someObj.publicReadonlyString: {someObj.publicReadonlyString}");
        }
コード例 #25
0
 /* you must add this inside < Project > tag in your .csproj file
  * <ItemGroup>
  *  <PackageReference Include="Jint" Version="3.0.0-beta-1828"/>
  * </ItemGroup>
  */
 public DartConnector(string sourcePath)
 {
     engine = new Jint.Engine();
     engine.SetValue("CS_GD__Print", new Action <object>(o => GD.Print(o)));
     engine.SetValue("print", new Action <object>(o => GD.Print(o)));
     engine.SetValue("self", "this");
     engine.Execute(new StreamReader(sourcePath).ReadToEnd());
 }
コード例 #26
0
ファイル: ScriptPlugin.cs プロジェクト: mldYM/IW4M-Admin
        public async Task Initialize(IManager mgr)
        {
            bool firstRun = ScriptEngine == null;

            // it's been loaded before so we need to call the unload event
            if (!firstRun)
            {
                await OnUnloadAsync();
            }

            Manager = mgr;
            string script;

            using (var stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var reader = new StreamReader(stream, Encoding.Default))
                {
                    script = await reader.ReadToEndAsync();
                }
            }

            ScriptEngine = new Jint.Engine(cfg =>
                                           cfg.AllowClr(new[]
            {
                typeof(System.Net.Http.HttpClient).Assembly,
                typeof(EFClient).Assembly,
            })
                                           .CatchClrExceptions());

            ScriptEngine.Execute(script);
            ScriptEngine.SetValue("_localization", Utilities.CurrentLocalization);
            dynamic pluginObject = ScriptEngine.GetValue("plugin").ToObject();

            this.Author  = pluginObject.author;
            this.Name    = pluginObject.name;
            this.Version = (float)pluginObject.version;


            try
            {
                if (pluginObject.isParser)
                {
                    await OnLoadAsync(mgr);

                    IEventParser eventParser = (IEventParser)ScriptEngine.GetValue("eventParser").ToObject();
                    IRConParser  rconParser  = (IRConParser)ScriptEngine.GetValue("rconParser").ToObject();
                    Manager.AdditionalEventParsers.Add(eventParser);
                    Manager.AdditionalRConParsers.Add(rconParser);
                }
            }
            catch { }


            if (!firstRun)
            {
                await OnLoadAsync(mgr);
            }
        }
コード例 #27
0
        protected override object InnerEvaluate(string expression, string documentName)
        {
            object result;
            string uniqueDocumentName = _documentNameManager.GetUniqueName(documentName);

            lock (_executionSynchronizer)
            {
                OriginalValue resultValue;

                try
                {
                    var parserOptions = new OriginalParserOptions
                    {
                        Source = uniqueDocumentName
                    };
                    resultValue = _jsEngine.Execute(expression, parserOptions).GetCompletionValue();
                }
                catch (OriginalParserException e)
                {
                    throw WrapParserException(e);
                }
                catch (OriginalJavaScriptException e)
                {
                    throw WrapJavaScriptException(e);
                }
                catch (OriginalRecursionDepthOverflowException e)
                {
                    throw WrapRecursionDepthOverflowException(e);
                }
                catch (OriginalStatementsCountOverflowException e)
                {
                    throw WrapStatementsCountOverflowException(e);
                }
                catch (TimeoutException e)
                {
                    throw WrapTimeoutException(e);
                }

                result = MapToHostType(resultValue);
            }

            return(result);
        }
コード例 #28
0
ファイル: AppDomainEngine.cs プロジェクト: molekm/nucleuscoop
        public void Import(string path)
        {
            // TODO: IO Manager
            string folderPath = PackageManager.GetAssetsFolder(gameMetadata);
            string fullPath   = Path.Combine(folderPath, path);

            string jsCode = File.ReadAllText(fullPath);

            engine.Execute(jsCode);
        }
コード例 #29
0
        private static async Task Run(string url)
        {
            var baseUrl   = new Uri(url);
            var configUrl = new Uri(baseUrl, "standalone/config.js");

            var configJs = await LoadStringAsync(configUrl.ToString());

            var engine = new JintEngine();

            engine.Execute(configJs);

            var urlObj            = engine.Global.GetObject("config").url;
            var configurationUrl  = new Uri(baseUrl, urlObj.configuration);
            var configurationJson = await LoadStringAsync(configurationUrl.ToString());

            var configuration = JsonConvert.DeserializeObject <ConfigurationModel>(configurationJson);

            string updateUrlFormat = ((string)urlObj.update).Replace("{world}", "{0}").Replace("{timestamp}", "{1}");

            var update = new UpdateModel {
                timestamp = 0
            };

            while (true)
            {
                var updateUrl  = new Uri(baseUrl, string.Format(updateUrlFormat, "Main", update.timestamp));
                var updateJson = await LoadStringAsync(updateUrl.ToString());

                update = JsonConvert.DeserializeObject <UpdateModel>(updateJson);

                foreach (var updateData in update.updates)
                {
                    switch (updateData.type)
                    {
                    case "tile": continue;

                    case "playerjoin":
                    case "playerquit":
                        Console.WriteLine($"[{DateTime.Now:dd HH:mm:ss}] {updateData.type} {updateData.playerName}");
                        break;

                    case "chat":
                        Console.WriteLine($"[{DateTime.Now:dd HH:mm:ss}] {updateData.playerName}({updateData.source}): {updateData.message}");
                        break;

                    default:
                        Console.WriteLine($"[{DateTime.Now:dd HH:mm:ss}] {updateData.type}");
                        break;
                    }
                }

                await Task.Delay(TimeSpan.FromMilliseconds(configuration.updaterate));
            }
        }
コード例 #30
0
        static void exceptions()
        {
            var engine = new Jint.Engine();

            try
            {
                engine.Execute("not_a_function()");
            }
            catch (Exception e)
            {
                Console.WriteLine($"caught expected exception: {e.Message}, {e.GetType()}");
            }
        }
コード例 #31
0
        void CreateLocation(Jint.Engine engine, ReactScript script)
        {
            var location = new DomProxies.Location(script.SourceLocation, Restart);

            engine.SetValue("location", location);

#if UNITY_EDITOR
            engine.SetValue("WebSocket", typeof(WebSocketProxy));
            engine.SetValue("oldXMLHttpRequest", typeof(XMLHttpRequest));
            engine.Execute(@"XMLHttpRequest = function() { return new oldXMLHttpRequest('" + location.origin + @"'); }");
#endif
            engine.SetValue("document", new DocumentProxy(unityContext, this, location.origin));
        }
コード例 #32
0
        static void listOperations()
        {
            var engine = new Jint.Engine();
            var list   = new List <SomeClass> {
                new SomeClass(20, "twenty"), new SomeClass(-20, "negative twenty"), new SomeClass(0, "zero")
            };

            IList <SomeClass> ilist = list;

            engine.SetValue("log", new Action <object>(Console.WriteLine));
            engine.SetValue("rng", new kaiGameUtil.RNG(2111));
            engine.SetValue("list", list);
            engine.SetValue("ilist", ilist);
            engine.Execute(@"
                log('testing random list operations:');
                log(typeof(list));
                log(list[0].publicNum);

                let count = list.Count;
                let newArray = [];
                for (let i = 0; i < count; ++i) {
                    if (list[i].publicNum >= 0) {
                        newArray.push(list[i]);
                    }
                }
                log('filtered: ' + newArray.length);
                function rngArray(a) { return a[ rng.Next(0, a.length - 1) ].publicNum; }

                for (let i = 0; i < 20; ++i) log('more rng: ' + rng.Next(0, 3));
            ");
            engine.SetValue("listArray", list.ToArray());
            engine.Execute(@"
                log('testing using list as array');
                log('listArray.length: ' + listArray.length);

                listArray = listArray.filter(function(i) { return i.publicNum >= 0 });
                log('filtered length: ' + listArray.length);
            ");
        }
コード例 #33
0
        /// <summary>
        /// Tries to return a webclient with the neccessary cookies installed to do requests for a cloudflare protected website.
        /// </summary>
        /// <param name="url">The page which is behind cloudflare's anti-dDoS protection</param>
        /// <returns>A WebClient object or null on failure</returns>
        public static WebClientEx CreateBypassedWebClient(string url)
        {
            var JSEngine = new Jint.Engine(); //Use this JavaScript engine to compute the result.

            //Download the original page
            var uri = new Uri(url);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
            //Try to make the usual request first. If this fails with a 503, the page is behind cloudflare.
            try
            {
                var res = req.GetResponse();
                string html = "";
                using (var reader = new StreamReader(res.GetResponseStream()))
                    html = reader.ReadToEnd();
                return new WebClientEx();
            }
            catch (WebException ex) //We usually get this because of a 503 service not available.
            {
                string html = "";
                using (var reader = new StreamReader(ex.Response.GetResponseStream()))
                    html = reader.ReadToEnd();
                //If we get on the landing page, Cloudflare gives us a User-ID token with the cookie. We need to save that and use it in the next request.
                var cookie_container = new CookieContainer();
                //using a custom function because ex.Response.Cookies returns an empty set ALTHOUGH cookies were sent back.
                var initial_cookies = GetAllCookiesFromHeader(ex.Response.Headers["Set-Cookie"], uri.Host);
                foreach (Cookie init_cookie in initial_cookies)
                    cookie_container.Add(init_cookie);

                /* solve the actual challenge with a bunch of RegEx's. Copy-Pasted from the python scrapper version.*/
                var challenge = Regex.Match(html, "name=\"jschl_vc\" value=\"(\\w+)\"").Groups[1].Value;
                var challenge_pass = Regex.Match(html, "name=\"pass\" value=\"(.+?)\"").Groups[1].Value;

                var builder = Regex.Match(html, @"setTimeout\(function\(\){\s+(var t,r,a,f.+?\r?\n[\s\S]+?a\.value =.+?)\r?\n").Groups[1].Value;
                builder = Regex.Replace(builder, @"a\.value =(.+?) \+ .+?;", "$1");
                builder = Regex.Replace(builder, @"\s{3,}[a-z](?: = |\.).+", "");

                //Format the javascript..
                builder = Regex.Replace(builder, @"[\n\\']", "");

                //Execute it.
                long solved = long.Parse(JSEngine.Execute(builder).GetCompletionValue().ToObject().ToString());
                solved += uri.Host.Length; //add the length of the domain to it.

                Console.WriteLine("***** SOLVED CHALLENGE ******: " + solved);
                Thread.Sleep(3000); //This sleeping IS requiered or cloudflare will not give you the token!!

                //Retreive the cookies. Prepare the URL for cookie exfiltration.
                string cookie_url = string.Format("{0}://{1}/cdn-cgi/l/chk_jschl", uri.Scheme, uri.Host);
                var uri_builder = new UriBuilder(cookie_url);
                var query = HttpUtility.ParseQueryString(uri_builder.Query);
                //Add our answers to the GET query
                query["jschl_vc"] = challenge;
                query["jschl_answer"] = solved.ToString();
                query["pass"] = challenge_pass;
                uri_builder.Query = query.ToString();

                //Create the actual request to get the security clearance cookie
                HttpWebRequest cookie_req = (HttpWebRequest)WebRequest.Create(uri_builder.Uri);
                cookie_req.AllowAutoRedirect = false;
                cookie_req.CookieContainer = cookie_container;
                cookie_req.Referer = url;
                cookie_req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
                //We assume that this request goes through well, so no try-catch
                var cookie_resp = (HttpWebResponse)cookie_req.GetResponse();
                //The response *should* contain the security clearance cookie!
                if (cookie_resp.Cookies.Count != 0) //first check if the HttpWebResponse has picked up the cookie.
                    foreach (Cookie cookie in cookie_resp.Cookies)
                        cookie_container.Add(cookie);
                else //otherwise, use the custom function again
                {
                    //the cookie we *hopefully* received here is the cloudflare security clearance token.
                    if (cookie_resp.Headers["Set-Cookie"] != null)
                    {
                        var cookies_parsed = GetAllCookiesFromHeader(cookie_resp.Headers["Set-Cookie"], uri.Host);
                        foreach (Cookie cookie in cookies_parsed)
                            cookie_container.Add(cookie);
                    }
                    else
                    {
                        //No security clearence? something went wrong.. return null.
                        //Console.WriteLine("MASSIVE ERROR: COULDN'T GET CLOUDFLARE CLEARANCE!");
                        return null;
                    }
                }
                //Create a custom webclient with the two cookies we already acquired.
                WebClientEx modedWebClient = new WebClientEx(cookie_container);
                modedWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0");
                modedWebClient.Headers.Add("Referer", url);
                return modedWebClient;
            }
        }
コード例 #34
0
 private static void ExecuteWithJint(Test test)
 {
     Execute("jint", test, () =>
     {
         var jintEngine = new Jint.Engine();
         jintEngine.Execute(test.Content);
     });
 }
コード例 #35
0
ファイル: QQEncryptor.cs プロジェクト: NitroXenon/iQQ.Net
 private static string RsaQQ(long uin, string password, string verifyCode)
 {
     var js = Resource.LoadLocalResource("encrypt.js", stream => stream.ToString(Encoding.UTF8));
     object[] args = { password, uin, verifyCode.ToUpper(), IsMd5(password).ToString().ToLower() };
     var code = string.Format("getEncryption('{0}','{1}','{2}',{3})", args);
     var engine = new Jint.Engine();
     engine.Execute(js);
     var s = engine.Execute(code).GetCompletionValue().AsString();
     return s;
 }