コード例 #1
0
        public void DynamicHostItem_CrossEngine()
        {
            const string format = "{0} foo {1} bar {2} baz {3} qux {4} quux {5}";
            var          args   = new object[] { 1, 2, 3, 4, 5, 6 };

            engine.Script.mscorlib = new HostTypeCollection("mscorlib");

            using (var outerEngine = new JScriptEngine())
            {
                outerEngine.Script.inner  = engine;
                outerEngine.Script.format = format;
                outerEngine.Script.args   = args;
                Assert.AreEqual(string.Format(format, args), outerEngine.Evaluate("inner.Script.mscorlib.System.String.Format(format, args)"));
                Assert.AreEqual(string.Format(format, args), outerEngine.Evaluate("inner.Script.mscorlib['System'].String['Format'](format, args)"));
            }
        }
コード例 #2
0
        public void JScriptCoreEngine_AddCOMType_XMLHTTP()
        {
            var    status = 0;
            string data   = null;

            var thread = new Thread(() =>
            {
                using (var testEngine = new JScriptEngine(Windows.WindowsScriptEngineFlags.EnableDebugging | Windows.WindowsScriptEngineFlags.EnableStandardsMode, NullSyncInvoker.Instance))
                {
                    testEngine.Script.onComplete = new Action <int, string>((xhrStatus, xhrData) =>
                    {
                        status = xhrStatus;
                        data   = xhrData;
                        Dispatcher.ExitAllFrames();
                    });

                    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
                    {
                        // ReSharper disable AccessToDisposedClosure

                        testEngine.AddCOMType("XMLHttpRequest", "MSXML2.XMLHTTP");
                        testEngine.Execute(@"
                            xhr = new XMLHttpRequest();
                            xhr.open('POST', 'http://httpbin.org/post', true);
                            xhr.onreadystatechange = function () {
                                if (xhr.readyState == 4) {
                                    onComplete(xhr.status, JSON.parse(xhr.responseText).data);
                                }
                            };
                            xhr.send('Hello, world!');
                        ");

                        // ReSharper restore AccessToDisposedClosure
                    }));

                    Dispatcher.Run();
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            Assert.AreEqual(200, status);
            Assert.AreEqual("Hello, world!", data);
        }
コード例 #3
0
        private JScriptEngine InstantiateScripts(string script, string resourceName, string[] refs)
        {
            var scriptEngine = new JScriptEngine();
            var collect      = new HostTypeCollection(refs);

            scriptEngine.AddHostObject("clr", collect);
            scriptEngine.AddHostObject("API", new API()
            {
                ResourceParent = this
            });
            scriptEngine.AddHostObject("host", new HostFunctions());
            scriptEngine.AddHostType("Dictionary", typeof(Dictionary <,>));
            scriptEngine.AddHostType("xmlParser", typeof(RetardedXMLParser));
            scriptEngine.AddHostType("Enumerable", typeof(Enumerable));
            scriptEngine.AddHostType("NetHandle", typeof(NetHandle));
            scriptEngine.AddHostType("String", typeof(string));
            scriptEngine.AddHostType("List", typeof(List <>));
            scriptEngine.AddHostType("Client", typeof(Client));
            scriptEngine.AddHostType("Vector3", typeof(Vector3));
            scriptEngine.AddHostType("Quaternion", typeof(Vector3));
            scriptEngine.AddHostType("Client", typeof(Client));
            scriptEngine.AddHostType("LocalPlayerArgument", typeof(LocalPlayerArgument));
            scriptEngine.AddHostType("LocalGamePlayerArgument", typeof(LocalGamePlayerArgument));
            scriptEngine.AddHostType("EntityArgument", typeof(EntityArgument));
            scriptEngine.AddHostType("EntityPointerArgument", typeof(EntityPointerArgument));
            scriptEngine.AddHostType("console", typeof(Console));
            scriptEngine.AddHostType("VehicleHash", typeof(VehicleHash));
            scriptEngine.AddHostType("Int32", typeof(int));
            scriptEngine.AddHostType("EntityArgument", typeof(EntityArgument));
            scriptEngine.AddHostType("EntityPtrArgument", typeof(EntityPointerArgument));

            try
            {
                scriptEngine.Execute(script);
            }
            catch (ScriptEngineException ex)
            {
                Program.Output("EXCEPTION WHEN COMPILING JAVASCRIPT " + Filename);
                Program.Output(ex.Message);
                Program.Output(ex.StackTrace);
                HasTerminated = true;
                throw;
            }

            return(scriptEngine);
        }
コード例 #4
0
        internal void RunScript(string code)
        {
            var t = new Task <System.String>(() =>
            {
                using (var engine = new JScriptEngine())
                {
                    engine.AddHostObject("driver", SwdBrowser.GetDriver());

                    ImportTypes(engine);

                    var uiPageObject = Presenters.PageObjectDefinitionPresenter.GetWebElementDefinitionFromTree();


                    foreach (var element in uiPageObject.Items)
                    {
                        IWebElement proxyElement = SwdBrowser.CreateWebElementProxy(element);
                        string name = element.Name;
                        engine.AddHostObject(name, proxyElement);
                    }

                    var result = engine.Evaluate(code) ?? "(none)";
                    return(result.ToString());
                }
            });


            string logLine = "done";

            try
            {
                t.Start();
                t.Wait();
                logLine = t.Result;
            }
            catch (Exception ex)
            {
                MyLog.Exception(ex);
                logLine = "ERROR: " + ex.Message;
                // TODO: FIX message --> Exception has been thrown by the target of invocation
                // \TODO: FIX message --> Exception has been thrown by the target of invocation
            }
            finally
            {
                view.AppendConsole(logLine + "\r\n");
            }
        }
コード例 #5
0
        public void BugFix_NonEnumerablePropertyAccess_JScript()
        {
            engine.Dispose();
            engine = new JScriptEngine();

            engine.Script.dump = new Action <dynamic, string>((obj, value) =>
            {
                Assert.AreEqual(value, obj.message);
            });

            engine.Execute(@"
                message = 'hello';
                dump({ message: message }, message);
                message = 'world';
                dump(new Error(message), message);
            ");
        }
コード例 #6
0
        public void BugFix_JScript_TargetInvocationException()
        {
            engine.Dispose();
            engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging);

            engine.Script.foo = new Action(() => throw new Exception("bar"));
            engine.Execute("function test() { foo(); }");

            try
            {
                engine.Invoke("test");
            }
            catch (ScriptEngineException exception)
            {
                Assert.IsTrue(exception.ErrorDetails.Contains("bar\n    at test (Script:0:18) -> foo"));
            }
        }
コード例 #7
0
        public static void StartScript(string script, List <int> identEnts)
        {
            var scriptEngine = new JScriptEngine();
            var collection   = new HostTypeCollection(Assembly.LoadFrom("scripthookvdotnet.dll"),
                                                      Assembly.LoadFrom("scripts\\NativeUI.dll"));

            scriptEngine.AddHostObject("API", collection);
            scriptEngine.AddHostObject("host", new HostFunctions());
            scriptEngine.AddHostObject("script", new ScriptContext());
            scriptEngine.AddHostType("Enumerable", typeof(Enumerable));
            scriptEngine.AddHostType("List", typeof(IList));
            scriptEngine.AddHostType("KeyEventArgs", typeof(KeyEventArgs));
            scriptEngine.AddHostType("Keys", typeof(Keys));

            foreach (var obj in identEnts)
            {
                var name = PropStreamer.Identifications[obj];
                if (MapEditor.IsPed(new Prop(obj)))
                {
                    scriptEngine.AddHostObject(name, new Ped(obj));
                }
                else if (MapEditor.IsVehicle(new Prop(obj)))
                {
                    scriptEngine.AddHostObject(name, new Vehicle(obj));
                }
                else if (MapEditor.IsProp(new Prop(obj)))
                {
                    scriptEngine.AddHostObject(name, new Prop(obj));
                }
            }

            try
            {
                scriptEngine.Execute(script);
            }
            catch (ScriptEngineException ex)
            {
                LogException(ex);
            }
            finally
            {
                lock (ScriptEngines)
                    ScriptEngines.Add(scriptEngine);
            }
        }
コード例 #8
0
        private static void ExecuteScript(UserScript script, ScriptHost scriptHost, Logger logger, object[] args)
        {
            try
            {
                //var engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging);
                var engine = new JScriptEngine();
                engine.AddHostObject("host", scriptHost);

                string initArgsScript = string.Format("var arguments = {0};", args.ToJson());
                engine.Execute(initArgsScript);
                engine.Execute(script.Body);
            }
            catch (Exception ex)
            {
                var messge = string.Format("Error in user script {0}", script.Name);
                logger.ErrorException(messge, ex);
            }
        }
コード例 #9
0
        public void BugFix_JScriptStandardsMode_MemberEnumeration()
        {
            engine.Dispose();
            engine = new JScriptEngine(WindowsScriptEngineFlags.EnableStandardsMode);

            engine.Script.x = new { foo = 123, bar = "blah" };
            var result = (string)engine.Evaluate(@"
                var result = '';
                for (var i in x) {
                    if ((i == 'foo') || (i == 'bar')) {
                        result += x[i];
                    }
                }
                result
            ");

            Assert.AreEqual(7, result.Length);
            Assert.IsTrue(result.IndexOf("123", StringComparison.Ordinal) >= 0);
            Assert.IsTrue(result.IndexOf("blah", StringComparison.Ordinal) >= 0);
        }
コード例 #10
0
        private static IList <PriceInfo> Filter(string contextOld, IList <PriceInfo> priceList)
        {
            JScriptEngine engine = null;

            if (IsDebugg)
            {
                engine = new JScriptEngine("Filter", WindowsScriptEngineFlags.EnableDebugging);
            }
            else
            {
                engine = new JScriptEngine("Filter");
            }
            using (engine)
            {
                if (string.IsNullOrEmpty(contextOld))
                {
                    return(priceList);
                }
                engine.Execute("var context=" + contextOld);

                engine.Execute(@"var data=context.data;  
                                var date;
                                if(data&&data.length>0){
	                                date=data[data.length-1][0];
                                }else{
	                                date='';
                                }");
                var date = engine.Script.date;

                var dateTime = DateTime.ParseExact(date, "yyyyMMdd", null);
                if (string.IsNullOrEmpty(date))
                {
                    return(priceList);
                }
                else
                {
                    return(priceList.Where(p => p.date > dateTime).ToList());
                }
            }
        }
コード例 #11
0
ファイル: ModuleLoader.cs プロジェクト: moayyaed/POS-1
        public static void Load(this JScriptEngine se, Type t)
        {
            var ca = t.GetCustomAttribute <ScriptModuleAttribute>();

            if (ca != null)
            {
                object tmp;
                try
                {
                    tmp = Activator.CreateInstance(t);
                }
                catch { tmp = 12; }

                if (ca.AsType)
                {
                    se.AddHostType(ca.Name != null ? ca.Name : t.Name, t);
                }

                foreach (var me in t.GetMethods())
                {
                    if (me.IsStatic)
                    {
                        var meca = me.GetCustomAttribute <ScriptFunctionAttribute>();
                        if (meca != null)
                        {
                            se.AddHostObject(meca.Name != null ? meca.Name : me.Name, new StaticMethodFunc(args => me.Invoke(null, args)));
                        }
                    }
                }

                foreach (var me in t.GetProperties())
                {
                    var meca = me.GetCustomAttribute <ScriptMemberAttribute>();
                    if (meca != null)
                    {
                        se.AddHostObject(meca.Name != null ? meca.Name : me.Name, me.GetValue(tmp, null));
                    }
                }
            }
        }
コード例 #12
0
        public void VBScriptEngine_ErrorHandling_NestedHostException()
        {
            var innerEngine = new JScriptEngine("inner", WindowsScriptEngineFlags.EnableDebugging);

            innerEngine.AddHostObject("host", new HostFunctions());
            engine.AddHostObject("engine", innerEngine);

            TestUtil.AssertException <ScriptEngineException>(() =>
            {
                try
                {
                    engine.Execute("engine.Evaluate(\"host.newObj(0)\")");
                }
                catch (ScriptEngineException exception)
                {
                    TestUtil.AssertValidException(engine, exception);
                    Assert.IsNotNull(exception.InnerException);

                    var hostException = exception.InnerException;
                    Assert.IsInstanceOfType(hostException, typeof(TargetInvocationException));
                    TestUtil.AssertValidException(hostException);
                    Assert.IsNotNull(hostException.InnerException);

                    var nestedException = hostException.InnerException as ScriptEngineException;
                    Assert.IsNotNull(nestedException);
                    TestUtil.AssertValidException(innerEngine, nestedException);
                    Assert.IsNotNull(nestedException.InnerException);

                    var nestedHostException = nestedException.InnerException;
                    Assert.IsInstanceOfType(nestedHostException, typeof(RuntimeBinderException));
                    TestUtil.AssertValidException(nestedHostException);
                    Assert.IsNull(nestedHostException.InnerException);

                    Assert.AreEqual(nestedHostException.Message, nestedException.Message);
                    Assert.AreEqual(hostException.Message, exception.Message);
                    throw;
                }
            });
        }
コード例 #13
0
        public DevTools(JScriptEngine engine, Dictionary<string, object> objects, string source = "")
        {
            InitializeComponent();

            this.engine = engine;
            this.objects = objects;

            editor = new ICSharpCode.AvalonEdit.TextEditor();
            editor.FontFamily = new System.Windows.Media.FontFamily("Consolas");
            editor.FontSize = 14;
            editor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinitionByExtension(".js");
            editor.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.DefaultIndentationStrategy();
            editor.ShowLineNumbers = true;

            editor.Text = source;

            foldingStrategy = new BraceFoldingStrategy();
            foldingManager = FoldingManager.Install(editor.TextArea);
            foldingStrategy.UpdateFoldings(foldingManager, editor.Document);

            editor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
            editor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
            editor.TextChanged += Editor_TextChanged;

            DispatcherTimer foldingUpdateTimer = new DispatcherTimer();
            foldingUpdateTimer.Interval = TimeSpan.FromTicks(20);
            foldingUpdateTimer.Tick += foldingUpdateTimer_Tick;
            foldingUpdateTimer.Start();

            var img = new Image();
            img.Source = Utils.ImageToBitmapsource(Properties.Resources.start);
            btnStart.Content = img;
            btnStart.Click += (s, e) => engine.Execute(editor.Text);

            editor.ExtendWithContextMenu();

            view.Child = editor;
        }
コード例 #14
0
        public void BugFix_PropertyBag_NativeEnumerator_JScript()
        {
            engine.Dispose();
            engine = new JScriptEngine();

            var x = new PropertyBag {
                ["foo"] = 123, ["bar"] = "blah"
            };

            engine.Script.x = x;

            var result = (string)engine.Evaluate(@"
                var result = '';
                for (var e = new Enumerator(x); !e.atEnd(); e.moveNext()) {
                    result += e.item().Value;
                }
                result
            ");

            Assert.AreEqual(7, result.Length);
            Assert.IsTrue(result.IndexOf("123", StringComparison.Ordinal) >= 0);
            Assert.IsTrue(result.IndexOf("blah", StringComparison.Ordinal) >= 0);
        }
コード例 #15
0
        public void BugFix_JScriptStandardsMode_MemberEnumeration_PropertyBag()
        {
            engine.Dispose();
            engine = new JScriptEngine(WindowsScriptEngineFlags.EnableStandardsMode);

            var x = new PropertyBag {
                ["foo"] = 123, ["bar"] = "blah"
            };

            engine.Script.x = x;

            var result = (string)engine.Evaluate(@"
                var result = '';
                for (var i in x) {
                    result += x[i];
                }
                result
            ");

            Assert.AreEqual(7, result.Length);
            Assert.IsTrue(result.IndexOf("123", StringComparison.Ordinal) >= 0);
            Assert.IsTrue(result.IndexOf("blah", StringComparison.Ordinal) >= 0);
        }
コード例 #16
0
ファイル: CommandLineEngine.cs プロジェクト: boro2g/sinj
        private int Execute()
        {
            int returnValue = 0;

            using (ScriptEngine scriptEngine = new JScriptEngine(_scriptFlags))
            {
                scriptEngine.AddHostObject("$cmd", new ProgramContext(_debug));

                foreach (string path in _paths)
                {
                    try
                    {
                        Console.Write("scriptEngine.Execute: " + path + "\r\n");
                        string contents = File.ReadAllText(path);
                        scriptEngine.Execute(contents);
                    }
                    catch (ScriptEngineException e)
                    {
                        Console.Write("CommandLineEngine error with script file' " + path + "'. ");
                        Console.Write(e.ErrorDetails + "\r\n\r\n" + e.InnerException + "\r\n\r\n");

                        returnValue = 2;
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.Write("CommandLineEngine error with script file' " + path + "'. ");
                        Console.Write("Details: " + GetaAllMessages(ex));

                        returnValue = 3;
                        break;
                    }
                }
            }

            return(returnValue);
        }
コード例 #17
0
        internal AutoWebProxyState Compile(Uri engineScriptLocation, string scriptBody, byte[] buffer)
        {
            if (closed != 0)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (jscriptObject != null)
            {
                jscript.Close();
            }

            scriptText = null;
            scriptBytes = null;
            jscriptObject = new JScriptEngine();
            jscript = (IActiveScript) jscriptObject;
            host = new ScriptHost();
            
            GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Binding to ScriptHost#" + ValidationHelper.HashString(this));
            
            jscriptParser = new ActiveScriptParseWrapper(jscriptObject);
            jscriptParser.InitNew();

            jscript.SetScriptSite(host);
            jscript.SetScriptState(ScriptState.Initialized);

            //
            // Inform the script engine that this host implements the IInternetHostSecurityManager interface, which
            // is used to prevent the script code from using any ActiveX objects.
            //
            IObjectSafety objSafety = jscript as IObjectSafety;
            if (objSafety != null)
            {
                Guid guid = Guid.Empty;
                GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Setting up IInternetHostSecurityManager");
                objSafety.SetInterfaceSafetyOptions(ref guid, ComConstants.INTERFACE_USES_SECURITY_MANAGER, ComConstants.INTERFACE_USES_SECURITY_MANAGER);
                objSafety = null;
            }

            EXCEPINFO exceptionInfo = new EXCEPINFO();
            object result = null;
            try
            {
                jscriptParser.ParseScriptText(scriptBody, null, null, null, IntPtr.Zero, 0, ScriptText.IsPersistent | ScriptText.IsVisible, out result, out exceptionInfo);
                GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() ParseScriptText() success:" + ValidationHelper.ToString(exceptionInfo.bstrDescription) + " result:" + ValidationHelper.ToString(result));
            }
            catch (Exception exception)
            {
                if (NclUtilities.IsFatal(exception)) throw;
                if (exception is TargetInvocationException)
                {
                    exception = exception.InnerException;
                }
                COMException comException = exception as COMException;
                if (comException == null || comException.ErrorCode != (int) HRESULT.SCRIPT_E_REPORTED)
                {
                    throw;
                }
                GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Script load error:[" + host.ExceptionMessage == null ? "" : host.ExceptionMessage + "]");
                throw new COMException(SR.GetString(SR.net_jscript_load, host.ExceptionMessage), comException.ErrorCode);
            }
            catch {
                GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Script load error:[Non-CLS Compliant Exception]");
                throw;
            }

            jscript.AddNamedItem(c_ScriptHelperName, ScriptItem.GlobalMembers | ScriptItem.IsPersistent | ScriptItem.IsVisible);

            // This part can run global code - time it out if necessary.
            jscript.GetCurrentScriptThreadID(out interruptThreadId);
            TimerThread.Timer timer = s_TimerQueue.CreateTimer(s_InterruptCallback, this);
            activeTimer = timer;
            try
            {
                jscript.SetScriptState(ScriptState.Started);
                jscript.SetScriptState(ScriptState.Connected);
            }
            finally
            {
                activeTimer = null;
                timer.Cancel();
            }

            jscript.GetScriptDispatch(null, out script);
            GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Got IDispatch:" + ValidationHelper.ToString(dispatch));

            scriptText = scriptBody;
            scriptBytes = buffer;

            return AutoWebProxyState.CompilationSuccess;
        }
コード例 #18
0
        internal AutoWebProxyState Compile(Uri engineScriptLocation, string scriptBody, byte[] buffer)
        {
            if (closed != 0)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (jscriptObject != null)
            {
                jscript.Close();
            }

            scriptText    = null;
            scriptBytes   = null;
            jscriptObject = new JScriptEngine();
            jscript       = (IActiveScript)jscriptObject;
            host          = new ScriptHost();

            GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Binding to ScriptHost#" + ValidationHelper.HashString(this));

            jscriptParser = new ActiveScriptParseWrapper(jscriptObject);
            jscriptParser.InitNew();

            jscript.SetScriptSite(host);
            jscript.SetScriptState(ScriptState.Initialized);

            //
            // Inform the script engine that this host implements the IInternetHostSecurityManager interface, which
            // is used to prevent the script code from using any ActiveX objects.
            //
            IObjectSafety objSafety = jscript as IObjectSafety;

            if (objSafety != null)
            {
                Guid guid = Guid.Empty;
                GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Setting up IInternetHostSecurityManager");
                objSafety.SetInterfaceSafetyOptions(ref guid, ComConstants.INTERFACE_USES_SECURITY_MANAGER, ComConstants.INTERFACE_USES_SECURITY_MANAGER);
                objSafety = null;
            }

            EXCEPINFO exceptionInfo = new EXCEPINFO();
            object    result        = null;

            try
            {
                jscriptParser.ParseScriptText(scriptBody, null, null, null, IntPtr.Zero, 0, ScriptText.IsPersistent | ScriptText.IsVisible, out result, out exceptionInfo);
                GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() ParseScriptText() success:" + ValidationHelper.ToString(exceptionInfo.bstrDescription) + " result:" + ValidationHelper.ToString(result));
            }
            catch (Exception exception)
            {
                if (NclUtilities.IsFatal(exception))
                {
                    throw;
                }
                if (exception is TargetInvocationException)
                {
                    exception = exception.InnerException;
                }
                COMException comException = exception as COMException;
                if (comException == null || comException.ErrorCode != (int)HRESULT.SCRIPT_E_REPORTED)
                {
                    throw;
                }
                GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Script load error:[" + host.ExceptionMessage == null ? "" : host.ExceptionMessage + "]");
                throw new COMException(SR.GetString(SR.net_jscript_load, host.ExceptionMessage), comException.ErrorCode);
            }
            catch {
                GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Script load error:[Non-CLS Compliant Exception]");
                throw;
            }

            jscript.AddNamedItem(c_ScriptHelperName, ScriptItem.GlobalMembers | ScriptItem.IsPersistent | ScriptItem.IsVisible);

            // This part can run global code - time it out if necessary.
            jscript.GetCurrentScriptThreadID(out interruptThreadId);
            TimerThread.Timer timer = s_TimerQueue.CreateTimer(s_InterruptCallback, this);
            activeTimer = timer;
            try
            {
                jscript.SetScriptState(ScriptState.Started);
                jscript.SetScriptState(ScriptState.Connected);
            }
            finally
            {
                activeTimer = null;
                timer.Cancel();
            }

            jscript.GetScriptDispatch(null, out script);
            GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Got IDispatch:" + ValidationHelper.ToString(dispatch));

            scriptText  = scriptBody;
            scriptBytes = buffer;

            return(AutoWebProxyState.CompilationSuccess);
        }
コード例 #19
0
        public void PropertyBag_MultiEngine_Parallel()
        {
            // This is a torture test for ConcurrentWeakSet and general engine teardown/cleanup.
            // It has exposed some very tricky engine bugs.

            var bag = new PropertyBag();

            engine.AddHostObject("bag", bag);

            const int threadCount = 256;
            var       engineCount = 0;

            // 32-bit V8 starts failing requests to create new contexts rather quickly. This is
            // because each V8 isolate requires (among other things) a 32MB address space
            // reservation. 64-bit V8 reserves much larger blocks but benefits from the enormous
            // available address space.

            var maxV8Count      = Environment.Is64BitProcess ? 128 : 16;
            var maxJScriptCount = (threadCount - maxV8Count) / 2;

            var startEvent      = new ManualResetEventSlim(false);
            var checkpointEvent = new ManualResetEventSlim(false);
            var continueEvent   = new ManualResetEventSlim(false);
            var stopEvent       = new ManualResetEventSlim(false);

            ParameterizedThreadStart body = arg =>
            {
                // ReSharper disable AccessToDisposedClosure

                var index = (int)arg;
                startEvent.Wait();

                ScriptEngine scriptEngine;
                if (index < maxV8Count)
                {
                    scriptEngine = new V8ScriptEngine();
                }
                else if (index < (maxV8Count + maxJScriptCount))
                {
                    scriptEngine = new JScriptEngine();
                }
                else
                {
                    scriptEngine = new VBScriptEngine();
                }

                scriptEngine.AddHostObject("bag", bag);
                if (Interlocked.Increment(ref engineCount) == threadCount)
                {
                    checkpointEvent.Set();
                }

                continueEvent.Wait();

                scriptEngine.Dispose();
                if (Interlocked.Decrement(ref engineCount) == 0)
                {
                    stopEvent.Set();
                }

                // ReSharper restore AccessToDisposedClosure
            };

            var threads = Enumerable.Range(0, threadCount).Select(index => new Thread(body)).ToArray();

            threads.ForEach((thread, index) => thread.Start(index));

            startEvent.Set();
            checkpointEvent.Wait();
            Assert.AreEqual(threadCount + 1, bag.EngineCount);

            continueEvent.Set();
            stopEvent.Wait();
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            Assert.AreEqual(1, bag.EngineCount);

            Array.ForEach(threads, thread => thread.Join());
            startEvent.Dispose();
            checkpointEvent.Dispose();
            continueEvent.Dispose();
            stopEvent.Dispose();
        }
コード例 #20
0
 public void JScriptEngine_StandardsMode()
 {
     engine.Dispose();
     engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableStandardsMode);
     Assert.AreEqual("{\"foo\":123,\"bar\":456.789}", engine.Evaluate("JSON.stringify({ foo: 123, bar: 456.789 })"));
 }
コード例 #21
0
ファイル: Runner.cs プロジェクト: axtens/Axtension
        public Runner()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

            JSE = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging);
            JSE.AddHostObject("CSHost", new ExtendedHostFunctions());

            JSE.AddHostType("CSMarkup", typeof(Markup));
            JSE.AddHostType("CSMarkupFormatters", typeof(MarkupFormatters));

            /// System
            JSE.AddHostType("CSString", typeof(String));
            JSE.AddHostType("CSEnvironment", typeof(Environment));
            JSE.AddHostType("CSConsole", typeof(Console));
            JSE.AddHostType("CSFile", typeof(File));
            JSE.AddHostType("CSFileInfo", typeof(FileInfo));
            JSE.AddHostType("CSDirectory", typeof(Directory));
            JSE.AddHostType("CSPath", typeof(Path));
            JSE.AddHostType("CSSearchOption", typeof(SearchOption));
            JSE.AddHostType("CSEncoding", typeof(Encoding));
            JSE.AddHostType("CSMemoryStream", typeof(MemoryStream));
            JSE.AddHostType("CSTimeSpan", typeof(TimeSpan));
            JSE.AddHostType("CSThread", typeof(Thread));
            JSE.AddHostType("CSProcess", typeof(Process));
            JSE.AddHostType("CSProcessStartInfo", typeof(ProcessStartInfo));
            JSE.AddHostType("CSSearchOption", typeof(SearchOption));
            JSE.AddHostType("CSUri", typeof(Uri));
            JSE.AddHostType("CSWebClient", typeof(WebClient));
            JSE.AddHostType("CSStreamReader", typeof(StreamReader));
            JSE.AddHostType("CSStream", typeof(Stream));
            JSE.AddHostType("CSBitmap", typeof(Bitmap));
            JSE.AddHostType("CSImageFormat", typeof(ImageFormat));
            JSE.AddHostType("CSDebugger", typeof(Debugger));

            /// Mail
            JSE.AddHostType("CSMailMessage", typeof(MailMessage));
            JSE.AddHostType("CSMailAddress", typeof(MailAddress));
            JSE.AddHostType("CSAttachment", typeof(Attachment));
            JSE.AddHostType("CSNetworkCredential", typeof(NetworkCredential));
            JSE.AddHostType("CSSmtpClient", typeof(SmtpClient));

            /// Firefox
            JSE.AddHostType("CSFirefoxBinary", typeof(FirefoxBinary));
            JSE.AddHostType("CSFirefoxDriver", typeof(FirefoxDriver));
            JSE.AddHostType("CSFirefoxProfileManager", typeof(FirefoxProfileManager));
            JSE.AddHostType("CSFirefoxProfile", typeof(FirefoxProfile));
            JSE.AddHostType("CSFirefoxDriverCommandExecutor", typeof(FirefoxDriverCommandExecutor));
            JSE.AddHostType("CSFirefoxOptions", typeof(FirefoxOptions));
            JSE.AddHostType("CSFirefoxDriverService", typeof(FirefoxDriverService));

            /// PhantomJS
            JSE.AddHostType("CSPhantomJSDriver", typeof(PhantomJSDriver));
            JSE.AddHostType("CSPhantomJSOptions", typeof(PhantomJSOptions));
            JSE.AddHostType("CSPhantomJSDriverService", typeof(PhantomJSDriverService));

            /// Selenium
            JSE.AddHostType("CSBy", typeof(By));
            JSE.AddHostType("CSJavascriptExecutor", typeof(IJavaScriptExecutor));
            JSE.AddHostType("CSActions", typeof(Actions));
            JSE.AddHostType("CSDriverService", typeof(OpenQA.Selenium.DriverService));
            JSE.AddHostType("CSRemoteWebDriver", typeof(RemoteWebDriver));
            JSE.AddHostType("CSDesiredCapabilities", typeof(DesiredCapabilities));
            JSE.AddHostType("CSPlatform", typeof(Platform));
            JSE.AddHostType("CSPlatformType", typeof(PlatformType));
            JSE.AddHostType("CSProxy", typeof(Proxy));
            JSE.AddHostType("CSProxyKind", typeof(ProxyKind));
            JSE.AddHostType("CSIWebDriver", typeof(IWebDriver));
            JSE.AddHostType("CSITakesScreenshot", typeof(ITakesScreenshot));
            JSE.AddHostType("CSScreenshot", typeof(Screenshot));
            JSE.AddHostType("CSSelectElement", typeof(SelectElement));

            /// HTMLAgilityPack
            JSE.AddHostType("CSHtmlDocument", typeof(HtmlAgilityPack.HtmlDocument));
            JSE.AddHostType("CSHtmlNode", typeof(HtmlAgilityPack.HtmlNode));
            JSE.AddHostType("CSHtmlNodeCollection", typeof(HtmlAgilityPack.HtmlNodeCollection));
            JSE.AddHostType("CSHtmlAttribute", typeof(HtmlAgilityPack.HtmlAttribute));
            //JSE.AddHostType(typeof(HapCssExtensionMethods));

            /// Axtension
            JSE.AddHostType("T", typeof(Axtension.ApplicationLogging));
            JSE.AddHostType("CSConfig", typeof(Axtension.Config));
            JSE.AddHostType("CSREST", typeof(Axtension.REST));
            JSE.AddHostType("CSRESTful", typeof(Axtension.RESTful));
            JSE.AddHostType("CSFluentREST", typeof(Axtension.RESTful2));
            JSE.AddHostType("CSProcesses", typeof(Axtension.Processes));
            JSE.AddHostType("CSMail", typeof(Axtension.Mail));
            JSE.AddHostType("CSDatabase", typeof(Axtension.SQL));
            JSE.AddHostType("CSTelstraSMS", typeof(Axtension.TelstraSMS));
            JSE.AddHostType("CSXML", typeof(Axtension.XML));
            JSE.AddHostType("CSSQL", typeof(Axtension.SQL));
            JSE.AddHostType("CSGoogleOAuth2", typeof(Axtension.GoogleOAuth2));
            JSE.AddHostType("CSDebugPoints", typeof(Axtension.DebugPoints));

            //
            JSE.AddHostType("CSZipFile", typeof(ZipFile));
        }
コード例 #22
0
 public void BugFix_UInt32RoundTrip_JScript()
 {
     engine.Dispose();
     engine = new JScriptEngine();
     BugFix_UInt32RoundTrip();
 }
コード例 #23
0
ファイル: JavascriptHook.cs プロジェクト: Radviger/MultiV
 public ClientsideScriptWrapper(JScriptEngine en, string rs, string filename)
 {
     Engine         = en;
     ResourceParent = rs;
     Filename       = filename;
 }
コード例 #24
0
        public static int LoadAndExec(String code, StreamReader rdr)
        {
            var lines = code.Split('\n');

            switch (lines[0])
            {
            case "//CLEARSCRIPT":
                JScriptEngine jsEngine = new JScriptEngine();
                jsEngine.AddHostType("Console", typeof(Console));
                jsEngine.AddHostObject("sw", streamWriter);
                jsEngine.AddHostObject("rdr", rdr);
                jsEngine.AddHostObject("xHost", new ExtendedHostFunctions());
                jsEngine.AddHostType("DllImports", typeof(DllImports));
                jsEngine.AddHostType("Win32", typeof(SilverSmoke.Execution.Win32));
                jsEngine.AddHostType("Native", typeof(SilverSmoke.Execution.Native));
                var typeCollection = new HostTypeCollection("mscorlib", "System", "System.Core");
                jsEngine.AddHostObject("clr", typeCollection);
                try
                {
                    jsEngine.Execute(code);
                }
                catch (Exception ex)
                {
                    streamWriter.WriteLine(ex.Message);
                }
                break;

            case "//C#":
                TextWriter oldOut = Console.Out;                  //save this
                Console.SetOut(streamWriter);
                string[] dlls = lines[1].Substring(2).Split(','); //2nd line: list of DLLs, seperated by commas
                string   nm   = lines[2].Substring(2);            //3rd line: namespace
                string   cls  = lines[3].Substring(2);            //4th line: class name
                string   mthd = lines[5].Substring(2);            //5th line: method name
                string[] argl = lines[4].Substring(2).Split(' '); //5th line: arguments for method
                compileInMemory(code, dlls, nm, cls, mthd, argl);
                Console.SetOut(oldOut);
                break;

            case "//IL-DATA":
                nm   = lines[1].Substring(2);                     //2nd line: namespace
                cls  = lines[2].Substring(2);                     //3rd line: class name
                mthd = lines[3].Substring(2);                     //4th line: method name
                argl = lines[4].Substring(2).Split(' ');          //5th line: arguments for method
                byte[] data = Convert.FromBase64String(lines[6]); //7th line: b64 encoded assembly
                try
                {
                    oldOut = Console.Out;     //save this
                    Console.SetOut(streamWriter);
                    Assembly        asm             = Assembly.Load(data);
                    Type            type            = asm.GetType(nm + "." + cls);
                    MethodInfo      method          = type.GetMethod(mthd);
                    ParameterInfo[] parameters      = method.GetParameters();
                    object[]        parametersArray = new object[] { argl };
                    method.Invoke(null, parameters.Length == 0 ? null : parametersArray);
                    Console.SetOut(oldOut);
                }
                catch (Exception e)
                {
                    streamWriter.WriteLine("Error Loading IL Assembly:");
                    streamWriter.WriteLine(e.Message);
                }
                break;

            default:
                streamWriter.WriteLine("[-] Invalid module format.");
                break;
            }
            bld.Remove(0, bld.Length);
            bld.Clear();
            streamWriter.WriteLine("SIGNAL-MODULE-FINISHED");
            return(0);
        }
コード例 #25
0
 public void BugFix_InteropMethodCallWithInteropArg_JScript()
 {
     engine.Dispose();
     engine = new JScriptEngine();
     BugFix_InteropMethodCallWithInteropArg();
 }
コード例 #26
0
 public void BugFix_ScriptObjectInHostVariable_JScript()
 {
     engine.Dispose();
     engine = new JScriptEngine();
     BugFix_ScriptObjectInHostVariable();
 }
コード例 #27
0
 public void BugFix_FloatParameterBinding_JScript()
 {
     engine.Dispose();
     engine = new JScriptEngine();
     BugFix_FloatParameterBinding();
 }
コード例 #28
0
 public void BugFix_DoubleExecution_Delegate_JScript()
 {
     engine.Dispose();
     engine = new JScriptEngine();
     BugFix_DoubleExecution_Delegate();
 }
コード例 #29
0
 public void TestInitialize()
 {
     engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging);
 }
コード例 #30
0
        public static IList <IndexData> GetIndexData(string jscript, string paramater, string contextOld, out string contextNew, IList <PriceInfo> priceList)
        {
            var           log    = log4net.LogManager.GetLogger(typeof(IndexCalculate));
            JScriptEngine engine = null;

            if (IsDebugg)
            {
                engine = new JScriptEngine(typeof(IndexCalculate).Name, WindowsScriptEngineFlags.EnableDebugging);
            }
            else
            {
                engine = new JScriptEngine(typeof(IndexCalculate).Name);
            }
            using (engine )
            {
                //log.Info("开始计算:" );
                var privatePath = string.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath) ? AppDomain.CurrentDomain.BaseDirectory : AppDomain.CurrentDomain.RelativeSearchPath;
                engine.Execute(File.ReadAllText(Path.Combine(privatePath, @"Script\json2.js")));
                engine.Execute(File.ReadAllText(Path.Combine(privatePath, @"Script\util.js")));

                engine.Execute("var context=" + jscript);

                engine.Execute("var config=" + paramater);

                engine.Execute("var context=Ext.apply(context,config)");

                if (!string.IsNullOrEmpty(contextOld))
                {
                    engine.Execute("var context_old=" + contextOld);
                    engine.Execute("var context=Ext.apply(context,context_old)");
                }


                //data格式,
                //e[0],//日期
                //e[1],//开盘
                //e[2],//收盘
                //e[3],//最高
                //e[4],//最低
                //e[5],//成交量
                //e[6],//涨跌额
                //e[7],//涨跌幅

                priceList = Filter(contextOld, priceList);

                string dataStr = "";
                foreach (var priceInfo in priceList)
                {
                    if (dataStr.Length == 0)
                    {
                        dataStr = string.Format("['{0}',{1},{2},{3},{4},{5},{6},{7}]",
                                                priceInfo.date.ToString("yyyyMMdd"),
                                                priceInfo.open,
                                                priceInfo.price,
                                                priceInfo.high,
                                                priceInfo.low,
                                                priceInfo.volume,
                                                priceInfo.updown,
                                                priceInfo.percent);
                    }
                    else
                    {
                        dataStr += "," + string.Format("['{0}',{1},{2},{3},{4},{5},{6},{7}]",
                                                       priceInfo.date.ToString("yyyyMMdd"),
                                                       priceInfo.open,
                                                       priceInfo.price,
                                                       priceInfo.high,
                                                       priceInfo.low,
                                                       priceInfo.volume,
                                                       priceInfo.updown,
                                                       priceInfo.percent);
                    }
                }

                engine.Execute("var data=" + '[' + dataStr + ']');

                engine.Execute(@" 
                                  var results=context.calculate(data);
                                  context.cutdownContext(50);
                                  var contextStr=JSON.stringify(context);
                                  ");

                var results = engine.Script.results;

                IList <IndexData> idataList = new List <IndexData>();

                for (int i = 0; i < results.length; i++)
                {
                    string idataStr = results[i][0] + "";
                    var    idata    = new IndexData(results[i][0]);
                    for (int j = 1; j < results[i].length; j++)
                    {
                        idataStr += "-" + results[i][j];
                        double value = 0;
                        double.TryParse(results[i][j] + "", out value);
                        idata.Add(value);
                    }
                    //log.Info(idataStr);
                    idataList.Add(idata);
                }

                contextNew = engine.Script.contextStr;
                //log.Info("计算完成" );
                return(idataList);
            }
        }
コード例 #31
0
        public void ProcessRequest(HttpContext context)
        {
            DateTime start = DateTime.Now;

            string[] paths   = context.Request.Params.GetValues("path");
            string[] scripts = context.Request.Params.GetValues("script");

            int pathIndex = -1;

            context.Response.ContentType = "text/plain";
            context.Response.Write("Connected to SINJ handler on " + Environment.MachineName + "\r\n");
            context.Response.Write("Sinj Version " + Assembly.GetExecutingAssembly().GetName().Version + "\r\n");

            context.Response.Write("Num Paths = " + GetDebugString(paths) + "\r\n");
            context.Response.Write("Num Scripts = " + GetDebugString(scripts) + "\r\n");

            WindowsScriptEngineFlags flags = WindowsScriptEngineFlags.None;

            if (context.Request.Params["debug"] == "true")
            {
                flags = WindowsScriptEngineFlags.EnableDebugging;
            }

            using (ScriptEngine engine = new JScriptEngine(flags))
            {
                var pushContext = new PushContext();
                engine.AddHostObject("$sc", pushContext);

                //these global variables should not be here polluting the global namespace in javascript
                //they should hang off $sc, that's what PushContext is for - KW
                engine.AddHostType("$scItemManager", typeof(Sitecore.Data.Managers.ItemManager));
                engine.AddHostType("$scTemplateManager", typeof(Sitecore.Data.Managers.TemplateManager));
                engine.AddHostType("$scLanguage", typeof(Sitecore.Globalization.Language));
                engine.AddHostType("$scVersion", typeof(Sitecore.Data.Version));
                engine.AddHostType("$scID", typeof(Sitecore.Data.ID));
                engine.AddHostType("$scTemplateIDs", typeof(Sitecore.TemplateIDs));
                engine.AddHostType("$scTemplateFieldIDs", typeof(Sitecore.TemplateFieldIDs));
                engine.AddHostType("$scTemplateFieldSharing", typeof(Sitecore.Data.Templates.TemplateFieldSharing));
                engine.AddHostObject("$scMediaItem", new MediaItem());
                engine.AddHostType("$scFieldIDs", typeof(Sitecore.FieldIDs));

                if (scripts != null && paths != null)
                {
                    try
                    {
                        using (new Sitecore.SecurityModel.SecurityDisabler())
                        {
                            foreach (string script in scripts)
                            {
                                pathIndex++;

                                engine.Execute(script);

                                pushContext.RunAsUser(null);
                            }
                        }

                        TimeSpan duration = DateTime.Now - start;

                        context.Response.Write(String.Format("Sinj.PushHandler Completed Successfully in {0} seconds.", duration.TotalSeconds));
                    }
                    catch (ScriptEngineException e)
                    {
                        context.Response.Write("PushHandler error in script file' " + paths[pathIndex] + "'. ");
                        context.Response.Write(e.ErrorDetails + "\r\n\r\n" + e.InnerException + "\r\n\r\n");
                    }
                }
                else
                {
                    engine.Execute("$sc.log('Hello from Sinj...')");
                }
            }
        }
コード例 #32
0
 public void TestInitialize()
 {
     engine = new JScriptEngine(Windows.WindowsScriptEngineFlags.EnableDebugging, NullSyncInvoker.Instance);
 }