/// <summary> /// Retrieves the JSON representation of a CLR object, /// consisting of a dictionary of strings to objects. /// </summary> /// <param name="o">CLR object, /// consisting of a dictionary of strings (attributes) to objects (values).</param> /// <returns>JSON representation, as string</returns> public static string SerializeObject(object o) { JavascriptContext context = null; try { if (o == null) return ""; context = new JavascriptContext(); context.SetParameter("arg1", o); context.SetParameter("obj", null); context.Run(@" obj = JSON.stringify(arg1, null); "); return (string)context.GetParameter("obj"); } catch (AccessViolationException) { throw new Exception("Access Violation Exception. Probably you should restart the app ..."); } catch (Exception ex) { throw new Exception("Error in SerializeObject.", ex); } finally { if (context != null) { context.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); } } }
/// <summary> /// 载入自动修改脚本,并创建菜单 /// </summary> // TODO 如果两个脚本 name 相同会崩溃 // TODO 如果 JS 代码有错误会崩溃 private void loadReplaces() { DirectoryInfo replaces = new DirectoryInfo(Directory.GetCurrentDirectory() + "/replaces"); using (JavascriptContext context = new JavascriptContext()) { context.SetParameter("commands", new string[] { }); foreach (FileInfo replace in replaces.GetFiles()) { if (replace.Extension.Equals(".js")) { string script = File.ReadAllText(replace.FullName); context.Run(script); string name = context.GetParameter("name") as string; this.replaces.Add(name, script); ToolStripMenuItem menuItem = new ToolStripMenuItem(name); menuItem.Click += this.replace_Click; this.自动修改命令.DropDownItems.Add(menuItem); } } } }
private void js_test() { using (JavascriptContext context = new JavascriptContext()) { // Setting external parameters for the context context.SetParameter("console", new SystemConsole()); context.SetParameter("message", "Hello World !"); context.SetParameter("number", 1); // Script string script = @" var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + j')'); number += i; "; try { // Running the script context.Run(script); } catch (JavascriptException je) { string msg = je.Message; msg += "\r\nLine: " + je.Line; msg += "\r\nColum: " + je.StartColumn + " - " + je.EndColumn; msg += "\r\n文件:" + je.Source; MessageBox.Show(msg); } // Getting a parameter Console.WriteLine("number: " + context.GetParameter("number")); } }
public static bool RunException(JavascriptContext iContext, string iCode, int iNumberTest, string expected_exception_message, out string failure) { try { iContext.SetParameter("myCurrentTest", iNumberTest); iContext.Run(iCode); } catch (Exception ex) { if (ex.Message != expected_exception_message) { failure = String.Format("Expected '{0}' exception, but got {1}: {2}", expected_exception_message, ex.GetType().Name, ex.Message); return false; } Console.ForegroundColor = ConsoleColor.Green; Console.Write("SUCCESS"); Console.ResetColor(); failure = null; return true; } failure = String.Format("Exception '{0}' not generated", expected_exception_message); return false; }
/// <summary>We have had a recurring AccessViolationException in CompileScript() -> NewFromTwoByte() /// This is an attempt to reproduce.</summary> static void TaskWithAReasonableAmountOfCompilation() { using (JavascriptContext context = new JavascriptContext()) { int i = (int)context.Run(@" function* fibonacci() { var a = 0; var b = 1; while (true) { yield a; a = b; b = a + b; } } // Instantiates the fibonacci generator fib = fibonacci(); // gets first 10 numbers from the Fibonacci generator starting from 0 var seq = []; for (let i = 0; i < 10; i++) { seq.push(fib.next().value); } var i = 0; for (i = 0; i < 1000; i ++) i ++; i;"); } }
static void Main(string[] args) { using (JavascriptContext context = new JavascriptContext()) { #region "SetParameter" context.SetParameter("console", new SystemConsole()); context.SetParameter("file", new SystemFile()); context.SetParameter("directory", new SystemDirectory()); context.SetParameter("stream", new SystemStream()); #endregion try { StreamReader sr = new StreamReader("startup.js"); string apps = sr.ReadToEnd(); sr.Close(); context.Run(apps); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Tap enter to continue ..."); Console.Read(); } } }
public void bteex_dys(Memoria memoria, string tag) { _memoria = memoria; try { int[] dx = DateCheck(_memoria.xd); int[] dy = DateCheck(_memoria.yd); try { DateTime datax = new DateTime(dx[2], dx[1], dx[0]); DateTime datay = new DateTime(dy[2], dy[1], dy[0]); } catch (Exception) { throw; } JavascriptContext context = new JavascriptContext(); context.SetParameter("dx", dx[0]); context.SetParameter("mx", dx[1]); context.SetParameter("yx", dx[2]); context.SetParameter("dy", dy[0]); context.SetParameter("my", dy[1]); context.SetParameter("yy", dy[2]); context.Run(JavaScripts.DYS); _memoria.xs = context.GetParameter("xx1").ToString(); _memoria.ys = context.GetParameter("yy1").ToString(); SetResultado(); } catch (Exception) { _memoria.Error = 8; SetResultado(false); } }
public bool Validate(IDictionary <string, object> variables, string key) { try { using (var context = new JavascriptContext()) { // set the argument context.SetParameter(ArgumentVariable, variables[key]); // set useful variables foreach (var element in variables) { context.SetParameter(element.Key, element.Value.ToString()); } // run the rule with the custom javascript context.Run(Source); // return the value if it can be found // if garbled, return false var result = context.GetParameter(ResultVariable); return(result != null && (bool)result); } } catch (Exception) { return(false); } }
/// <summary> /// 刷新 淘宝h5 SDK 的cookie /// </summary> public void RefreshH5Api_Cookies() { try { // 生成时间戳 string timestamp = JavascriptContext.getUnixTimestamp(); //加载Cookie var ckVisitor = new LazyCookieVistor(); ///淘宝域下 的cookie string etao_appkey = "12574478"; var data = "{\"isSec\":0}";//固定数据 只为刷token var sign_getToken = JavascriptContext.getEtaoJSSDKSign("", timestamp, etao_appkey, data); string h5TokenUrl = string.Format("https://api.m.taobao.com/h5/mtop.user.getusersimple/1.0/?appKey={0}&t={1}&sign={2}&api=mtop.user.getUserSimple&v=1.0&H5Request=true&type=jsonp&dataType=jsonp&callback=mtopjsonp1&data={3}", etao_appkey, timestamp, sign_getToken, data); this.AutoRefeshCookie(h5TokenUrl);//从新刷新页面 获取 服务器颁发的私钥 var cks_taobao = ckVisitor.LoadCookies(TaobaoSiteUrl); var _m_h5_tk_cookie = cks_taobao.FirstOrDefault(x => x.Name == "_m_h5_tk"); if (null == _m_h5_tk_cookie) { throw new Exception("未能成功刷新 淘宝h5 SDK! _m_h5_tk"); } } catch (Exception ex) { Logger.Error(ex); } }
/// <summary> /// Set variables /// </summary> /// <param name="context"></param> /// <param name="data"></param> /// <returns></returns> public static Dictionary <string, object> SetParameter(JavascriptContext context, BotData data) { Dictionary <string, object> @params = new Dictionary <string, object>(); context.SetParameter("console", new SysConsole()); // Add in all the variables data.Variables.All.ForEach(variable => { try { switch (variable.Type) { case CVar.VarType.List: @params.Add(variable.Name, (variable.Value as List <string>).ToArray()); context.SetParameter(variable.Name, (variable.Value as List <string>).ToArray()); break; default: @params.Add(variable.Name, variable.Value.ToString()); context.SetParameter(variable.Name, variable.Value.ToString()); break; } } catch { } }); return(@params); }
static void RunAndCallbackIntoCsharp(Action run_in_javascript_thread) { using (JavascriptContext context = new JavascriptContext()) { context.SetParameter("csharp_code", run_in_javascript_thread); context.Run("csharp_code();"); } }
static void Main(string[] args) { JavascriptContext.SetFatalErrorHandler(FatalErrorHandler); using (JavascriptContext _context = new JavascriptContext()) { int[] ints = new[] { 1, 2, 3 }; _context.SetParameter("bozo", new Bozo(ints)); try { //_context.Run("a=[]; while(true) a.push(0)"); //_context.Run("function f() { f(); } f()"); while (true) { Console.Write("> "); var input = Console.ReadLine(); if (input == "quit") { break; } var result = _context.Run(input); Console.WriteLine("Result is: `{0}`", result); } } catch (Exception ex) { string s = (string)ex.Data["V8StackTrace"]; Console.WriteLine(s); } //Console.WriteLine(ints[1]); } Console.WriteLine("Press any key to end"); Console.ReadKey(); }
private string CreateRSA(string id, string password, List <string> keys) { using (JavascriptContext context = new JavascriptContext()) { // set parameters context.SetParameter("vvv_id", id); context.SetParameter("vvv_pw", password); for (int i = 0; i < 4; i++) { context.SetParameter("vvv_" + i, keys[i]); } context.SetParameter("vvv_Resu", string.Empty); // make script string script = NaverCafeEditor.Properties.Resources.RSAJS; script += "\n\nvvv_Resu = createRsaKey(vvv_id,vvv_pw,vvv_0,vvv_1,vvv_2,vvv_3);"; // run try { context.Run(script); } catch (JavascriptException) { } // return rsa return(context.GetParameter("vvv_Resu") as string); } }
/// <summary> /// 执行JavaScript脚本,该脚本同源SPF脚本格式,在后续只兼容执行,不再添加新脚本 /// </summary> /// <param name="content">脚本内容(替换了$source之后的内容)</param> /// <param name="asyn">消息通知</param> /// <param name="argrument">传入main函数的参数,JavaScript脚本应该为空</param> /// <param name="paramValues">其它需要设置到脚本的动态参数</param> /// <param name="isThrowExeception">如果执行出现错误,是否抛出异常</param> /// <returns></returns> public object Execute(string content, IAsyncTaskProgress asyn, object[] argrument = null, Dictionary <string, object> paramValues = null, bool isThrowExeception = true) { try { using (JavascriptContext context = new JavascriptContext()) { context.SetParameter("XLY", SingleWrapperHelper <XLYEngine> .Instance); var ac = new Action <object>(s => { SingleWrapperHelper <XLYEngine> .Instance.Debug.Write(s); }); context.SetParameter("log", ac); if (paramValues != null) { foreach (var pk in paramValues) { context.SetParameter(pk.Key, pk.Value); } } //所有脚本均从main函数开始执行。 //content += string.Format(@" // var ___result = main({0}); // ___result; //", argrument); var obj = context.Run(content); return(obj); } } catch (Exception ex) { if (isThrowExeception) { throw ex; } return(null); } }
public static Dictionary <string, object> ConvertToLatLng(string x, string y, string pathToJS) { System.Collections.Generic.Dictionary <string, object> anewpointObj = new Dictionary <string, object>(); // Initialize a context using (JavascriptContext context = new JavascriptContext()) { using (var streamReader = new StreamReader(new Page().Server.MapPath(pathToJS + "proj4js-compressed.js"))) { context.Run(streamReader.ReadToEnd() + ScriptFileSeparator); } // Script string script = @" function ConvertToLatLng(x, y) { Proj4js.defs[""EPSG:32161""] = ""+proj=lcc +lat_1=18.43333333333333 +lat_2=18.03333333333333 +lat_0=17.83333333333333 +lon_0=-66.43333333333334 +x_0=200000 +y_0=200000 +ellps=GRS80 +datum=NAD83 +units=m +no_defs""; Proj4js.defs[""EPSG:4326""] = ""+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs""; var source = new Proj4js.Proj('EPSG:32161'); var dest = new Proj4js.Proj('EPSG:4326'); var anewpoint = new Proj4js.Point(x, y); Proj4js.transform(source, dest, anewpoint); return anewpoint; } var anewpoint = ConvertToLatLng(parseFloat('" + x + "'),parseFloat('" + y + "')); "; // Running the script context.Run(script); // Getting a parameter anewpointObj = (System.Collections.Generic.Dictionary <string, object>)context.GetParameter("anewpoint"); } return(anewpointObj); }
public void OnContentLoaded(Models.CombinatorResource resource) { if (Path.GetExtension(resource.AbsoluteUrl.ToString()).ToLowerInvariant() != ".ts") return; // Code taken from https://github.com/giggio/TypeScriptCompiler using (var context = new JavascriptContext()) { context.SetParameter("jsCode", resource.Content); using (var stream = _virtualPathProvider.OpenFile("~/Modules/Piedone.Combinator.TypeScript/typescript.js")) { context.Run(new StreamReader(stream).ReadToEnd()); } using (var stream = _virtualPathProvider.OpenFile("~/Modules/Piedone.Combinator.TypeScript/compiler.js")) { context.Run(new StreamReader(stream).ReadToEnd()); } var tsCode = (string)context.GetParameter("tsCode"); var error = (string)context.GetParameter("error"); if (!String.IsNullOrWhiteSpace(error)) { throw new ApplicationException("Preprocessing of the TypeScript resource " + resource.AbsoluteUrl + " failed. Error: " + error); } resource.Content = tsCode.Trim(); } }
static void Main(string[] args) { // Initialize a context using (JavascriptContext context = new JavascriptContext()) { try { // load shim context.SetParameter("SHIM", new Shim(context, args)); context.RunEmbeddedScript("rn.require.shim.js"); // run r.js context.RunEmbeddedScript("rn.require.r.js"); }catch(JavascriptException e){ Console.WriteLine("JS Error ({0}): {1}", e.Line, e.Message); } } Console.WriteLine("Any key to quit"); Console.ReadKey(); }
public static string RunExceptionTests(string js_dir) { // Initialization StreamReader fileReader = new StreamReader(Path.Combine(js_dir, "ExceptionTests.js")); String code = fileReader.ReadToEnd(); using (JavascriptContext context = new JavascriptContext()) { // Initialize context.SetParameter("JavascriptTest", new JavascriptTest()); context.SetParameter("myObject", new JavascriptTest()); context.SetParameter("myObjectNoIndexer", new JavascriptTestNoIndexer()); context.SetParameter("objectRejectUnknownProperties", new Object(), SetParameterOptions.RejectUnknownProperties); // Run the Exceptions's tests string failure; // This is an unhelpful error, which I think occurs because the // indexed property types are not matching. if (!ExceptionTests.RunException(context, code, 1, "Method 'Noesis.Javascript.Tests.JavascriptTest.Item' not found.", out failure)) return failure; if (!ExceptionTests.RunException(context, code, 2, "Property doesn't exist", out failure)) return failure; if (!ExceptionTests.RunException(context, code, 3, "Test C# exception", out failure)) return failure; if (!ExceptionTests.RunException(context, code, 4, "Indexer doesn't exist", out failure)) return failure; if (!ExceptionTests.RunException(context, code, 5, "Unknown member: NotExist", out failure)) return failure; if (!ExceptionTests.RunException(context, code, 6, "Unknown member: NotExist", out failure)) return failure; } return null; }
public static bool RunException(JavascriptContext iContext, string iCode, int iNumberTest, string expected_exception_message, out string failure) { try { iContext.SetParameter("myCurrentTest", iNumberTest); iContext.Run(iCode); } catch (Exception ex) { if (ex.Message != expected_exception_message) { failure = String.Format("Expected '{0}' exception, but got {1}: {2}", expected_exception_message, ex.GetType().Name, ex.Message); return(false); } Console.ForegroundColor = ConsoleColor.Green; Console.Write("SUCCESS"); Console.ResetColor(); failure = null; return(true); } failure = String.Format("Exception '{0}' not generated", expected_exception_message); return(false); }
public void DisposingAFunction() { using (var context = new JavascriptContext()) { var function = context.Run("() => { throw new Error('test'); }") as JavascriptFunction; function.Dispose(); } }
public string encrypt(string dKey, string data, string iv, string adata) { JavascriptContext context = new JavascriptContext(); context.SetParameter("derivedk", dKey); context.SetParameter("data", data); context.SetParameter("iv", iv); context.SetParameter("adata", adata); string js = string.Concat(jssjcl, "var c = new sjcl.cipher.aes(sjcl.codec.hex.toBits(derivedk));", "var ct = sjcl.mode.ccm.encrypt(c, sjcl.codec.utf8String.toBits(data), sjcl.codec.hex.toBits(iv), sjcl.codec.hex.toBits(adata));", "ct = sjcl.codec.hex.fromBits(ct);"); context.Run(js); string response = context.GetParameter("ct") as string; context.TerminateExecution(); context.Dispose(); context = null; js = null; return(response); }
private string GetTokenFromHtml(string htmlContent) { //Find token code var match = TOKEN_REGEX.Match(htmlContent); if (match == null || !match.Success) { throw new Exception("Cannot get google translate token"); } //Get javascript get generate token code var getTokenFunctionJs = match.Value; //Run javascript to get raw token var jsContext = new JavascriptContext(); jsContext.Run(getTokenFunctionJs); var tkk = jsContext.GetParameter("TKK") as string; //Attach js funtion AttachTkk(jsContext, tkk); AttachParseTkk(jsContext); //Get token var token = jsContext.Run(@"sM(text)") }
public void Execute(IEnumerable<Script> scripts) { using (var context = new JavascriptContext()) { try { context.SetParameter("console", new StandardOutputConsole()); context.SetParameter("__v8ScriptLoader", new ScriptIncluder(context, _scriptLoader)); foreach (var script in scripts) { context.Run(script.Source, script.Name); } } catch (JavascriptException ex) { object sourceLine = null; if (ex.Data.Contains("V8SourceLine")) sourceLine = ex.Data["V8SourceLine"]; sourceLine = sourceLine ?? "<no source available>"; object stackTrace = null; if (ex.Data.Contains("V8StackTrace")) stackTrace = ex.Data["V8StackTrace"]; stackTrace = stackTrace ?? "<no stack trace available>"; throw new ScriptException(ex.Message, sourceLine.ToString().Trim(), stackTrace.ToString().Trim()); } } }
public void btchs_date(Memoria memoria, string tag) { _memoria = memoria; try { int[] dy = DateCheck(_memoria.yd); try { DateTime datay = new DateTime(dy[2], dy[1], dy[0]); } catch (Exception) { throw; } JavascriptContext context = new JavascriptContext(); context.SetParameter("day", dy[0]); context.SetParameter("month", dy[1]); context.SetParameter("year", dy[2]); context.SetParameter("x", _memoria.xd); context.SetParameter("dmy", _memoria.DMY); context.Run(JavaScripts.DATE); PilhaUp(); _memoria.xs = context.GetParameter("xx1").ToString(); SetResultado(); } catch (Exception) { _memoria.Error = 8; SetResultado(false); } }
private Engine CreateJsEngine(BotData data) { var context = new JavascriptContext(); var engine = new Engine(context, SetParameter(context, data)); return(engine); }
public static string RunAccessorsInterceptorsTests(string js_dir) { using (JavascriptContext context = new JavascriptContext()) { // Initialization StreamReader fileReader = new StreamReader(Path.Combine(js_dir, "AccessorsInterceptorsTests.js")); String code = fileReader.ReadToEnd(); // Initialize context.SetParameter("JavascriptTest", new JavascriptTest()); /** * Test #1: Accessing an element in a .NET Array * Test #4: Setting by index an value in a .NET Array * */ int[] myArray = new int[] { 151515, 666, 2555, 888, 99 }; context.SetParameter("myArray", myArray); /** * Test #2: Accessing by index an property in a .NET Object, * Test #3: Accessing by name an property in a .NET Object * Test #5: Setting by index an value in a .NET Object * Test #6: Setting by name an property in a .NET Object */ context.SetParameter("myObject", new JavascriptTest()); // Run context context.Run(code); } return null; }
/// <summary> /// /// </summary> /// <param name="strCalculateExpression"></param> /// <returns></returns> public object AdvancedCalcV8(string strCalculateExpression) { if (!string.IsNullOrEmpty(strCalculateExpression)) { if (strCalculateExpression.Trim().IndexOf("无") >= 0 || strCalculateExpression.Trim().IndexOf("wu") >= 0) { return(false); } } object retValue = null; try { return(new System.Data.DataTable().Compute(strCalculateExpression, null)); } catch { using (JavascriptContext ctx = new JavascriptContext()) { try { retValue = ctx.Run(strCalculateExpression); } catch (Exception ex) { return(CheckBoolCalculate(strCalculateExpression, ex)); } } } return(retValue); }
public MainWindow() { InitializeComponent(); double[] InputStream = new double[] { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 }; double[] OutputStream = new double[16]; string[] scriptRegions = LoadScript(@"Y:\Documents\Sontia\DevelopementProjects\Ford\Measurement Tool\script.js"); string script; // Initialize a context using (JavascriptContext context = new JavascriptContext()) { // Setting external parameters for the context context.SetParameter("console", new SystemConsole()); context.SetParameter("message", "Hello World !"); context.SetParameter("number", 1); context.SetParameter("InputStream", InputStream); context.SetParameter("OutputStream", OutputStream); context.SetParameter("blockSize", 16); // Script script = scriptRegions[0] + scriptRegions[1]; // Running the script context.Run(script); // Script script = scriptRegions[0] + scriptRegions[2]; // Running the script context.Run(script); } }
private JavascriptContext GetLinterContext(Linters linter) { if (_contexts.ContainsKey(linter)) { return(_contexts[linter]); } JavascriptContext context = null; switch (linter) { case Linters.JSLint: context = setupContext("fulljslint.js"); context.SetParameter("linterName", "JSLINT"); break; case Linters.JSLintOld: context = setupContext("old_fulljslint.js"); context.SetParameter("linterName", "JSLINT"); break; case Linters.JSHint: context = setupContext("jshint.js"); context.SetParameter("linterName", "JSHINT"); break; default: throw new Exception("Invalid linter to create context for"); } _contexts.Add(linter, context); return(context); }
public List <JSLintError> Lint(string javascript, JSLintOptions configuration, bool isJavaScript) { if (string.IsNullOrEmpty(javascript)) { throw new ArgumentNullException("javascript"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } lock (_lock) { Linters linterToUse = isJavaScript ? configuration.SelectedLinter : Linters.JSLint; JavascriptContext context = GetLinterContext(linterToUse); LintDataCollector dataCollector = new LintDataCollector(configuration.ErrorOnUnused); // Setting the externals parameters of the context context.SetParameter("dataCollector", dataCollector); context.SetParameter("javascript", javascript); context.SetParameter("options", configuration.ToJsOptionVar(linterToUse)); // Running the script context.Run("lintRunner(linterName, dataCollector, javascript, options);"); return(dataCollector.Errors); } }
/* Method reverse engineered/adapted from the script emitted at /modemstatus_modemutilization.html from the device */ private void parseScriptData(string scriptData) { // We don't want to call this because it will cause a reference error scriptData = scriptData.Replace("print_utilize_log();", String.Empty); if (!String.IsNullOrEmpty(scriptData)) { JavascriptContext jsContext = new JavascriptContext(); jsContext.Run(scriptData); total_mem = int.Parse(jsContext.GetParameter("total_mem").ToString()); mem_usage = int.Parse(jsContext.GetParameter("total_mem").ToString()); max_session_num = int.Parse(jsContext.GetParameter("max_session_num").ToString()); tcp_session = int.Parse(jsContext.GetParameter("tcp_session").ToString()); udp_session = int.Parse(jsContext.GetParameter("udp_session").ToString()); total_sessions = int.Parse(jsContext.GetParameter("total_sessions").ToString()); if (jsContext.GetParameter("modem_utlize_log") != null && !String.IsNullOrEmpty(jsContext.GetParameter("modem_utlize_log").ToString())) { string[] client_info = jsContext.GetParameter("modem_utlize_log").ToString().Split('|'); foreach (string s in client_info) { string[] clientDetail = s.Split('/'); deviceSessionLog.Add(new DeviceSessionInfo() { DeviceName = clientDetail[0], IPAddress = clientDetail[1], SessionCount = int.Parse(clientDetail[2]) }); } } } }
public bool Evaluate(string conditionScript, IWorkflowRuntime runtime) { if (conditionScript == null) { throw new ArgumentNullException("conditionScript"); } if (runtime == null) { throw new ArgumentNullException("runtime"); } using (var scriptContext = new JavascriptContext()) { scriptContext.SetParameter("input", runtime.Input); foreach (var providerRuntimeResult in runtime.ProviderResults) { if (providerRuntimeResult.ProviderStatus == EWorkflowProviderRuntimeStatus.Success) { scriptContext.SetParameter(providerRuntimeResult.ProviderName, providerRuntimeResult.Result); } } conditionScript = "var result = (function() {" + conditionScript + "})()"; scriptContext.Run(conditionScript); return(Convert.ToBoolean(scriptContext.GetParameter("result"), CultureInfo.InvariantCulture)); } }
public static string RunAccessorsInterceptorsTests(string js_dir) { using (JavascriptContext context = new JavascriptContext()) { // Initialization StreamReader fileReader = new StreamReader(Path.Combine(js_dir, "AccessorsInterceptorsTests.js")); String code = fileReader.ReadToEnd(); // Initialize context.SetParameter("JavascriptTest", new JavascriptTest()); /** * Test #1: Accessing an element in a .NET Array * Test #4: Setting by index an value in a .NET Array * */ int[] myArray = new int[] { 151515, 666, 2555, 888, 99 }; context.SetParameter("myArray", myArray); /** * Test #2: Accessing by index an property in a .NET Object, * Test #3: Accessing by name an property in a .NET Object * Test #5: Setting by index an value in a .NET Object * Test #6: Setting by name an property in a .NET Object */ context.SetParameter("myObject", new JavascriptTest()); // Run context context.Run(code); } return(null); }
void Init() { try { context = new JavascriptContext(); host = new LanguageServiceShimHost(); context.SetParameter("host", host); host.AddFile("lib.d.ts", File.ReadAllText("lib.d.ts")); string source = File.ReadAllText("typescriptServices.js"); context.Run(source); source = File.ReadAllText("test.ts"); scriptTextBox.Text = source; string fileName = "test.ts"; host.AddFile(fileName, source); host.FileName = fileName; source = File.ReadAllText("Main.js"); context.Run(source); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
/// <summary> /// Executes the script passed in against the DOM passed /// Informed bythe function show_dsl_status() /// which is emitted by the WAN Status URL of the router /// </summary> /// <param name="dom"></param> /// <param name="scriptData"></param> private void parseScriptData(HtmlDocument dom, string scriptData) { JavascriptContext jsContext = new JavascriptContext(); jsContext.SetParameter("document", dom); jsContext.Run(scriptData); string dslstatus = jsContext.GetParameter("dslstatus").ToString(); string[] dslsts_temp = dslstatus.Split('|'); speed_d = int.Parse(dslsts_temp[2]); speed_d = int.Parse(dslsts_temp[3]); retrains_time = int.Parse(dslsts_temp[7]); retrains_num = int.Parse(dslsts_temp[6]); Near_endCRC = int.Parse(dslsts_temp[8].Split('/')[0]); Far_endCRC = int.Parse(dslsts_temp[9].Split('/')[0]); Near_endCRC_cnt = int.Parse(dslsts_temp[10].Split('/')[0]); Far_endCRC_cnt = int.Parse(dslsts_temp[11].Split('/')[0]); Near_endRS = int.Parse(dslsts_temp[12].Split('/')[0]); Far_endRS = int.Parse(dslsts_temp[13].Split('/')[0]); Near_endFEC = int.Parse(dslsts_temp[14].Split('/')[0]); Far_endFEC = int.Parse(dslsts_temp[15].Split('/')[0]); discard_pkt_up = int.Parse(dslsts_temp[16].Split('/')[0]); discard_pkt_down = int.Parse(dslsts_temp[16].Split('/')[1]); up_power = int.Parse(dslsts_temp[17].Split('/')[0]); down_power = int.Parse(dslsts_temp[17].Split('/')[1]); snr_margin = int.Parse(dslsts_temp[4].Split('/')[0]); snr_margin_u = int.Parse(dslsts_temp[4].Split('/')[1]); attenuation = int.Parse(dslsts_temp[5].Split('/')[0]); attenuation_u = int.Parse(dslsts_temp[5].Split('/')[1]); }
private void CreateContext() { FreeContext(); m_Context = new JavascriptContext(); m_Elements = new ExternalElementsHost(this, m_Context); }
/// <summary> /// Retrieves the CLR representation, consisting of a dictionary of strings to objects, /// of a JSON string. /// </summary> /// <param name="o">JSON representation, as string</param> /// <returns>CLR object, consisting of a dictionary /// of strings (attributes) to objects (values).</returns> public static object DeserializeJson(string jsonString) { JavascriptContext context = null; try { if (string.IsNullOrEmpty(jsonString)) return null; context = new JavascriptContext(); context.SetParameter("arg1", jsonString); context.SetParameter("obj", null); context.Run(@" obj = JSON.parse(arg1, null); "); return context.GetParameter("obj"); } catch (AccessViolationException) { throw new Exception("Access Violation Exception. Probably you should restart the app ..."); } catch (Exception ex) { throw new Exception("Error in DeserializeJson.", ex); } finally { if (context != null) { context.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); } } }
static void Main(string[] args) { // Initialize a context using (JavascriptContext context = new JavascriptContext()) { // Setting external parameters for the context context.SetParameter("console", new SystemConsole()); context.SetParameter("message", "Hello World !"); context.SetParameter("number", 1); // Script string script = @" var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + ')'); number += i; "; // Running the script context.Run(script); // Getting a parameter Console.WriteLine("number: " + context.GetParameter("number")); } Console.ReadKey(); }
static void Main(string[] args) { JavascriptContext.SetFatalErrorHandler(FatalErrorHandler); using (JavascriptContext _context = new JavascriptContext()) { int[] ints = new[] { 1, 2, 3 }; _context.SetParameter("bozo", new Bozo(ints)); try { //_context.Run("a=[]; while(true) a.push(0)"); //_context.Run("function f() { f(); } f()"); while(true) { Console.Write("> "); var input = Console.ReadLine(); if (input == "quit") break; var result = _context.Run(input); Console.WriteLine("Result is: `{0}`", result); } } catch (Exception ex) { string s = (string)ex.Data["V8StackTrace"]; Console.WriteLine(s); } //Console.WriteLine(ints[1]); } Console.WriteLine("Press any key to end"); Console.ReadKey(); }
static void Main(string[] args) { string path = Environment.CurrentDirectory + "\\test.js"; string js = getJavascriptFromFile(path); using (JavascriptContext context = new JavascriptContext()) { // Setting external parameters for the context context.SetParameter("console", new SystemConsole()); context.SetParameter("p1", 10); context.SetParameter("p2", 11); context.SetParameter("runResult", 0); string script = js + @" runResult = add(p1, p2); console.Print(runResult); "; context.Run(script); Console.WriteLine("run result: " + context.GetParameter("runResult")); Console.ReadKey(); } }
public SystemConsole(JavascriptContext context) { Context = new JContext(context); string input; while((input = GetInput()) != "") WriteResult(input); }
public JavaScriptScript(String code) { context = new JavascriptContext(); this["createObject"] = new Func<String, Dictionary<String, Object>, Object>(createObject); this["createArray"] = new Func<String, int, Object>(createArray); this["getStaticProperty"] = new Func<String, String, Object>(getStaticProperty); Code = code; }
private static JavascriptContext setupContext(string jslintFilename) { JavascriptContext context = new JavascriptContext(); string JSLint = Utility.ReadResourceFile("JS." + jslintFilename); JSLint += Utility.ReadResourceFile("JS.LintRunner.js"); context.Run(JSLint); return context; }
protected virtual void Dispose(bool disposing) { if (disposing) { // Managed, disposable resources that should be released during dispose only. var eng = _engine; _engine = null; if (eng != null) eng.Dispose(); } // Resources that may be released during dispose or finalize. }
internal JavascriptPlugin(string name, string source) { this.Name = name; Runtime = new JavascriptContext (); Runtime.SetParameter("Console", API.Console.Instance); Runtime.SetParameter("Player", NINSS.API.Player.Instance); Runtime.SetParameter("Server", NINSS.API.Server.Instance); Runtime.SetParameter("Config", new NINSS.API.Config (name)); Run(source); }
static void RunInstance() { using (JavascriptContext context = new JavascriptContext()) { int i = (int)context.Run(@" var started = new Date(); var i = 0; while (new Date().getTime() - started.getTime() < 1000) i ++; i;"); } }
public void SimpleSumWithParam() { using (var context = new JavascriptContext()) { context.SetParameter("a", 1); context.SetParameter("b", 2); const string script = @"var sum = a + b;"; context.Run(script); var result = (int)context.GetParameter("sum"); result.Should().Be(3); } }
public void ReturnHello() { using (var context = new JavascriptContext()) { const string script = @"var str = 'hello';"; context.Run(script); var result = context.GetParameter("str"); result.Should().Be("hello"); } }
static void Main(string[] args) { /* context.SetParameter("console", new SystemConsole()); context.Run(System.IO.File.ReadAllText("handlebars.js\\handlebars-1.0.0.beta.6.js")); context.Run("var source = '<div class=\"entry\"><h1>{{title}}</h1><div class=\"body\">{{{body}}}</div></div>';"); context.Run("var template = Handlebars.compile(source);"); int count = 1000; var sw = System.Diagnostics.Stopwatch.StartNew(); Parallel.For(0, count, (i) => { context.Run("console.Print(template({title: \"My New Post\", body: \"" + i + "\"}));"); }); sw.Stop(); Console.WriteLine("{0} tps", count / sw.Elapsed.TotalSeconds); */ // Initialize the context using (JavascriptContext context = new JavascriptContext()) { // Setting the externals parameters of the context context.SetParameter("console", new SystemConsole()); context.SetParameter("message", "Hello World !"); context.SetParameter("number", 1); var a = context.Run("'abc';"); context.SetParameter("output", "''"); context.Run("output = 'test';"); var o = context.GetParameter("output"); // Running the script var _assembly = Assembly.GetExecutingAssembly(); using (var _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("handlebars.cs.handlebars.js.handlebars-1.0.0.beta.6.js"))) { context.Run(_textStreamReader.ReadToEnd()); } context.Run("var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + ')'); number += i;"); context.Run("var source = '<div class=\"entry\"><h1>{{title}}</h1><div class=\"body\">{{{body}}}</div></div>';"); context.Run("var template = Handlebars.compile(source);"); context.Run("var context = {title: \"My New Post\", body: \"This is my first post!\"};"); var test = context.Run("console.Print(template(context));"); // Getting a parameter Console.WriteLine("number: " + context.GetParameter("number")); } }
private static void MemoryUsageLoadInstance() { using (JavascriptContext ctx = new JavascriptContext()) { ctx.Run( @" buffer = []; for (var i = 0; i < 100000; i++) { buffer[i] = 'new string'; } "); } }
public dynamic ExecuteExpression(string expression, ScriptScope scope) { try { using (var context = new JavascriptContext()) { foreach (var variable in scope.Variables) { context.SetParameter(variable.Key, variable.Value); } context.SetParameter("Factory", new TypeFactory(scope.Assemblies)); var workContext = _wcaWork.Value.GetContext(); var orchardGlobal = new Dictionary<string, dynamic>(); orchardGlobal["WorkContext"] = workContext; orchardGlobal["OrchardServices"] = workContext.Resolve<IOrchardServices>(); orchardGlobal["Layout"] = new StaticShape(workContext.Layout); var existing = scope.GetVariable("Orchard"); if (existing != null) { if (!(existing is IDictionary<string, object>)) throw new ArgumentException("The Orchard global variable should be an IDictionary<string, dynamic>."); var existingDictionary = existing as IDictionary<string, dynamic>; foreach (var existingItem in existingDictionary) { orchardGlobal[existingItem.Key] = existingItem.Value; } } context.SetParameter("Orchard", orchardGlobal); _eventHandler.BeforeExecution(new BeforeJavaScriptExecutionContext(scope, context)); var output = context.Run(expression); _eventHandler.AfterExecution(new AfterJavaScriptExecutionContext(scope, context)); foreach (var variableName in scope.Variables.Select(kvp => kvp.Key)) { scope.SetVariable(variableName, context.GetParameter(variableName)); } return output; } } catch (Exception ex) { if (ex.IsFatal()) throw; throw new ScriptRuntimeException("The JavaScript script could not be executed.", ex); } }
static void BasicTest() { JavascriptContext ctx = new JavascriptContext(); ctx.SetParameter("XB", "begin: "); ctx.RegisterMethod("XB += 'included_test ';", "test"); ctx.RegisterMethod("XB += 'included_thr '; var a = sam + 4;", "thr"); try { Console.WriteLine("Parameter XB={0}", ctx.GetParameter("XB")); ctx.CallMethodFromDict("test"); Console.WriteLine("After test, parameter XB={0}", ctx.GetParameter("XB")); ctx.CallMethodFromDict("thr"); Console.WriteLine("After thr, parameter XB={0}", ctx.GetParameter("XB")); } catch (JavascriptException e) { string err = (string)e.Data["V8StackTrace"]; Console.WriteLine("Called thr, threw error: {0} at code {1} at line {2}", err, e.Source, e.Line); Console.WriteLine("**********"); var stacktrace = (string)e.Data["V8StackTrace"]; Console.WriteLine(FancifyStackTrace("XB += 'included_thr '; var a = sam + 4;", stacktrace)); Console.WriteLine("**********"); Console.WriteLine("After throwing, parameter XB={0}", ctx.GetParameter("XB")); } //ctx.RegisterMethod("function test() { return \"Success!!\"; };", "test"); //ctx.RegisterMethod("function add(a,b) { return a + b; };", "add"); //ctx.RegisterMethod("function und() { return undefined; };", "und"); //ctx.RegisterMethod("function thr(i) { i = i || 0;\n if (i > 3)\n { var a = sam + 5; return a; };\n return thr(i+1);\n}", "thr"); //var result = ctx.CallMethodFromDict("test");//, new object[] { }); //Console.WriteLine("Called test, got result: "); //Console.WriteLine(result); //Console.WriteLine("Ran add(2,3)"); //result = ctx.CallMethod("add", new object[] { 2, 3 }); //Console.WriteLine("Called add, got result: "); //Console.WriteLine(result); //try //{ // Console.WriteLine("Ran thr"); // result = ctx.CallMethodFromDict("thr");//, new object[] { }); // Console.WriteLine("Called thr, got result: "); // Console.WriteLine(result); //} //catch (JavascriptException e) //{ // string err = (string)e.Data["V8StackTrace"]; // Console.WriteLine("Called thr, threw error: {0} at code {1} at line {2}", err, e.Source, e.Line); // var stacktrace = (string)e.Data["V8StackTrace"]; // Console.WriteLine(FancifyStackTrace("function thr(i) { i = i || 0;\n if (i > 3)\n { var a = sam + 5; return a; };\n return thr(i+1);\n}", stacktrace)); //} }
static void RunInstance() { using (JavascriptContext context = new JavascriptContext()) { context.SetParameter("finishTime", finishTime); int i = (int)context.Run(@" var started = new Date(); var i = 0; while (new Date().getTime() - started.getTime() < 1000) i ++; i;"); Console.WriteLine(String.Format("Counted to {0}", i)); } }
static HandleBars() { _context = new JavascriptContext(); var _assembly = Assembly.GetExecutingAssembly(); using (var _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("handlebars.cs.handlebars.js.handlebars-1.0.0.beta.6.js"))) _context.Run(_textStreamReader.ReadToEnd()); // ensure there is a 'templates' property _context.Run("Handlebars.templates = Handlebars.templates || {};"); // setup an object which contains the compiled templates as properties. // _context.Run("var templates = {};"); _templates = new Dictionary<string, string>(); }
static void Main(string[] args) { using (JavascriptContext _context = new JavascriptContext()) { int[] ints = new[] { 1, 2, 3 }; _context.SetParameter("bozo", new Bozo(ints)); try { object res = _context.Run("bozo[7];"); } catch (Exception ex) { string s = (string)ex.Data["V8StackTrace"]; Console.WriteLine(s); } //Console.WriteLine(ints[1]); } }
public string DecryptLink(string key, string cipher) { using (var context = new JavascriptContext()) { // context.SetParameter("Console", new SystemConsole()); context.SetParameter("key", key); context.SetParameter("cipher", cipher); // Running the script context.Run(File.ReadAllText("Hindi4ULink.js")); // Getting a parameter return context.GetParameter("decryptedText").ToString(); } }
static void Main(string[] args) { // Initialize the context using (JavascriptContext context = new JavascriptContext()) { // Setting the externals parameters of the context context.SetParameter("console", new SystemConsole()); context.SetParameter("message", "Hello World !"); context.SetParameter("number", 1); // Running the script context.Run("var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + ')'); number += i;"); // Getting a parameter Console.WriteLine("number: " + context.GetParameter("number")); } }
static void Main(string[] args) { JavascriptContext.SetFatalErrorHandler(FatalErrorHandler); using (JavascriptContext _context = new JavascriptContext()) { int[] ints = new[] { 1, 2, 3 }; _context.SetParameter("bozo", new Bozo(ints)); try { //_context.Run("a=[]; while(true) a.push(0)"); _context.Run("function f() { f(); } f()"); } catch (Exception ex) { string s = (string)ex.Data["V8StackTrace"]; Console.WriteLine(s); } //Console.WriteLine(ints[1]); } }
static void Main(string[] args) { using (JavascriptContext _context = new JavascriptContext()) { _context.FatalError += _context_FatalError; //int[] ints = new[] { 1, 2, 3 }; //_context.SetParameter("bozo", new Bozo(ints)); try { object res = _context.Run( //"function f() { f(); }; f();" "a = []; while(true) a.push(1);" ); } catch (Exception ex) { string s = (string)ex.Data["V8StackTrace"]; Console.WriteLine(s); } //Console.WriteLine(ints[1]); } }
public static string Responsejs(string script, string key) { using (JavascriptContext context = new JavascriptContext()) { try { context.Run(script); var res = context.GetParameter(key); return res.ToString(); } catch (Exception ex) { return ex.Message; } } }