Exemplo n.º 1
0
 public override void Cleanup()
 {
     engine_.Dispose();
     engine_ = null;
     runtime_.Dispose();
     runtime_ = null;
 }
 public Utils.ExecutionInfo Run(string javaScriptFile, JavaScriptEngine javaScriptEngine)
 {
     var r2 = new Utils.ExecutionInfo();
     var commandLine = @" ""{0}"" ".format(javaScriptFile);
     var r = Utils.Execute("node.exe", commandLine);
     return r;
 }
Exemplo n.º 3
0
        protected virtual void LoadSource()
        {
            var source = File.ReadAllText(Filename);

            JavaScriptEngine.Execute(source, new ParserOptions {
                Source = Path.GetFileName(Filename)
            });
        }
Exemplo n.º 4
0
        static JavaScriptValue Echo(JavaScriptEngine engine, bool construct, JavaScriptValue thisValue, IEnumerable <JavaScriptValue> arguments)
        {
            string fmt = arguments.First().ToString();

            object[] args = (object[])arguments.Skip(1).ToArray();
            Console.WriteLine(fmt, args);
            return(engine.UndefinedValue);
        }
        public Utils.ExecutionInfo Run(string javaScriptFile, JavaScriptEngine javaScriptEngine)
        {
            var r2          = new Utils.ExecutionInfo();
            var commandLine = @" ""{0}"" ".format(javaScriptFile);
            var r           = Utils.Execute("node.exe", commandLine);

            return(r);
        }
Exemplo n.º 6
0
 public async Task Setup()
 {
     await DispatchContainer.GlobalDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         runtime_ = new JavaScriptRuntime();
         engine_  = runtime_.CreateEngine();
     });
 }
Exemplo n.º 7
0
        private IJavaScriptValue EchoForNoNamespace(JavaScriptEngine source, bool construct, IJavaScriptValue thisValue, IEnumerable <IJavaScriptValue> args)
        {
            string arg = args.First().ToString();

            Assert.AreEqual("callback completed", arg);
            successSignal.SetResult(0);
            return(source.UndefinedValue);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Loads this plugin
        /// </summary>
        public void Load()
        {
            // Load the plugin
            string code = File.ReadAllText(Filename);

            Name = Path.GetFileNameWithoutExtension(Filename);
            JavaScriptEngine.Execute(code);
            if (JavaScriptEngine.GetValue(Name).TryCast <ObjectInstance>() == null)
            {
                throw new Exception("Plugin is missing main object");
            }
            Class = JavaScriptEngine.GetValue(Name).AsObject();
            if (!Class.HasProperty("Name"))
            {
                Class.FastAddProperty("Name", Name, true, false, true);
            }
            else
            {
                Class.Put("Name", Name, true);
            }

            // Read plugin attributes
            if (!Class.HasProperty("Title") || string.IsNullOrEmpty(Class.Get("Title").AsString()))
            {
                throw new Exception("Plugin is missing title");
            }
            if (!Class.HasProperty("Author") || string.IsNullOrEmpty(Class.Get("Author").AsString()))
            {
                throw new Exception("Plugin is missing author");
            }
            if (!Class.HasProperty("Version") || Class.Get("Version").ToObject() == null)
            {
                throw new Exception("Plugin is missing version");
            }
            Title     = Class.Get("Title").AsString();
            Author    = Class.Get("Author").AsString();
            Version   = (VersionNumber)Class.Get("Version").ToObject();
            HasConfig = Class.HasProperty("HasConfig") && Class.Get("HasConfig").AsBoolean();

            // Set attributes
            Class.FastAddProperty("Plugin", JsValue.FromObject(JavaScriptEngine, this), true, false, true);

            Globals = new List <string>();
            foreach (var property in Class.Properties)
            {
                if (property.Value.Value != null)
                {
                    var callable = property.Value.Value.Value.TryCast <ICallable>();
                    if (callable != null)
                    {
                        Globals.Add(property.Key);
                    }
                }
            }

            // Bind any base methods (we do it here because we don't want them to be hooked)
            BindBaseMethods();
        }
Exemplo n.º 9
0
        protected override void LoadSource()
        {
            var source = File.ReadAllText(Filename);

            JavaScriptEngine.SetValue("__CoffeeSource", source);
            JavaScriptEngine.Execute($"eval(__CompileScript('{Name}'))", new ParserOptions {
                Source = Path.GetFileName(Filename)
            });
        }
Exemplo n.º 10
0
 public ReplViewModel()
 {
     readOnly       = false;
     engine         = new JavaScriptEngine();
     prompt         = "$ ";
     items          = new ObservableCollection <String>();
     ClearCommand   = new RelayCommand(() => Clear());
     ExecuteCommand = new RelayCommand(cmd => Run(cmd.ToString()));
 }
        public void Setup()
        {
            var settings = new JavaScriptRuntimeSettings()
            {
                EnableIdleProcessing = true,
            };

            runtime_ = new JavaScriptRuntime(settings);
            engine_  = runtime_.CreateEngine();
        }
Exemplo n.º 12
0
 public async Task Cleanup()
 {
     await DispatchContainer.GlobalDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         engine_.Dispose();
         engine_ = null;
         runtime_.Dispose();
         runtime_ = null;
     });
 }
        public override void Setup()
        {
            var settings = new JavaScriptRuntimeSettings()
            {
                AllowScriptInterrupt = true,
            };

            runtime_ = new JavaScriptRuntime(settings);
            engine_  = runtime_.CreateEngine();
        }
Exemplo n.º 14
0
        internal static void RunEval(string code, PipeStream pipeStream, StreamWriter writer)
        {
            using (JavaScriptRuntime runtime = new JavaScriptRuntime())
                using (JavaScriptEngine engine = runtime.CreateEngine())
                {
                    try
                    {
                        using (engine.AcquireContext())
                        {
                            engine.AddTypeToGlobal <JSConsole>();
                            engine.AddTypeToGlobal <XMLHttpRequest>();
                            engine.SetGlobalVariable("tools", engine.Converter.FromObject(new Tools()));
                            engine.SetGlobalVariable("console", engine.Converter.FromObject(new JSConsole()));

                            engine.SetGlobalFunction("get", JsGet);
                            engine.SetGlobalFunction("post", JsPost);
                            engine.SetGlobalFunction("atob", JsAtob);
                            engine.SetGlobalFunction("btoa", JsBtoa);

                            try
                            {
                                var fn = engine.EvaluateScriptText($@"(function() {{ {code} }})();");
                                var v  = fn.Invoke(Enumerable.Empty <JavaScriptValue>());

                                if (engine.HasException)
                                {
                                    var e = engine.GetAndClearException();
                                    writer.WriteLine(JsonConvert.SerializeObject(engine.Converter.ToObject(e)));
                                }
                                else
                                {
                                    string o = engine.Converter.ToString(v);
                                    writer.WriteLine(JsonConvert.SerializeObject(o));
                                }
                            }
                            catch (Exception ex)
                            {
                                if (engine.HasException)
                                {
                                    var e = engine.GetAndClearException();
                                    writer.WriteLine(JsonConvert.SerializeObject(engine.Converter.ToObject(e)));
                                }
                                else
                                {
                                    writer.WriteLine(JsonConvert.SerializeObject(ex));
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        writer.WriteLine(JsonConvert.SerializeObject(ex));
                    }
                }
        }
Exemplo n.º 15
0
        public override void Cleanup()
        {
            dataView_   = null;
            typedArray_ = null;
            buffer_     = null;

            engine_.Dispose();
            engine_ = null;
            runtime_.Dispose();
            runtime_ = null;
        }
Exemplo n.º 16
0
 private void btnStop_Click(object sender, EventArgs e)
 {
     try {
         JavaScriptEngine.getContext().TerminateExecution();
         threadJS.Abort();
         btnRun.Visible  = true;
         btnStop.Visible = false;
         addDebugInfo("Javascript program terminated.");
     } catch (Exception ex) {
         addDebugInfo("Javascript Engine error:" + ex.Message);
     }
 }
 public CompilerResultUtility CompileToJavaScript(string typeScriptFile, JavaScriptEngine javaScriptEngine)
 {
     var r2 = new CompilerResultUtility();
     r2.InputFileName = typeScriptFile;
     var typeScriptCompilerFile = this.ExportTypeScriptCompiler();
     r2.OutputFileName = Path.Combine(Path.GetDirectoryName(typeScriptFile), Path.GetFileNameWithoutExtension(typeScriptFile)+ ".js");
     var commandLine = @" ""{0}"" ""{1}"" -out ""{2}"" ".format(typeScriptCompilerFile, typeScriptFile, r2.OutputFileName);
     var r = Utils.Execute(NodeJSExe, commandLine);
     r2.ConsoleOutput = r.Succeeded ? r.Output : r.ErrorOutput;
     r2.Succeeded = r.Succeeded;
     return r2;
 }
Exemplo n.º 18
0
        private IJavaScriptValue MessageDialog(JavaScriptEngine source, bool construct, IJavaScriptValue thisValue, IEnumerable <IJavaScriptValue> args)
        {
            if (!construct)
            {
                var undefined = source.UndefinedValue;
                source.SetException(source.CreateTypeError("Must call as a constructor."));
                return(undefined);
            }

            var dlg = new MessageDialog(args.First().ToString());

            return(source.Converter.FromWindowsRuntimeObject(dlg));
        }
Exemplo n.º 19
0
        private IJavaScriptValue EchoForProjectedNamespace(JavaScriptEngine source, bool construct, IJavaScriptValue thisValue, IEnumerable <IJavaScriptValue> args)
        {
            string arg = args.First().ToString();

            arg = arg.Replace("{", "{{").Replace("}", "}}");
            Debug.WriteLine(string.Format(arg, (object[])args.Skip(1).ToArray()));

            if (arg == "toast promise done")
            {
                successSignal.SetResult(0);
            }
            return(source.UndefinedValue);
        }
Exemplo n.º 20
0
        private IJavaScriptValue Echo(JavaScriptEngine source, bool construct, IJavaScriptValue thisValue, IEnumerable <IJavaScriptValue> args)
        {
            string arg = args.First().ToString();

            arg = arg.Replace("{", "{{").Replace("}", "}}");
            Log.Message(string.Format(arg, (object[])args.Skip(1).ToArray()));

            if (arg == "toast promise done")
            {
                Assert.Succeeded();
            }
            return(source.UndefinedValue);
        }
Exemplo n.º 21
0
        public static void CheckForScriptExceptionOrThrow(JsErrorCode errorCode, JavaScriptEngine engine)
        {
            if (errorCode == JsErrorCode.JsErrorScriptException)
            {
                engine.OnRuntimeExceptionRaised();
                return;
            }

            if (errorCode != JsErrorCode.JsNoError)
            {
                ThrowFor(errorCode);
            }
        }
Exemplo n.º 22
0
        private IWorkflowScriptEvaluator CreateWorkflowScriptEvaluator(IServiceProvider serviceProvider)
        {
            var memoryCache             = new MemoryCache(new MemoryCacheOptions());
            var javaScriptEngine        = new JavaScriptEngine(memoryCache);
            var workflowContextHandlers = new Resolver <IEnumerable <IWorkflowExecutionContextHandler> >(serviceProvider);
            var globalMethodProviders   = new IGlobalMethodProvider[0];
            var scriptingManager        = new DefaultScriptingManager(new[] { javaScriptEngine }, globalMethodProviders);

            return(new JavaScriptWorkflowScriptEvaluator(
                       scriptingManager,
                       workflowContextHandlers.Resolve(),
                       new Mock <ILogger <JavaScriptWorkflowScriptEvaluator> >().Object
                       ));
        }
Exemplo n.º 23
0
        public CompilerResultUtility CompileToJavaScript(string typeScriptFile, JavaScriptEngine javaScriptEngine)
        {
            var r2 = new CompilerResultUtility();

            r2.InputFileName = typeScriptFile;
            var typeScriptCompilerFile = this.ExportTypeScriptCompiler();

            r2.OutputFileName = Path.Combine(Path.GetDirectoryName(typeScriptFile), Path.GetFileNameWithoutExtension(typeScriptFile) + ".js");
            var commandLine = @" ""{0}"" ""{1}"" -out ""{2}"" ".format(typeScriptCompilerFile, typeScriptFile, r2.OutputFileName);
            var r           = Utils.Execute(NodeJSExe, commandLine);

            r2.ConsoleOutput = r.Succeeded ? r.Output : r.ErrorOutput;
            r2.Succeeded     = r.Succeeded;
            return(r2);
        }
Exemplo n.º 24
0
        public override void Setup()
        {
            runtime_ = new JavaScriptRuntime(new JavaScriptRuntimeSettings());
            engine_  = runtime_.CreateEngine();

            var baseline = new ScriptSource("test://init.js", @"(function(global) {
    global.buffer = new ArrayBuffer(1024);
    global.typedArray = new Uint8ClampedArray(buffer);
    global.dataView = new DataView(buffer, 1);
})(this);");

            engine_.Execute(baseline);
            buffer_     = (JavaScriptArrayBuffer)engine_.GetGlobalVariable("buffer");
            typedArray_ = (JavaScriptTypedArray)engine_.GetGlobalVariable("typedArray");
            dataView_   = (JavaScriptDataView)engine_.GetGlobalVariable("dataView");
        }
Exemplo n.º 25
0
 private void txtImdyt_KeyPress(object sender, KeyPressEventArgs e)
 {
     if (e.KeyChar == 13)
     {
         try {
             string code = txtImdyt.Text;
             addDebugInfo(">>> " + code);
             jsReturn = JavaScriptEngine.runCmd(code);
             if (jsReturn != null)
             {
                 addDebugInfo("JSResult>\n" + jsReturn.ToString());
             }
         } catch (Exception ex) {
             addDebugInfo("Javascript Engine error:" + ex.Message);
         }
     }
 }
Exemplo n.º 26
0
        private void btnImportConfigure_Click(object sender, EventArgs e)
        {
            OpenFileDialog cdlgOpenJson = new OpenFileDialog();

            cdlgOpenJson.Filter = "JSON配置文件(*.json)|*.json";
            cdlgOpenJson.ShowDialog();
            if (cdlgOpenJson.FileName != "")
            {
                try {
                    ConfigureFile cfgs = new JSONConfigIO().ReadConfigure(cdlgOpenJson.FileName);
                    ctvr.loadConfigure(cfgs);
                    JavaScriptEngine.runCmd(cfgs.UserDefinedScript);
                } catch (Exception ex) {
                    Logger.logError(ex);
                }
            }
        }
Exemplo n.º 27
0
        //private void PullPrint(UserCredential user, string ip)
        //{
        //    var controller = new SafeComDeviceAutomationController(user, ip);
        //    try
        //    {
        //        controller.Launch();
        //        var initialJobCount = controller.GetNumberOfAvailablePrintJobs();

        //        if (initialJobCount > 0)
        //        {
        //            //controller.PullSinglePrintJob();
        //            TimedDelay.Wait(TimeSpan.FromSeconds(5));
        //            var finalJobCount = controller.GetNumberOfAvailablePrintJobs();
        //            if (finalJobCount == initialJobCount)
        //            {
        //                TraceFactory.Logger.Error("Validation of job counts failed");
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //    finally
        //    {
        //        controller.Finish();
        //    }
        //}

        //private void HpacPullPrint(UserCredential user, string ip)
        //{
        //    var controller = new HpacDeviceAutomationController(user, ip, "admin");
        //    try
        //    {
        //        controller.Launch();
        //        var initialJobCount = controller.GetNumberOfAvailablePrintJobs();

        //        if (initialJobCount > 0)
        //        {
        //            //controller.PullSinglePrintJob();
        //            TimedDelay.Wait(TimeSpan.FromSeconds(5));
        //            var finalJobCount = controller.GetNumberOfAvailablePrintJobs();
        //            if (finalJobCount == initialJobCount)
        //            {
        //                TraceFactory.Logger.Error("Validation of job counts failed");
        //            }
        //        }
        //    }
        //    catch (Exception)
        //    {
        //    }
        //    finally
        //    {
        //        controller.SignOut();
        //    }
        //}

        private void WaitForHtmlString(JavaScriptEngine engine, string validationRegexPattern)
        {
            // Wait for up to 2 minutes for the job to finish
            DateTime end = DateTime.Now + TimeSpan.FromMinutes(2);

            while (DateTime.Now < end)
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                try
                {
                    var html = string.Empty;
                    if (Regex.IsMatch(html, validationRegexPattern, RegexOptions.IgnoreCase))
                    {
                        return;
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Exemplo n.º 28
0
        public bool RunSanityCheck(out string result)
        {
            bool   success = false;
            string error   = string.Empty;

            result = "Success";

            try
            {
                using (var javaScriptEngine = new JavaScriptEngine())
                {
                    // The Script...
                    string script = "(()=>{return \'Hello world!\';})()";

                    var javaScriptValue = javaScriptEngine.RunScript(script);

                    var stringValue = javaScriptEngine.ConvertValueToString(javaScriptValue);

                    if (string.Compare("Hello world!", stringValue, false) == 0)
                    {
                        success = true;
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message + Environment.NewLine + ex.StackTrace;
            }

            if (success)
            {
                result = string.Format("SUCCESS -----------> {0}", GetExecutingAssemblyName());
            }
            else
            {
                result = string.Format("FAILED -----------> {0}{1}{2}", GetExecutingAssemblyName(), Environment.NewLine + Environment.NewLine, error);
            }

            return(success);
        }
Exemplo n.º 29
0
 void runJs()
 {
     try {
         jsReturn = JavaScriptEngine.runCmd(jsCode);
         if (jsReturn != null)
         {
             string printInfo = "JSResult>\n" + jsReturn.ToString();
             BeginInvoke(
                 new Action(
                     () => { addDebugInfo(printInfo); }
                     )
                 );
         }
     }catch (Exception e) {
         Logger.logError(e);
         lstDebugInfo.addItem(
             "Error while executing JS code:"
             + "\n  Error Message:\n" + e.Message
             + "\n   Error Source:\n" + e.Source
             + "\n    Stack Trace:\n" + e.StackTrace);
     }
 }
Exemplo n.º 30
0
        /// <summary>
        /// Gets stats for the latest completed job
        /// </summary>
        /// <param name="ip">The ip.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        static private void GetLatestJobStats(string ip)
        {
            var device = new JediWindjammerDevice(ip, "admin");
            var engine = new JavaScriptEngine(device.ControlPanel);

            //WaitForDeviceToFinish(device);
            device.ControlPanel.PressKeyWait(JediHardKey.Reset, "HomeScreenForm");
            device.ControlPanel.ScrollPressNavigate("mAccessPointDisplay", "Title", "Job Status", "JobStatusMainForm", true);
            var cp = device.ControlPanel;
            var firstJobButtonText = cp.GetProperty("mLoggedJobsListBox_Item0", "Column1Text");

            if (firstJobButtonText == string.Empty)
            {
                TraceFactory.Logger.Error("No job history found");
            }
            else
            {
                //cp.Press("mLogTab");
                cp.PressToNavigate(firstJobButtonText, "JobStatusMainForm", true);
                cp.PressToNavigate("mDetailsButton", "JobDetailsForm", true);
                var doc = device.ControlPanel.GetProperty("m_WebBrowser", "DocumentHTML");
            }
        }
Exemplo n.º 31
0
        public object DecodeCANMessage(ulong signalValue)
        {
            switch (sType)
            {
            //连续值解析
            case SignalType.Continuous:
                double value = signalValue;
                value *= cRatio;
                value += cOffset;
                return(value);

            //离散值解析
            case SignalType.Discrete:
                return(DiscreteDecodeTable.ContainsKey(signalValue) ? DiscreteDecodeTable[signalValue] : string.Format("Undef:{0}", signalValue));

            //开关量解析
            case SignalType.Switch:
                return(SwitchMap[signalValue]);

            //DM1故障码
            case SignalType.DM1FaultCode:
                DM1Value dm1Obj = new DM1Value()
                {
                    FMI = (uint)(signalValue >> 16 & 0x1F),
                    SPN = (uint)(signalValue >> 21 & 7 << 16 | (signalValue & 0xFFFF))
                };
                return(dm1Obj);

            case SignalType.UserDefined:
                //用匿名函数的形式描述解析器(少用)
                //JS: function(var_ulong_value){...}
                return(JavaScriptEngine.runCmd(string.Format("{0}({1})", UDFName, signalValue)));

            default:
                throw new Exception("Undefined signal type, please check your code:" + sType.ToString());
            }
        }
Exemplo n.º 32
0
 private IJavaScriptValue Echo(JavaScriptEngine source, bool construct, IJavaScriptValue thisValue, IEnumerable <IJavaScriptValue> args)
 {
     Log.Message(string.Format(args.First().ToString(), (object[])args.Skip(1).ToArray()));
     return(source.UndefinedValue);
 }
Exemplo n.º 33
0
        private void initAndConnect(string ip, short port, string nickname)
        {
            currentIP = ip;
            GTA.Native.Function.Call("DISABLE_PAUSE_MENU", 1);
            GTA.Native.Function.Call("SET_FILTER_MENU_ON", 1);
            BroadcastingPaused = true;
            playerNames = new Dictionary<uint, string>();
            playerModels = new Dictionary<uint, string>();
            isCurrentlyDead = false;
            actionQueue = new Queue<Action>();
            instance = this;

            jsEngine = new JavaScriptEngine();

            CurrentVirtualWorld = 0;

            cameraController = new CameraController(this);

            debugDraw = new ClientTextView(new System.Drawing.PointF(10, 400), "", new GTA.Font("Segoe UI", 24, FontScaling.Pixel), System.Drawing.Color.White);

            pedStreamer = new PedStreamer(this, 100.0f);
            vehicleStreamer = new VehicleStreamer(this, 100.0f);

            pedController = new PlayerPedController();
            npcPedController = new NPCPedController();
            vehicleController = new VehicleController();
            playerVehicleController = new PlayerVehicleController();
            chatController = new ChatController(this);
            keyboardHandler = new KeyboardHandler(this);
            currentState = ClientState.Initializing;
            Interval = 80;
            //cam = new Camera();
            //cam.Activate();
            currentState = ClientState.Disconnected;
            System.IO.File.WriteAllText("multiv-log.txt", "");
            perFrameRenderer = new PerFrameRenderer(this);

            Player.Character.CurrentRoom = Room.FromString("R_00000000_00000000");

            startTimersandBindEvents();
            try
            {
                if (client != null && client.Connected)
                {
                    client.Close();
                }
                client = new TcpClient();
                IPAddress address = IPAddress.Parse(ip);
                nick = nickname;

                client.Connect(address, port);

                Client.currentData = UpdateDataStruct.Zero;

                serverConnection = new ServerConnection(this);

                World.CurrentDayTime = new TimeSpan(12, 00, 00);
                World.PedDensity = 0;
                World.CarDensity = 0;
                // AlternateHook.call(AlternateHook.OtherCommands.TERMINATE_ALL_SCRIPTS_FOR_NETWORK_GAME);
                GTA.Native.Function.Call("CLEAR_AREA", 0.0f, 0.0f, 0.0f, 4000.0f, true);
                currentState = ClientState.Connecting;
            }
            catch
            {
                currentState = ClientState.Disconnected;
                if (client != null && client.Connected)
                {
                    client.Close();
                }
                throw;
            }
        }
        internal void SetEngine(JavaScriptEngine engine)
        {
            Debug.Assert(engine != null);

            engine_ = new WeakReference<JavaScriptEngine>(engine);
        }