Пример #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
        protected override object InnerCallFunction(string functionName, params object[] args)
        {
            OriginalJsValue functionValue;

            try
            {
                functionValue = _jsEngine.GetValue(functionName);
            }
            catch (OriginalJsException e)
            {
                throw ConvertJavaScriptExceptionToJsRuntimeException(e);
            }

            var callable = functionValue.TryCast <IOriginalCallable>();

            if (callable == null)
            {
                throw new JsRuntimeException(
                          string.Format(CoreStrings.Runtime_FunctionNotExist, functionName));
            }

            int argumentCount = args.Length;
            var processedArgs = new OriginalJsValue[argumentCount];

            if (argumentCount > 0)
            {
                for (int argumentIndex = 0; argumentIndex < argumentCount; argumentIndex++)
                {
                    processedArgs[argumentIndex] = MapToJintType(args[argumentIndex]);
                }
            }

            OriginalJsValue resultValue;

            try
            {
                resultValue = callable.Call(functionValue, processedArgs);
            }
            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);
        }
Пример #3
0
        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);
            }
        }
Пример #4
0
        public static JsValue GetValueByPath(this JSEngine engine, params string[] path)
        {
            JsValue value = engine.GetValue(path[0]);

            for (int i = 1; i < path.Length; ++i)
            {
                value = engine.GetValue(value, path[i]);
            }
            return(value);
        }
Пример #5
0
        internal object GetValueFromJsEngine(GetValueQuery query, Jint.Engine engine)
        {
            if (engine == null)
            {
                return(null);
            }

            if (query.IsMember)
            {
                var jsvalue = engine.GetValue(query.MemberName);
                if (jsvalue != null && jsvalue.Type != Jint.Runtime.Types.Undefined)
                {
                    return(jsvalue.ToObject());
                }
            }
            else
            {
                var value = engine.GetValue(query.Key);

                if (value != null && value.Type != Jint.Runtime.Types.Undefined)
                {
                    string[] subs = query.SubProperty.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    object rightvalue = value;

                    foreach (var sub in subs)
                    {
                        rightvalue = getMember(rightvalue, sub);
                        if (rightvalue == null)
                        {
                            break;
                        }
                    }

                    if (rightvalue != null)
                    {
                        if (rightvalue is Jint.Native.JsValue)
                        {
                            var jsvalue = rightvalue as Jint.Native.JsValue;
                            if (jsvalue != null && jsvalue.Type != Jint.Runtime.Types.Undefined)
                            {
                                return(jsvalue.ToObject());
                            }
                        }
                        else
                        {
                            return(rightvalue);
                        }
                    }
                }
            }

            return(null);
        }
Пример #6
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));
        }
Пример #7
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);
        }
Пример #8
0
        public void EqualsDictionaryHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(CollectionTesting);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List <string>()
                {
                    "Dto"
                },
                CamelCase                    = true,
                IncludeMergeFunction         = true,
                OutputNamespace              = "models",
                RespectDataMemberAttribute   = true,
                RespectDefaultValueAttribute = true,
                IncludeEqualsFunction        = true
            });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));


            var js = new Jint.Parser.JavaScriptParser();



            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }

            var strToExecute = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                               $"var p2 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                               $"var result = p1.$equals(p2);";

            var jsEngine = new Jint.Engine().Execute(strToExecute);
            var res      = (bool)jsEngine.GetValue("result").ToObject();

            Assert.IsTrue(res);

            var strToExecuteNotEqual = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                                       $"var p2 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test2' }} }});\r\n" +
                                       $"var result = p1.$equals(p2);";

            var jsEngineNotEqual = new Jint.Engine().Execute(strToExecuteNotEqual);
            var resNotEqual      = (bool)jsEngineNotEqual.GetValue("result").ToObject();

            Assert.IsFalse(resNotEqual);
        }
Пример #9
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.ExecuteWithErrorHandle(code.Config, new Jint.Parser.ParserOptions()
                {
                    Tolerant = true
                });
            }
            catch (System.Exception ex)
            {
                Kooboo.Data.Log.Instance.Exception.WriteException(ex);
            }

            if (kcontext.ReturnValues.Count() > 0)
            {
                return(kcontext.ReturnValues.Last());
            }
            else
            {
                var obj = EngineConfigReturnObject(engine);
                return(obj);
            }
        }
Пример #10
0
        public static HttpResponseMessage GetRequestedPage(HttpClient client, IShop shop, string url, CancellationToken token)
        {
            var    initialUrl  = new Uri(url);
            var    host        = new Uri(shop.WebsiteBaseUrl);
            string initialPage = null;

            var message1 = new HttpRequestMessage()
            {
                Method     = HttpMethod.Get,
                RequestUri = initialUrl,
            };

            message1.Headers.AddHeaders(DefaultHeaders);

            using (message1)
            {
                var task = client.SendAsync(message1);

                using (var result = task.Result)
                {
                    string pageSource = result.Content.ReadAsStringAsync().Result;
                    if (!pageSource.Contains("s,t,o,p,b,r,e,a,k,i,n,g,f"))
                    {
                        result.EnsureSuccessStatusCode();
                        return(result);
                    }

                    initialPage = pageSource;
                }
            }

            for (int i = 0; i < 3; i++)
            {
                #region AdditionalReq
                //var message2 = new HttpRequestMessage()
                //{
                //    Method = HttpMethod.Get,
                //    RequestUri = new Uri(host, "/favicon.ico")
                //};

                //message2.Headers.AddHeaders(DefaultHeaders);

                //using (message2)
                //{
                //    message2.Headers.Referrer = initialUrl;
                //    message2.Headers.Remove("Accept");
                //    message2.Headers.Add("Accept", "*/*");
                //    using (var cc = client.SendAsync(message2, token).Result)
                //    {
                //        cc.EnsureSuccessStatusCode();
                //    }
                //}
                #endregion


                var engine = new Jint.Engine();
                engine.SetValue("interop", "15");

                var pass   = Regex.Match(initialPage, "name=\"pass\" value=\"(.*?)\"/>").Groups[1].Value;
                var answer = Regex.Match(initialPage, "name=\"jschl_vc\" value=\"(.*?)\"/>").Groups[1].Value;

                var match = Regex.Match(initialPage, @"setTimeout\(function\(\)({.+}), (\d+)\)",
                                        RegexOptions.Singleline | RegexOptions.IgnoreCase);
                var script  = match.Groups[1].Value;
                int timeout = int.Parse(match.Groups[2].Value);
                script = script.Replace("a = document.getElementById('jschl-answer');", string.Empty);
                script = script.Replace("f.action += location.hash;", string.Empty);
                script = script.Replace("f.submit();", string.Empty);
                script = script.Replace("f = document.getElementById('challenge-form');", string.Empty);
                script = script.Replace("a.value", "interop");
                script = script.Replace("t = document.createElement('div');", string.Empty);
                script = script.Replace("t.innerHTML=\"<a href='/'>x</a>\";", string.Empty);
                script = script.Replace("t = t.firstChild.href", $"t='{host.AbsoluteUri}';");



                engine.Execute(script);
                engine.Execute("interop=interop.toString();");
                var calc = engine.GetValue("interop").AsString();

                Task.Delay(timeout, token).Wait(token);
                var uri      = new Uri(host, $"/cdn-cgi/l/chk_jschl?jschl_vc={answer}&pass={pass}&jschl_answer={calc}");
                var message3 = new HttpRequestMessage()
                {
                    Method     = HttpMethod.Get,
                    RequestUri = uri,
                    Headers    = { Referrer = initialUrl }
                };

                message3.Headers.AddHeaders(FireFoxHeaders);

                using (message3)
                {
                    var finalResult = client.SendAsync(message3, token).Result;


                    string pageSource = finalResult.Content.ReadAsStringAsync().Result;
                    if (!pageSource.Contains("s,t,o,p,b,r,e,a,k,i,n,g,f"))
                    {
                        finalResult.EnsureSuccessStatusCode();
                        return(finalResult);
                    }

                    initialPage = pageSource;
                }
            }

            throw new WebException("Couldn't bypass cloudfare");
        }
Пример #11
0
        public void EqualsHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(AddressInformation);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List<string>() { "Dto" },
                CamelCase = true,
                IncludeMergeFunction = true,
                OutputNamespace = "models",
                RespectDataMemberAttribute = true,
                RespectDefaultValueAttribute = true,
                IncludeEqualsFunction = true
            });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            var js = new Jint.Parser.JavaScriptParser();

            try
            {
                js.Parse(outputJs);

            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }

            var strToExecute = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.AddressInformation({{ name: 'Test' }});\r\n" +
                               $"var p2 = new models.AddressInformation({{ name: 'Test' }});\r\n" +
                               $"var result = p1.$equals(p2);";

            var jsEngine = new Jint.Engine().Execute(strToExecute);
            var res = (bool)jsEngine.GetValue("result").ToObject();

            Assert.IsTrue(res);

            var strToExecuteNotEqual = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.AddressInformation({{ name: 'Test' }});\r\n" +
                               $"var p2 = new models.AddressInformation({{ name: 'Test2' }});\r\n" +
                               $"var result = p1.$equals(p2);";

            var jsEngineNotEqual = new Jint.Engine().Execute(strToExecuteNotEqual);
            var resNotEqual = (bool)jsEngineNotEqual.GetValue("result").ToObject();

            Assert.IsFalse(resNotEqual);
        }