public async void ProcessFrame(FrameData frame) { if (callbacks.Count == 0 || busy) { return; } else { busy = true; } RecognitionServer.Inst.RecognizePose(frame.bitmap, (x) => { var o = JsonObject.Parse(x); var detectedPoses = o["PoseDetection"].GetArray(); ProjectRuntime.Inst.DispatchRuntimeCode(() => { var poses = JavaScriptValue.CreateArray(0); var pushFunc = poses.GetProperty(JavaScriptPropertyId.FromString("push")); foreach (var item in detectedPoses) { var pose = item.GetObject(); var id = pose["PoseID"].GetNumber(); var score = pose["PoseScore"].GetNumber(); var keypoints = pose["Keypoints"].GetArray(); var newKeypoints = new JsonObject(); foreach (var jtem in keypoints) { var keypoint = jtem.GetObject().First(); var defaultPosition = new JsonArray(); defaultPosition.Add(JsonValue.CreateNumberValue(0)); defaultPosition.Add(JsonValue.CreateNumberValue(0)); defaultPosition.Add(JsonValue.CreateNumberValue(0)); var position = keypoint.Value.GetObject().GetNamedArray("Position", defaultPosition); var pos = GetEstimatedPositionFromPosition(new Vector3((float)position.GetNumberAt(0), (float)position.GetNumberAt(1), (float)position.GetNumberAt(2)), frame.bitmap); //var pos = GetEstimatedPositionFromPosition(new Vector3(1, 1, 1), frame.bitmap); var newKeypoint = new JsonObject(); var newPosition = new JsonArray(); newPosition.Add(JsonValue.CreateNumberValue(pos.X)); newPosition.Add(JsonValue.CreateNumberValue(pos.Y)); newPosition.Add(JsonValue.CreateNumberValue(pos.Z)); newKeypoint.Add("position", newPosition); newKeypoint.Add("score", JsonValue.CreateNumberValue(keypoint.Value.GetObject().GetNamedNumber("Score", 0.5))); //newKeypoint.Add("score", JsonValue.CreateNumberValue(0)); newKeypoints.Add(keypoint.Key, newKeypoint); } var jsPose = JavaScriptContext.RunScript($"new Pose({id}, {score}, {newKeypoints.Stringify()});"); pushFunc.CallFunction(poses, jsPose); } foreach (var callback in callbacks) { callback.CallFunction(callback, poses); } }); busy = false; }); }
private static JavaScriptValue RunScript(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData) { if (argumentCount < 2) { ThrowException("not enough arguments"); return(JavaScriptValue.Invalid); } // // Convert filename. // string filename = arguments[1].ToString(); // // Load the script from the disk. // string script = File.ReadAllText(filename); if (string.IsNullOrEmpty(script)) { ThrowException("invalid script"); return(JavaScriptValue.Invalid); } // // Run the script. // return(JavaScriptContext.RunScript(script, currentSourceContext++, filename)); }
private void InitializeArmUnimplementedFunctions() { LogVerbose("Initializing unimplemented function list"); _unimplementedFunctions.UnionWith(GetDefinedFunctionNames(ArmRuntimeJsScripts.unimplementedArmFunctions)); JavaScriptContext.RunScript(ArmRuntimeJsScripts.unimplementedArmFunctions); }
private void EvaluateResources() { LogVerbose("Evaluating resources"); foreach (var resource in _armTemplate.Resources) { JObject copy = null; if (resource.Properties().Any(p => p.Name.Equals("copy"))) { copy = resource.Property("copy").Value as JObject; } if (copy != null && copy.Properties().Any(p => p.Name.Equals("name")) && copy.Properties().Any(p => p.Name.Equals("count"))) { EvaluateResourceWithCopy(resource); } else { EvaluateResource(resource); } JavaScriptContext.RunScript("setCopyIndex(-1);"); } }
private void button1_Click(object sender, EventArgs e) { JavaScriptRuntime runtime; JavaScriptContext context; JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero); bool bSuccess = false; try { string script = System.IO.File.ReadAllText("C:/Temp/Script/Sample01.js"); runtime = JavaScriptRuntime.Create(); context = runtime.CreateContext(); JavaScriptContext.Current = context; JavaScriptContext.RunScript(script, currentSourceContext++, ""); bSuccess = true; } finally { if (true == bSuccess) { System.Diagnostics.Trace.WriteLine("Success"); } else { System.Diagnostics.Trace.WriteLine("Error"); } } }
private void EvaluateResourceWithCopy(JObject resource) { var copy = resource.Property("copy").Value as JObject; LogVerbose(string.Format("Found copy node {0}", copy["name"])); EvaluateJToken(copy); if (!_copyNames.Add(copy["name"].ToString())) { throw new ArgumentException(string.Format("Copy loop name '{0}' name is already in use.", copy["name"])); } //Get rid of copy resource.Remove("copy"); var numInstances = copy.Property("count").Value.ToObject <int>(); JavaScriptContext.RunScript(string.Format("var {0}=[]", copy["name"])); for (int i = 0; i < numInstances; i++) { JavaScriptContext.RunScript(string.Format("setCopyIndex({0});", i)); var copiedResource = EvaluateResource(resource.DeepClone()); JavaScriptContext.RunScript(string.Format("{0}.push('{1}');", copy.Property("name").Value, copiedResource["name"])); } }
public void Execute(string script) { using (new JavaScriptContext.Scope(context)) { try { var result = JavaScriptContext.RunScript(script); } catch (JavaScriptScriptException e) { var message = e.Error.Get("message").ConvertToString().ToString(); if (e.Error.Has("line") && e.Error.Has("column")) { var line = e.Error.Get("line").ToInt32(); var col = e.Error.Get("column").ToInt32(); System.Diagnostics.Debug.WriteLine($"JavaScriptError on {line}:{col} => {message}"); } else { System.Diagnostics.Debug.WriteLine($"JavaScriptError => {message}"); } } catch (JavaScriptUsageException e) { System.Diagnostics.Debug.WriteLine($"Usage exception during script execution: {e.Message}"); System.Diagnostics.Debug.WriteLine(e.StackTrace); } catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Exception during script execution: {e.Message}"); } } }
public void LoadExtensions_PointedToPreferencesFile_LoadsCustomSnippets() { // Arrange var engine = JavaScriptRuntime.Create(JavaScriptRuntimeAttributes.None); JavaScriptContext ctx = engine.CreateContext(); JavaScriptContext.Current = ctx; var compiler = new EngineCompiler(); // Act compiler.CompileCore(JavaScriptSourceContext.None); compiler.LoadExtensions( Path.Combine(TestContext.DeploymentDirectory, "Resources"), JavaScriptSourceContext.None); // Assert string script = "replaceAbbreviation('cst', '3', 'markup')"; JavaScriptValue result = JavaScriptContext.RunScript(script, JavaScriptSourceContext.None); // preferences.json file contains "cst" abbreviation. If we are able to find it then // our extension has been loaded correctly. result.ValueType.Should().Be(JavaScriptValueType.String); engine.Dispose(); }
private void RunScriptAsync(string script) { App.Current.Dispatcher.BeginInvoke(new Action(() => { JavaScriptContext.RunScript(script); })); }
public static oResult test_2(Dictionary <string, object> request = null) { oResult rs = new oResult() { ok = false, request = request }; using (new JavaScriptContext.Scope(js_context)) { string script = "(()=>{ var val = ___api.test('TEST_2: Hello world'); ___api.log('api-js.test-2', 'key-2', 'TEST_2: This log called by JS...'); return val; })()"; try { JavaScriptValue result = JavaScriptContext.RunScript(script, CURRENT_SOURCE_CONTEXT++, string.Empty); rs.data = result.ConvertToString().ToString(); rs.ok = true; } catch (JavaScriptScriptException e) { var messageName = JavaScriptPropertyId.FromString("message"); rs.error = "ERROR_JS_EXCEPTION: " + e.Error.GetProperty(messageName).ConvertToString().ToString(); } catch (Exception e) { rs.error = "ERROR_CHAKRA: failed to run script: " + e.Message; } } return(rs); }
/// <summary> /// Runs the given script. /// </summary> /// <param name="script">The script.</param> /// <param name="sourceUrl">The source URL.</param> public void RunScript(string script, string sourceUrl) { if (script == null) { throw new ArgumentNullException(nameof(script)); } if (sourceUrl == null) { throw new ArgumentNullException(nameof(sourceUrl)); } string source = LoadScriptAsync(script).Result; try { _context = JavaScriptSourceContext.Increment(_context); JavaScriptContext.RunScript(source, _context, sourceUrl); } catch (JavaScriptScriptException ex) { var jsonError = JavaScriptValueToJTokenConverter.Convert(ex.Error); var message = jsonError.Value <string>("message"); var stackTrace = jsonError.Value <string>("stack"); throw new Modules.Core.JavaScriptException(message ?? ex.Message, stackTrace, ex); } }
public JavaScriptValue Eval(string script) { var debugService = CurrentNode.GetService <IRuntimeDebuggingService>(); return(contextSwitch.With(() => JavaScriptContext.RunScript(script, debugService.GetScriptContext("Script", script)))); }
protected override void OnUpdate(float timeStep) { base.OnUpdate(timeStep); time += timeStep; if (time < UPDATE_INTERVAL) { return; } else { time -= UPDATE_INTERVAL; } if (callbacks.Count == 0) { return; } ProjectRuntime.Inst.DispatchRuntimeCode(() => { var position = JavaScriptContext.RunScript($"new Position({Node.WorldPosition.X}, {Node.WorldPosition.Y}, {Node.WorldPosition.Z});"); var forwardVec = Node.WorldRotation * Vector3.Forward; var forward = JavaScriptContext.RunScript($"new Position({forwardVec.X}, {forwardVec.Y}, {forwardVec.Z});"); var upVec = Node.WorldRotation * Vector3.Up; var up = JavaScriptContext.RunScript($"new Position({upVec.X}, {upVec.Y}, {upVec.Z});"); var rightVec = Node.WorldRotation * Vector3.Right; var right = JavaScriptContext.RunScript($"new Position({rightVec.X}, {rightVec.Y}, {rightVec.Z});"); foreach (var callback in callbacks) { callback.CallFunction(callback, position, forward, up, right); } }); }
private void EvaluateParameters() { if (_armTemplate.Parameters == null) { return; } LogVerbose("Evaluating parameters..."); foreach (var param in _armTemplate.Parameters) { if (param.Value.DefaultValue == null) { throw new Exception(string.Format("No value specified for parameter '{0}'", param.Key)); } param.Value.DefaultValue = EvaluateJToken(param.Value.DefaultValue); const string arrayType = "array"; const string stringType = "string"; const string secureStringType = "securestring"; const string intType = "int"; const string objectType = "object"; switch (param.Value.Type.ToLowerInvariant()) { case arrayType: ThrowIfNotCorrectType(param, JTokenType.Array, arrayType); break; case stringType: ThrowIfNotCorrectType(param, JTokenType.String, stringType); break; case secureStringType: ThrowIfNotCorrectType(param, JTokenType.String, secureStringType); break; case intType: ThrowIfNotCorrectType(param, JTokenType.Integer, intType); break; case objectType: ThrowIfNotCorrectType(param, JTokenType.Object, objectType); break; default: throw new ArgumentException(string.Format("<{0},{1}>: Unrecognized paramater type", param.Value.LineNumber, param.Value.LinePosition)); } string expression = string.Format("params[\"{0}\"]= {1};", param.Key, GetJsParseJSONExpression(param.Value.DefaultValue)); JavaScriptContext.RunScript(expression); } LogVerbose("Finished parameter evaluation"); }
private void ReadModifiedResources() { LogVerbose("Getting modified resource list"); var modifiedResources = JavaScriptContext.RunScript("JSON.stringify(resources)") .ConvertToString() .ToString(); _armTemplate.Resources = JsonConvert.DeserializeObject <List <JObject> >(modifiedResources); }
private void TimerFired(object sender, ElapsedEventArgs e) { if (App.Current != null) { App.Current.Dispatcher.BeginInvoke(new Action(() => { JavaScriptContext.RunScript("controller.task();"); })); } }
/// <summary> /// Executes Emmet command with the specified identifier on the specified editor view. /// </summary> /// <param name="cmdId">Identifier of the command to execute.</param> /// <param name="view">Editor to execute command in.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Indicates that the specified command identifier was not found. /// </exception> public bool RunCommand(int cmdId, ICodeEditor view) { if (!_initialized) { InitializeEngine(); } string script; switch (cmdId) { case PackageIds.CmdIDExpandAbbreviation: script = GetExpandAbbreviationScript(view); break; case PackageIds.CmdIDWrapWithAbbreviation: script = GetWrapWithAbbreviationScript(view); if (script is null) { return(false); } break; default: throw new ArgumentOutOfRangeException( nameof(cmdId), cmdId, "Specified command identifier not found."); } Trace($"Running script: {script}"); JavaScriptContext.Current = _context; JavaScriptValue result = JavaScriptContext.RunScript(script, _currentSourceContext++); if (result.ValueType is JavaScriptValueType.Boolean) { Trace("Emmet engine failed to execute command."); return(false); } string replacement = result.ToString(); JavaScriptContext.Idle(); if (cmdId is PackageIds.CmdIDExpandAbbreviation) { view.ReplaceCurrentLine(replacement); } else { view.ReplaceSelection(replacement); } Trace($"Command {script} completed successfully."); return(true); }
private JToken EvaluateResource(JToken resource) { EvaluateJToken(resource); string jsParseJsonExpression = GetJsParseJSONExpression(resource); //update the state of resources in javascript runtime JavaScriptContext.RunScript(string.Format("setResource('{0}',{1});", resource["name"], jsParseJsonExpression), _currentSourceContext++, resource["name"].ToString()); return(resource); }
private void button4_Click(object sender, EventArgs e) { JavaScriptRuntime runtime; JavaScriptContext context; JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero); JavaScriptValue DbgStringFn; JavaScriptValue DbgStringName; JavaScriptPropertyId DbgStringId; JavaScriptValue SumFn; JavaScriptValue SumName; JavaScriptPropertyId SumId; IntPtr callbackState = IntPtr.Zero; bool bSuccess = false; try { string script = System.IO.File.ReadAllText("C:/Temp/Script/Sample04.js"); runtime = JavaScriptRuntime.Create(); context = runtime.CreateContext(); JavaScriptContext.Current = context; DbgStringName = JavaScriptValue.FromString("DbgString"); DbgStringId = JavaScriptPropertyId.FromString("DbgString"); Native.JsCreateNamedFunction(DbgStringName, (ChakraHost.Hosting.JavaScriptNativeFunction)DbgString, callbackState, out DbgStringFn); JavaScriptValue.GlobalObject.SetProperty(DbgStringId, DbgStringFn, true); SumName = JavaScriptValue.FromString("Sum"); SumId = JavaScriptPropertyId.FromString("Sum"); Native.JsCreateNamedFunction(SumName, (ChakraHost.Hosting.JavaScriptNativeFunction)Sum, callbackState, out SumFn); JavaScriptValue.GlobalObject.SetProperty(SumId, SumFn, true); JavaScriptContext.RunScript(script, currentSourceContext++, ""); bSuccess = true; } finally { if (true == bSuccess) { System.Diagnostics.Trace.WriteLine("Success"); } else { System.Diagnostics.Trace.WriteLine("Error"); } } }
public string Eval(string CodeToExecute) { using (new JavaScriptContext.Scope(Runtime.CreateContext())) { DefineEcho(); var result = JavaScriptContext.RunScript(CodeToExecute); //var numberResult = result.ConvertToNumber(); //var doubleResult = numberResult.ToDouble(); return(result.ToString()); } }
private void InitializeArmRuntimeScripts() { foreach (var script in _runtimeScripts) { LogVerbose(string.Format("Executing ARM script {0}", script)); JavaScriptContext.RunScript(script); } JavaScriptContext.RunScript(string.Format("subscriptionId = '{0}';", _subscriptionId)); JavaScriptContext.RunScript(string.Format("resourceGroupName = '{0}';", _resourceGroupName)); JavaScriptContext.RunScript(string.Format("resourceGroupLocation = '{0}';", regionNameRegex.Replace(_resourceGroupLocation, string.Empty).ToLowerInvariant())); }
public static JavaScriptValue RunFile(string filename) { string path = new JavaScript.Module.Resolver(javascriptRoot).Normalize(null, filename); if (path == null) { throw new Exception($"Could not find file from specifier '{filename}'"); } string code = JavaScript.Module.Loader.ConvertSourceToJS(System.IO.File.ReadAllText(path), path); return(JavaScriptContext.RunScript(code, filename)); }
public async void ProcessFrame(FrameData frame) { if (callbacks.Count == 0 || busy) { return; } else { busy = true; } var bitmap = frame.bitmap; if (!FaceDetector.IsBitmapPixelFormatSupported(bitmap.BitmapPixelFormat)) { bitmap = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Gray8); } var detectedFaces = await faceDetector.DetectFacesAsync(bitmap); int frameKey = -1; if (detectedFaces.Count > 0) { frameKey = SceneCameraManager.Inst.AddFrameToCache(frame); } ProjectRuntime.Inst.DispatchRuntimeCode(() => { var jsImg = JavaScriptValue.CreateObject(); jsImg.SetProperty(JavaScriptPropertyId.FromString("id"), JavaScriptValue.FromInt32(frameKey), true); Native.JsSetObjectBeforeCollectCallback(jsImg, IntPtr.Zero, jsObjectCallback); var faces = JavaScriptValue.CreateArray(0); var pushFunc = faces.GetProperty(JavaScriptPropertyId.FromString("push")); foreach (var face in detectedFaces) { var pos = GetEstimatedPositionFromFaceBounds(face.FaceBox, frame.bitmap); var jsFace = JavaScriptContext.RunScript($"new Face(new Position({pos.X}, {pos.Y}, {pos.Z}), {0});"); jsFace.SetProperty(JavaScriptPropertyId.FromString("frame"), jsImg, true); jsFace.SetProperty(JavaScriptPropertyId.FromString("bounds"), face.FaceBox.ToJavaScriptValue(), true); pushFunc.CallFunction(faces, jsFace); } foreach (var callback in callbacks) { callback.CallFunction(callback, faces); } }); busy = false; }
public void Benchmark7_5() { using (var c = ControllerTests.MakeController()) { c.Evaluate("var i = 1"); c.Evaluate("var f = (function() { i += 1; })"); c.Evaluate("f()"); Go(() => { JavaScriptContext.RunScript("for (var i=0; i<10000;i++) { f() }"); }); Console.WriteLine(i); } }
public ChakraCoreTypeScriptTranspiler() { using var stream = typeof(ChakraCoreTypeScriptTranspiler).Assembly.GetManifestResourceStream(typeof(V8TypeScriptTranspiler), "typescriptServices.js"); using var reader = new StreamReader(stream); var typescriptServicesSource = reader.ReadToEnd(); _runtime = JavaScriptRuntime.Create(JavaScriptRuntimeAttributes.None); _context = JavaScriptContext.CreateContext(_runtime); // Install the compiler in the context using (var scope = _context.GetScope()) { JavaScriptContext.RunScript(typescriptServicesSource); } }
private void EvaluateScript(string script, string sourceUrl) { try { _context = JavaScriptSourceContext.Increment(_context); JavaScriptContext.RunScript(script, _context, sourceUrl); } catch (JavaScriptScriptException ex) { var jsonError = JavaScriptValueToJTokenConverter.Convert(ex.Error); var message = jsonError.Value <string>("message"); var stackTrace = jsonError.Value <string>("stack"); throw new Modules.Core.JavaScriptException(message ?? ex.Message, stackTrace, ex); } }
private void RunUserScript(ArmTemplateScript script) { try { LogVerbose(string.Format("Running user script {0}", GetScriptPath(script))); _userScriptFunctions.UnionWith(GetDefinedFunctionNames(File.ReadAllText(GetScriptPath(script)))); JavaScriptContext.RunScript(File.ReadAllText(GetScriptPath(script)), _scriptToSourceContexts[script], script.ScriptUri); } catch (JavaScriptScriptException eX) { Console.Error.WriteLine("Error executing script '{0}': {1}", script.ScriptUri, GetExceptionString(eX.Error)); throw; } }
public JavaScriptValue Execute(string source, string name) { var sourceName = string.IsNullOrEmpty(name) ? name : FixSourceName(name); if (string.IsNullOrEmpty(source)) { ThrowException("invalid script"); return(JavaScriptValue.Invalid); } // // Run the script. // return(JavaScriptContext.RunScript(source, currentSourceContext++, sourceName)); }
/// <summary> /// Finds and compiles Emmet source file. /// </summary> /// <param name="sourceContext">Source context to use during compilation.</param> /// <exception cref="FileNotFoundException">Indicates that Emmet script was not found.</exception> /// <exception cref="Exception{EmmetEngineExceptionArgs}"> /// Indicates that JavaScript error occurred during compilation. /// </exception> public void CompileCore(JavaScriptSourceContext sourceContext) { string extensionFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string emmetScriptPath = Path.Combine(extensionFolder, EmmetScript); if (!File.Exists(emmetScriptPath)) { throw new FileNotFoundException("Emmet script not found.", emmetScriptPath); } string script = File.ReadAllText(emmetScriptPath); JavaScriptContext.RunScript(script, sourceContext); Trace("Emmet core compiled successfully."); }
protected override object RunScript(string javaScriptString, string filename) { IntPtr returnValue; try { JavaScriptValue result; switchContextifNeeded(); if (filename != null && filename != "") { result = JavaScriptContext.RunScript(javaScriptString, currentSourceContext, filename); currentSourceContext = JavaScriptSourceContext.Increment(currentSourceContext); } else { result = JavaScriptContext.RunScript(javaScriptString, JavaScriptSourceContext.None, string.Empty); } // Execute promise tasks stored in taskQueue while (_jsTaskQueue.Count != 0) { JavaScriptValue jsTask = (JavaScriptValue)_jsTaskQueue.Dequeue(); JavaScriptValue promiseResult; JavaScriptValue global; Native.JsGetGlobalObject(out global); JavaScriptValue[] args = new JavaScriptValue[1] { global }; Native.JsCallFunction(jsTask, args, 1, out promiseResult); } // Convert the return value. JavaScriptValue stringResult; UIntPtr stringLength; Native.ThrowIfError(Native.JsConvertValueToString(result, out stringResult)); Native.ThrowIfError(Native.JsStringToPointer(stringResult, out returnValue, out stringLength)); } catch (Exception e) { // throw e; NKLogging.log(e.Message); return(null); } return(Marshal.PtrToStringUni(returnValue)); }