public void CheckinScript(ScriptedPatchRequest request, Engine context) { CachedResult value; if (cacheDic.TryGetValue(request, out value)) { if (value.Queue.Count > 20) return; value.Queue.Enqueue(context); return; } cacheDic.AddOrUpdate(request, patchRequest => { var queue = new ConcurrentQueue<Engine>(); queue.Enqueue(context); return new CachedResult { Queue = queue, Timestamp = SystemTime.UtcNow, Usage = 1 }; }, (patchRequest, result) => { result.Queue.Enqueue(context); return result; }); }
public void Test4() { Jint.Engine engine = new Jint.Engine(); IDocument htmlDocument = new Document(); htmlDocument.HtmlDocument = new AngleSharp.Html.Parser.HtmlParser().ParseDocument(htmlContent); Window.Window window1 = new Window.Window(engine); window1.document = htmlDocument.HtmlDocument; window1.InitializeEngine(); var jquery = System.IO.File.ReadAllText(@"../../../../BrowseSharpPlayground/jquery.js"); //engine.Execute("window.document.readyState = \"Loading\";"); engine.Execute(jquery); engine.Execute("var $ = window.jQuery;"); var script = "$(document).ready(function() {$('#content').text('hello there it worked');})"; //var cleanedScript = new Regex(); Regex regex = new Regex(@"(\$\([^document]*document[^)]*\)[^.]*.ready[^(]*\([^function]*function[^(]*\([^)]*\)[^{]*{)([^a|a]*)(}\))"); engine.Execute(regex.Match(script).Groups[2].Value); //engine.Execute("window.document.readyState = 'complete'"); //engine.Execute("$(document).trigger('ready',window.document)"); //engine.Execute("$(document).trigger('ready')"); Assert.AreEqual("hello there it worked", window1.document.GetElementById("content").TextContent); }
public override void Dispose() { if (_disposedFlag.Set()) { lock (_executionSynchronizer) { if (_debuggerStepCallback != null) { _jsEngine.DebugHandler.Step -= _debuggerStepCallback; _debuggerStepCallback = null; } if (_debuggerBreakCallback != null) { _jsEngine.DebugHandler.Break -= _debuggerBreakCallback; _debuggerBreakCallback = null; } _jsEngine = null; _cancellationConstraint = null; if (_cancellationTokenSource != null) { _cancellationTokenSource.Dispose(); _cancellationTokenSource = null; } } } }
/// <summary> /// Initializes a new instance of the JavaScriptPlugin class /// </summary> /// <param name="filename"></param> /// <param name="engine"></param> /// <param name="watcher"></param> internal JavaScriptPlugin(string filename, Engine engine, FSWatcher watcher) { // Store filename Filename = filename; JavaScriptEngine = engine; this.watcher = watcher; }
public JSEngine(Engine engine) { if (engine == null) throw new ArgumentNullException(nameof(engine)); _engine = engine; }
public PlexBinding(string username, string password) { _username = username; _password = password; this.PlayBack = new PlaybackApiBinding(Plexito.JavaScriptLogic.Scripts.PlaybackApi); _scripts = new Engine(cfg => cfg.AllowClr(typeof(XMLHttpRequest).Assembly)).Execute(Plexito.JavaScriptLogic.Scripts.PlexApi); }
public JavaScriptRunner(IFeedback<LogEntry> log, ICommandProcessor commandProcessor, IEntityContextConnection entityContextConnection) { if (log == null) throw new ArgumentNullException(nameof(log)); if (commandProcessor == null) throw new ArgumentNullException(nameof(commandProcessor)); if (entityContextConnection == null) throw new ArgumentNullException(nameof(entityContextConnection)); Log = log; CommandProcessor = commandProcessor; EntityContextConnection = entityContextConnection; log.Source = "JavaScript Runner"; JintEngine = new Engine(cfg => { cfg.AllowClr(); cfg.AllowDebuggerStatement(JavascriptDebugEnabled); }); //JintEngine.Step += async (s, info) => //{ // await Log.ReportInfoFormatAsync(CancellationToken.None, "{1} {2}", // info.CurrentStatement.Source.Start.Line, // info.CurrentStatement.Source.Code.Replace(Environment.NewLine, "")); //}; }
public void CheckinScript(ScriptedPatchRequest request, Engine context, RavenJObject customFunctions) { CachedResult cacheByCustomFunctions; var patchRequestAndCustomFunctionsTuple = new ScriptedPatchRequestAndCustomFunctionsToken(request, customFunctions); if (cacheDic.TryGetValue(patchRequestAndCustomFunctionsTuple, out cacheByCustomFunctions)) { if (cacheByCustomFunctions.Queue.Count > 20) return; cacheByCustomFunctions.Queue.Enqueue(context); return; } cacheDic.AddOrUpdate(patchRequestAndCustomFunctionsTuple, patchRequest => { var queue = new ConcurrentQueue<Engine>(); return new CachedResult { Queue = queue, Timestamp = SystemTime.UtcNow, Usage = 1 }; }, (patchRequest, result) => { result.Queue.Enqueue(context); return result; }); }
public bool Initialize(UserGameInfo game, GameProfile profile) { this.userGame = game; this.profile = profile; // see if we have any save game to backup gen = game.Game as GenericGameInfo; if (gen == null) { // you f****d up return false; } engine = new Engine(); engine.SetValue("Options", profile.Options); data = new Dictionary<string, string>(); data.Add(NucleusFolderEnum.GameFolder.ToString(), Path.GetDirectoryName(game.ExePath)); if (gen.SaveType == GenericGameSaveType.None) { return true; } string saveFile = ProcessPath(gen.SavePath); GameManager.Instance.BeginBackup(game.Game); GameManager.Instance.BackupFile(game.Game, saveFile); return true; }
public Plugin(DirectoryInfo directory, string name, string code) { Name = name; Code = code; RootDirectory = directory; Timers = new Dictionary<String, TimedEvent>(); Engine = new Engine(cfg => cfg.AllowClr(typeof(UnityEngine.GameObject).Assembly, typeof(uLink.NetworkPlayer).Assembly, typeof(PlayerInventory).Assembly)) .SetValue("Server", Server.GetServer()) .SetValue("DataStore", DataStore.GetInstance()) .SetValue("Util", Util.GetUtil()) .SetValue("World", World.GetWorld()) .SetValue("Lookup", LookUp.GetLookUp()) .SetValue("Plugin", this) .Execute(code); Logger.LogDebug(string.Format("{0} AllowClr for Assemblies: {1} {2} {3}", brktname, typeof(UnityEngine.GameObject).Assembly.GetName().Name, typeof(uLink.NetworkPlayer).Assembly.GetName().Name, typeof(PlayerInventory).Assembly.GetName().Name)); try { Engine.Invoke("On_PluginInit"); } catch { } }
public UnityUGUIContext(RectTransform hostElement, Jint.Engine engine, StringObjectDictionary assets, ReactScript script, bool isDevServer) { Engine = engine; Globals = assets; Script = script; IsDevServer = isDevServer; Parser = new StylesheetParser(true, true, true, true, true); StyleTree = new StyleTree(Parser); Host = new HostComponent(hostElement, this); Host.Tag = "_root"; RootLayoutNode = Host.Layout; InsertStyle(ResourcesHelper.UseragentStylesheet?.text, -1); Host.ResolveStyle(true); MainThreadDispatcher.AddCallOnLateUpdate(() => { if (Scheduled) { RootLayoutNode.CalculateLayout(); Scheduled = false; for (int i = 0; i < ScheduledCallbacks.Count; i++) { ScheduledCallbacks[i]?.Invoke(); } } }); }
public void loop() { string loopscript = File.ReadAllText("scripts/loop.js"); Jint.Engine jsint = new Jint.Engine(); jsint.SetValue("debuglog", new Action<object>(Console.WriteLine)); jsint.Execute(loopscript); }
/// <summary> /// 获取一淘的sign /// </summary> /// <param name="_m_h5_tk"> 第一个参数 是服务器产生的私钥-公钥 _m_h5_tk=8a1c196f9c4cc68b00b8e46858cef6d7_1499930011052; 8a开头_结束</param> /// <param name="timestnap">时间戳 ,通过js生成13位的时间戳</param> /// <param name="appkey">第三个是固定的key ,一淘的是 12574478</param> /// <param name="paraData">需要加密的参数字符串 ,比如:"{\"s\":0,\"n\":40,\"q\":\"植物\",\"needEncode\":false,\"sort\":\"sales_desc\",\"maxPrice\":10000000,\"minPrice\":0,\"serviceList\":\"\",\"navigator\":\"all\",\"urlType\":2}"</param> /// <returns></returns> public static string getEtaoJSSDKSign(string _m_h5_tk, string timestamp, string appkey, string paraData) { //方法1: //先打开etao 点击搜索框 触发热词检索。断网!!!!!在chrome中 即可发现 触发的位置; //点击进去,然后点击 下面的{}进行代码格式化 //联网后,重新触发算法,断点调试进去;找到调用堆栈 u = r([n.cookie.replace(/.*?(?:\b|;)\s*_m_h5_tk=([^;]+).*$|.*/, "$1").split("_")[0], a, t.appKey, e].join("&")); //格式化的js 代码,查看r=function 的开始结束,即可找出算法!!! //从 一淘官方提取的 js 加密sign 方法 在 https://g.alicdn.com/etao/lego2-pc/0.1.0/app/??libs/crox-min.js,libs/pc-mtop-min.js,libs/include-min.js,libs/popupManager-min.js //方法2: //第一步 从js 文件中搜索 api 找到getSearchList:"mtop.etao.fe.search" //第二部 使用IE 在这里尝试打断点,触发事件 也可以尝试断网,让js 报错 逆向找出请求源 // 从index.js 中 监听 renderMain:function(a){var t=this,r=e.Defer(),n=r.promise;i({api:g.getSearchList,v:"1.0",data:t.generateRequestParams(),callback:fun 按钮点击排序时间 // 使用IE 11 F12进行跟踪断点调试 单步 // 最后在 app js ///w=function(t){if(t.api){t=S(t,E.params),t.retry=parseInt(t.retry)||0;var e=c(t.data,!1),a=i(),u=r([n.cookie.replace(/.*?(?:\b|;)\s*_m_h5_tk=([^;]+).*$|.*/,"$1").split("_")[0],a,t.appKey,e].join("&")); o("//" + d + "." + g + "." + h + "." + m + "/h5/" + t.api + "/" + t.v + "/",{ type: "jsonp",api: t.api,v: t.v,appKey: t.appKey,data: e,t: a,sign: u},function(n){ n = n ||{ }; var e = (n.ret ||["UNKNOW::未知错误,请检查网络是否正常后重试"])[0], r = n.data ||{ }; if (/^ SUCCESS /.test(e)) "function" == typeof t.callback&& t.callback(r, null, n); else { e = e.split("::"); var o = e[0], a = e[1]; if (/ SESSION_EXPIRED /.test(o)) a = "未登录淘宝账号"; else if (/^ FAIL_SYS | TOKEN_EXOIRED | TOKEN_EMPTY | BIZ_UNAVAILABLE | NO_NETWORK |^ UNKNOW$/.test(o) && !/^ FAIL_SYS_(SERVICE_NOT_EXIST | API_NOT_FOUNDED | ILLEGAL_ACCESS)$/.test(o) && --t.retry >= 0)return E(t),!1; "function" == typeof t.callback&& t.callback(r,{ code: o,msg: a},n)} })}}, //可以尝试把代码 格式化到 typesctipt 里进行在线代码调试 //单步调试跟踪到签名算法----下面的是格式化后的 string getSignScript = @"var r=function(t){function n(t,n){return t<<n|t>>>32-n}function e(t,n){var e,r,o,a,c;return o=2147483648&t,a=2147483648&n,e=1073741824&t,r=1073741824&n,c=(1073741823&t)+(1073741823&n),e&r?2147483648^c^o^a:e|r?1073741824&c?3221225472^c^o^a:1073741824^c^o^a:c^o^a}function r(t,n,e){return t&n|~t&e}function o(t,n,e){return t&e|n&~e}function a(t,n,e){return t^n^e}function c(t,n,e){return n^(t|~e)}function i(t,o,a,c,i,u,l){return t=e(t,e(e(r(o,a,c),i),l)),e(n(t,u),o)}function u(t,r,a,c,i,u,l){return t=e(t,e(e(o(r,a,c),i),l)),e(n(t,u),r)}function l(t,r,o,c,i,u,l){return t=e(t,e(e(a(r,o,c),i),l)),e(n(t,u),r)}function f(t,r,o,a,i,u,l){return t=e(t,e(e(c(r,o,a),i),l)),e(n(t,u),r)}function s(t){for(var n,e=t.length,r=e+8,o=(r-r%64)/64,a=16*(o+1),c=new Array(a-1),i=0,u=0;u<e;)n=(u-u%4)/4,i=u%4*8,c[n]=c[n]|t.charCodeAt(u)<<i,u++;return n=(u-u%4)/4,i=u%4*8,c[n]=c[n]|128<<i,c[a-2]=e<<3,c[a-1]=e>>>29,c}function p(t){var n,e,r='',o='';for(e=0;e<=3;e++)n=t>>>8*e&255,o='0'+n.toString(16),r+=o.substr(o.length-2,2);return r}function d(t){t=t.replace(/\r\n/g,'\n');for(var n='',e=0;e<t.length;e++){var r=t.charCodeAt(e);r<128?n+=String.fromCharCode(r):r>127&&r<2048?(n+=String.fromCharCode(r>>6|192),n+=String.fromCharCode(63&r|128)):(n+=String.fromCharCode(r>>12|224),n+=String.fromCharCode(r>>6&63|128),n+=String.fromCharCode(63&r|128))}return n}var g,h,m,v,b,y,C,S,w,E=[],_=7,I=12,N=17,j=22,A=5,k=9,O=14,L=20,T=4,U=11,K=16,R=23,F=6,$=10,x=15,D=21;for(t=d(t),E=s(t),y=1732584193,C=4023233417,S=2562383102,w=271733878,g=0;g<E.length;g+=16)h=y,m=C,v=S,b=w,y=i(y,C,S,w,E[g+0],_,3614090360),w=i(w,y,C,S,E[g+1],I,3905402710),S=i(S,w,y,C,E[g+2],N,606105819),C=i(C,S,w,y,E[g+3],j,3250441966),y=i(y,C,S,w,E[g+4],_,4118548399),w=i(w,y,C,S,E[g+5],I,1200080426),S=i(S,w,y,C,E[g+6],N,2821735955),C=i(C,S,w,y,E[g+7],j,4249261313),y=i(y,C,S,w,E[g+8],_,1770035416),w=i(w,y,C,S,E[g+9],I,2336552879),S=i(S,w,y,C,E[g+10],N,4294925233),C=i(C,S,w,y,E[g+11],j,2304563134),y=i(y,C,S,w,E[g+12],_,1804603682),w=i(w,y,C,S,E[g+13],I,4254626195),S=i(S,w,y,C,E[g+14],N,2792965006),C=i(C,S,w,y,E[g+15],j,1236535329),y=u(y,C,S,w,E[g+1],A,4129170786),w=u(w,y,C,S,E[g+6],k,3225465664),S=u(S,w,y,C,E[g+11],O,643717713),C=u(C,S,w,y,E[g+0],L,3921069994),y=u(y,C,S,w,E[g+5],A,3593408605),w=u(w,y,C,S,E[g+10],k,38016083),S=u(S,w,y,C,E[g+15],O,3634488961),C=u(C,S,w,y,E[g+4],L,3889429448),y=u(y,C,S,w,E[g+9],A,568446438),w=u(w,y,C,S,E[g+14],k,3275163606),S=u(S,w,y,C,E[g+3],O,4107603335),C=u(C,S,w,y,E[g+8],L,1163531501),y=u(y,C,S,w,E[g+13],A,2850285829),w=u(w,y,C,S,E[g+2],k,4243563512),S=u(S,w,y,C,E[g+7],O,1735328473),C=u(C,S,w,y,E[g+12],L,2368359562),y=l(y,C,S,w,E[g+5],T,4294588738),w=l(w,y,C,S,E[g+8],U,2272392833),S=l(S,w,y,C,E[g+11],K,1839030562),C=l(C,S,w,y,E[g+14],R,4259657740),y=l(y,C,S,w,E[g+1],T,2763975236),w=l(w,y,C,S,E[g+4],U,1272893353),S=l(S,w,y,C,E[g+7],K,4139469664),C=l(C,S,w,y,E[g+10],R,3200236656),y=l(y,C,S,w,E[g+13],T,681279174),w=l(w,y,C,S,E[g+0],U,3936430074),S=l(S,w,y,C,E[g+3],K,3572445317),C=l(C,S,w,y,E[g+6],R,76029189),y=l(y,C,S,w,E[g+9],T,3654602809),w=l(w,y,C,S,E[g+12],U,3873151461),S=l(S,w,y,C,E[g+15],K,530742520),C=l(C,S,w,y,E[g+2],R,3299628645),y=f(y,C,S,w,E[g+0],F,4096336452),w=f(w,y,C,S,E[g+7],$,1126891415),S=f(S,w,y,C,E[g+14],x,2878612391),C=f(C,S,w,y,E[g+5],D,4237533241),y=f(y,C,S,w,E[g+12],F,1700485571),w=f(w,y,C,S,E[g+3],$,2399980690),S=f(S,w,y,C,E[g+10],x,4293915773),C=f(C,S,w,y,E[g+1],D,2240044497),y=f(y,C,S,w,E[g+8],F,1873313359),w=f(w,y,C,S,E[g+15],$,4264355552),S=f(S,w,y,C,E[g+6],x,2734768916),C=f(C,S,w,y,E[g+13],D,1309151649),y=f(y,C,S,w,E[g+4],F,4149444226),w=f(w,y,C,S,E[g+11],$,3174756917),S=f(S,w,y,C,E[g+2],x,718787259),C=f(C,S,w,y,E[g+9],D,3951481745),y=e(y,h),C=e(C,m),S=e(S,v),w=e(w,b);var Y=p(y)+p(C)+p(S)+p(w);return Y.toLowerCase()}"; var ck = _m_h5_tk.Split('_')[0]; //"8a1c196f9c4cc68b00b8e46858cef6d7"; var t = timestamp; // "1499931938374";////function () { var n = (new Date).getTime(); return n <= t && (n = t + 1), t = n }(); var key = appkey; // "12574478"; var paras = paraData; // "{\"s\":0,\"n\":40,\"q\":\"植物\",\"needEncode\":false,\"sort\":\"sales_desc\",\"maxPrice\":10000000,\"minPrice\":0,\"serviceList\":\"\",\"navigator\":\"all\",\"urlType\":2}"; var paraSring = string.Join("&", ck, t, key, paras); var add = new Jint.Engine() .Execute(getSignScript) .GetValue("r"); var val = add.Invoke(paraSring); return(val.AsString()); }
static void Main(string[] args) { string datePattern = @"([0-2]?[0-9]|3[0-1])/(0?[0-9]|1[0-2])/([0-9][0-9])?[0-9][0-9]|([0-9][0-9])?[0-9][0-9]/(0?[0-9]|1[0-2])/([0-2]?[0-9]|3[0-1])"; string equationInString = "12/12/2018 - 11/11/2017"; MatchCollection dateMatcher = Regex.Matches(equationInString, datePattern); List <DateTime> dateTimeList = new List <DateTime>(); if (dateMatcher.Count > 0) { foreach (Match match in dateMatcher) { Console.WriteLine(match.Value); } } Jint.Engine scriptEngine = new Jint.Engine(); Console.WriteLine("this: " + scriptEngine.Execute("\'this is good\'>= \'what is this\'").GetCompletionValue()); //TestClass.Testing_for_ALL_Node_Lines_and_features_10(); //TestClass.Testing_Whole_Features_Of_ValueConclusionLine_ComparisonLine_and_ExprConclusionLine_9(); //TestClass.Testing_Whole_Features_Of_ValueConclusionLIne_and_ComparisonLine_8(); //TestClass.Tesing_Full_ValueConclusion_Comparison_7(); //TestClass.Testing_ValueConclusionLine_6(); //TestClass.Testing_Inference_For_NotKnownManOpPo_5(); //TestClass.Testing_For_Reading_NotKnownMandatoryPossiblyAndOptionally_4(); //TestClass.WeddingPlanner_Inference_Test_3(); //TestClass.TopoSortingTest_2(); //TestClass.Testing(); }
public override void PutDocument(string documentKey, object data, object meta, Engine engine) { if (forbiddenDocuments.Contains(documentKey)) throw new InvalidOperationException(string.Format("Cannot PUT document '{0}' to prevent infinite indexing loop. Avoid modifying documents that could be indirectly referenced by index.", documentKey)); base.PutDocument(documentKey, data, meta, engine); }
private void ExecuteError(int errcode, string errmessage) { try { System.Diagnostics.Debug.WriteLine("GeoLocation.ExecuteError"); System.Func <Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue> _func = _funcError as System.Func <Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue>; Jint.Native.Function.ScriptFunctionInstance JintScript = _func.Target as Jint.Native.Function.ScriptFunctionInstance; Jint.Engine _JintEngine = JintScript.Engine; JsValue A = new JsValue(1); JsValue[] B = new Jint.Native.JsValue[1]; Jint.Native.Json.JsonParser _jsp = new Jint.Native.Json.JsonParser(_JintEngine); String FormatString = "{{\"code\":{0}, \"message\":\"{1}\"}}"; String Error = String.Format(FormatString, errcode, errmessage); B[0] = _jsp.Parse(Error); _func.Invoke(A, B); } catch (Exception exp) { System.Diagnostics.Debug.WriteLine("Exception" + exp.Message); } }
public JavaScriptEngine(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; _scripterModuleRegistry = serviceProvider.GetRequiredService <IScripterModuleRegistry>(); _engine = new Jint.Engine(GetOptions()); Initialize(); }
/// <summary> /// Constructs an instance of adapter for the Jint JS engine /// </summary> /// <param name="settings">Settings of the Jint JS engine</param> public JintJsEngine(JintSettings settings) { _cancellationTokenSource = new CancellationTokenSource(); _cancellationConstraint = new CustomCancellationConstraint(_cancellationTokenSource.Token); JintSettings jintSettings = settings ?? new JintSettings(); try { _jsEngine = new OriginalEngine(options => { options .AllowDebuggerStatement(jintSettings.AllowDebuggerStatement) .Constraint(_cancellationConstraint) .DebugMode(jintSettings.EnableDebugging) .LimitMemory(jintSettings.MemoryLimit) .LimitRecursion(jintSettings.MaxRecursionDepth) .LocalTimeZone(jintSettings.LocalTimeZone ?? TimeZoneInfo.Local) .MaxStatements(jintSettings.MaxStatements) .Strict(jintSettings.StrictMode) .TimeoutInterval(jintSettings.TimeoutInterval) ; if (jintSettings.RegexTimeoutInterval.HasValue) { options.RegexTimeoutInterval(jintSettings.RegexTimeoutInterval.Value); } options.AddObjectConverter(new UndefinedConverter()); }); } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
private void ExecuteSuccess(Geoposition _pos) { try { System.Diagnostics.Debug.WriteLine("GeoLocation.ExecuteSuccess"); System.Func <Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue> _func = _funcSuccess as System.Func <Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue>; Jint.Native.Function.ScriptFunctionInstance JintScript = _func.Target as Jint.Native.Function.ScriptFunctionInstance; Jint.Engine _JintEngine = JintScript.Engine; JsValue A = new JsValue(1); JsValue[] B = new JsValue[1]; Jint.Native.Json.JsonParser _jsp = new Jint.Native.Json.JsonParser(_JintEngine); String FormatString = "{{\"coords\":{{\"latitude\":{0}, \"longitude\":{1}}}}}"; String Coordinates = String.Format(FormatString, _pos.Coordinate.Latitude, _pos.Coordinate.Longitude); B[0] = _jsp.Parse(Coordinates); _func.Invoke(A, B); } catch (Jint.Runtime.JavaScriptException exc) { System.Diagnostics.Debug.WriteLine("JavaScriptException" + exc.Message + " " + exc.LineNumber); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception" + e.Message); ExecuteError(e.HResult, e.Message); } }
private static void Run(string[] args) { var engine = new Engine(cfg => cfg.AllowClr()) .SetValue("print", new Action<object>(Print)) .SetValue("ac", _acDomain); var filename = args.Length > 0 ? args[0] : ""; if (!String.IsNullOrEmpty(filename)) { if (!File.Exists(filename)) { Console.WriteLine(@"Could not find file: {0}", filename); } var script = File.ReadAllText(filename); var result = engine.GetValue(engine.Execute(script).GetCompletionValue()); return; } Welcome(); var defaultColor = Console.ForegroundColor; while (true) { Console.ForegroundColor = defaultColor; Console.Write(@"anycmd> "); var input = Console.ReadLine(); if (input == "exit") { return; } if (input == "clear") { Console.Clear(); Welcome(); continue; } try { var result = engine.GetValue(engine.Execute(string.Format("print({0})", input)).GetCompletionValue()); if (result.Type != Types.None && result.Type != Types.Null && result.Type != Types.Undefined) { var str = TypeConverter.ToString(engine.Json.Stringify(engine.Json, Arguments.From(result, Undefined.Instance, " "))); Console.WriteLine(@"=> {0}", str); } } catch (JavaScriptException je) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(je.ToString()); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message); } } }
static Engine PrepareEngine(string code) { Engine e = new Engine(f => f.AllowClr(typeof(CDSData).Assembly)); e.SetValue("Log", new Action<Object>(Console.WriteLine)); //change to write data to a node rather than to console later e.Execute("var CDSCommon = importNamespace('CDS.Common');"); e.Execute(code); return e; }
static string GetCryPwd(string pwd) { var engine = new Engine() .Execute(@"function mc(a){ret='';var b='0123456789ABCDEF';if(a==' '.charCodeAt()){ret='+'}else if((a<'0'.charCodeAt()&&a!='-'.charCodeAt()&&a!='.'.charCodeAt())||(a<'A'.charCodeAt()&&a>'9'.charCodeAt())||(a>'Z'.charCodeAt()&&a<'a'.charCodeAt()&&a!='_'.charCodeAt())||(a>'z'.charCodeAt())){ret='%';ret+=b.charAt(a>>4);ret+=b.charAt(a&15)}else{ret=String.fromCharCode(a)};return ret};function m(a){return(((a&1)<<7)|((a&(0x2))<<5)|((a&(0x4))<<3)|((a&(0x8))<<1)|((a&(0x10))>>1)|((a&(0x20))>>3)|((a&(0x40))>>5)|((a&(0x80))>>7))};function md6(a){var b='';var c=0xbb;for(i=0;i<a.length;i++){c=m(a.charCodeAt(i))^(0x35^(i&0xff));var d=c.toString(16);b+=mc(c)};return b}"); var value = engine.Invoke("md6", pwd); return value.ToString(); }
public JavascriptContext(string script, string errorMessageContext) { _engine = new Engine(); _errorMessageContext = errorMessageContext; _initialJavascript = script; Initialize(_initialJavascript); }
private static int Echo(Engine scriptScope, object echoStr) { var response = (ClientHttpResponse) scriptScope.GetValue("response").ToObject(); if (!response.HasFinishedSendingHeaders) response.SendDefaultHeaders(); response.OutputStream.WriteLine(echoStr.ToString()); return 0; }
public void Construct(params string[] JavascriptSourceFiles) { JintEngine = new Jint.Engine(); foreach (string JavascriptSourceFile in JavascriptSourceFiles) { JintEngine.Execute(System.IO.File.ReadAllText(JavascriptSourceFile)); } }
/// <summary> /// 通过js脚本执行获取时间戳 /// </summary> /// <returns></returns> public static string getUnixTimestamp() { string cmd = "function timeToken(){var t=0; var n=(new Date).getTime();return n<=t&&(n=t+1),t=n};"; var engine = new Jint.Engine().Execute(cmd).GetValue("timeToken"); string stamp = engine.Invoke().AsNumber().ToString(); return(stamp); }
/// <summary> /// Initializes a new instance of the JavaScriptPlugin class /// </summary> /// <param name="filename"></param> /// <param name="engine"></param> /// <param name="watcher"></param> internal JavaScriptPlugin(string filename, Engine engine, FSWatcher watcher) { // Store filename Filename = filename; Name = Core.Utility.GetFileNameWithoutExtension(Filename); JavaScriptEngine = engine; this.watcher = watcher; }
public static ConsoleInstance CreateObject(Jint.Engine engine) { var console = new ConsoleInstance(engine); console.Extensible = true; console.Prototype = engine.Object.PrototypeObject; return(console); }
internal void InstallProvider_WebUtils(Engine scriptScope) { InitializeScope_WebUtils(scriptScope); scriptScope.SetValue("echo", new Func<object, int>(s => Echo(scriptScope, s))); scriptScope.SetValue("header", new Func<string, int>(s => Header(scriptScope, s))); scriptScope.SetValue("endheaders", new Action(() => EndHeaders(scriptScope))); scriptScope.SetValue("die", new Action(() => Die(scriptScope))); scriptScope.SetValue("error_reporting", new Func<int, int>(s => error_reporting(scriptScope, s))); }
/// <summary> /// Copies and translates the contents of the specified config file into the specified object /// </summary> /// <param name="config"></param> /// <param name="engine"></param> /// <returns></returns> public static ObjectInstance ObjectFromConfig(DynamicConfigFile config, Engine engine) { var objInst = new ObjectInstance(engine) {Extensible = true}; foreach (var pair in config) { objInst.FastAddProperty(pair.Key, JsValueFromObject(pair.Value, engine), true, true, true); } return objInst; }
/// <summary> /// Initializes a new instance of the CoffeeScriptPluginLoader class /// </summary> /// <param name="engine"></param> public CoffeeScriptPluginLoader(Engine engine) { JavaScriptEngine = engine; using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(compilerResourcePath)) using (var reader = new StreamReader(stream)) engine.Execute(reader.ReadToEnd(), new ParserOptions { Source = "CoffeeScriptCompiler" }); engine.Execute("function __CompileScript(name){return CoffeeScript.compile(name+\"=\\n\"+__CoffeeSource.replace(/^/gm, ' '),{bare: true})}"); }
//Arrays cannot simply be passed into the Javascript engine, they must be allocated //according to Javascript rules private static ArrayInstance ToJSArray(IEnumerable list, Engine engine) { List<JsValue> wrappedVals = new List<JsValue>(); foreach (object x in list) { wrappedVals.Add(JsValue.FromObject(engine, x)); } return (ArrayInstance)engine.Array.Construct(wrappedVals.ToArray()); }
public static long DateGetTime(DateTime date) { var time = new Engine() .Execute(@"function getTime(date){return date.getTime();}") .Invoke("getTime", DateTime.Now) .ToObject(); return Convert.ToInt64(time); }
protected override void RemoveEngineCustomizations(Engine jintEngine) { jintEngine.Global.Delete("documentId", true); jintEngine.Global.Delete("replicateTo", true); foreach (var sqlReplicationTable in config.SqlReplicationTables) { jintEngine.Global.Delete("replicateTo" + sqlReplicationTable.TableName, true); } }
public static EventInstance CreateObject(Jint.Engine engine) { var e = new EventInstance(engine); e.Extensible = true; e.Prototype = engine.Object.PrototypeObject; return(e); }
public static BlockInstance CreateObject(Jint.Engine engine, IMyTerminalBlock tb) { var e = new BlockInstance(engine, tb); e.Extensible = true; e.Prototype = engine.Object.PrototypeObject; return(e); }
public static void DefinedDotNetApi() { var engine = new Jint.Engine(); engine.SetValue("demoJSApi", new DemoJavascriptApi()); var result = engine.Execute("demoJSApi.helloWorldFromDotNet('TestTest')").GetCompletionValue(); Console.WriteLine(result); }
public void VarTest() { var square = new Engine() .SetValue("x", 3) // define a new variable .Execute("x * x") // execute a statement .GetCompletionValue() // get the latest statement completion value .ToObject() // converts the value to .NET ; Assert.AreEqual(9.0, square); }
public override void Dispose() { if (_disposedFlag.Set()) { lock (_executionSynchronizer) { _jsEngine = null; } } }
/// <summary> /// Loads the law script received. /// </summary> /// <param name="script">The javascript laws applied to the current /// principal.</param> public virtual void Load(string script) { if (string.IsNullOrEmpty(script.Trim())) { throw new ArgumentException("the 'script' parameter cannot be null or empty."); } this.engine = new Jint.Engine(); this.engine.SetValue("message", new JsMessageDelegate(o => OnMessage(new MessageEventArgs(o.ToString())))); this.engine.Execute(script); }
public TemplateJintPreprocessor(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource, DocumentBuildContext context) { if (!string.IsNullOrWhiteSpace(scriptResource.Content)) { _engine = SetupEngine(resourceCollection, scriptResource, context); } else { _engine = null; } }
public static void Repl() { var engine = new Jint.Engine(); while (true) { Console.Write("> "); var statement = Console.ReadLine(); var result = engine.Execute(statement).GetCompletionValue(); Console.WriteLine(result); } }
public override void PutDocument(string key, object documentAsObject, object metadataAsObject, Engine engine) { if (documentAsObject == null) { throw new InvalidOperationException( string.Format("Created document cannot be null or empty. Document key: '{0}'", key)); } var newDocument = new JsonDocument { Key = key, //DataAsJson = ToRavenJObject(doc) DataAsJson = RavenJObject.FromObject(documentAsObject) }; if (metadataAsObject == null) { RavenJToken value; if (newDocument.DataAsJson.TryGetValue("@metadata", out value)) { newDocument.DataAsJson.Remove("@metadata"); newDocument.Metadata = (RavenJObject)value; } } else { var metadata = RavenJObject.FromObject(metadataAsObject); foreach (var etagKeyName in EtagKeyNames) { RavenJToken etagValue; if (!metadata.TryGetValue(etagKeyName, out etagValue)) continue; metadata.Remove(etagKeyName); var etag = etagValue.Value<string>(); if (string.IsNullOrEmpty(etag)) continue; Etag newDocumentEtag; if (Etag.TryParse(etag, out newDocumentEtag) == false) throw new InvalidOperationException(string.Format("Invalid ETag value '{0}' for document '{1}'", etag, key)); newDocument.Etag = newDocumentEtag; } newDocument.Metadata = metadata; } ValidateDocument(newDocument); AddToContext(key, newDocument); }
public Parser(string inputFile) { _inputFile = inputFile; _engine = new Engine(); _watcher = new FileSystemWatcher { Path = "./", NotifyFilter = NotifyFilters.LastWrite, Filter = string.Format("*{0}*", _inputFile) }; _watcher.Changed += OnInputFileChanged; }
/// <summary> /// Initializes the JavaScript engine /// </summary> private void InitializeJavaScript() { // Create the JavaScript engine JavaScriptEngine = new Engine(cfg => cfg.AllowClr(AppDomain.CurrentDomain.GetAssemblies().Where(AllowAssemblyAccess).ToArray())); JavaScriptEngine.Global.FastSetProperty("importNamespace", new PropertyDescriptor(new ClrFunctionInstance(JavaScriptEngine, (thisObj, arguments) => { var nspace = TypeConverter.ToString(arguments.At(0)); if (string.IsNullOrEmpty(nspace) || (WhitelistNamespaces?.Any(nspace.StartsWith) ?? false) || nspace.Equals("System")) return new NamespaceReference(JavaScriptEngine, nspace); return JsValue.Null; }), false, false, false)); }
private static void InitJsEngine(Jint.Engine engine) { StringBuilder sb = new StringBuilder(); foreach (string strFunc in listFunc) { sb.Append(strFunc); } engine.Execute(sb.ToString()); engine.SetValue("colorFromName", new Func <string, System.Drawing.Color>(System.Drawing.Color.FromName)); engine.SetValue("colorFromArgb", new Func <int, int, int, int, System.Drawing.Color>(System.Drawing.Color.FromArgb)); }
public async Task jQueryClickTest() { string script = "var numClicks = 0;\n" + "$('#btn').click(function() {\n" + "$('#message').text(\"hello there you clicked the button \" + numClicks + \" times\");\n" + "});"; string html = @"<!DOCTYPE html>\n<html> <head> </head> <body> <div id='message'>empty</div> <input type='button' id='btn'>Click me please</input> </body> </html>"; Jint.Engine engine = new Jint.Engine(); IDocument document = new Document(); var parser = new AngleSharp.Html.Parser.HtmlParser(new AngleSharp.Html.Parser.HtmlParserOptions() { IsScripting = true }); bool waitForScripts = true; //parser.AddEventListener(AngleSharp.Dom.EventNames.Parsing, (target,ev) => { document.HtmlDocument = (IHtmlDocument)target; while (waitForScripts) { Thread.Sleep(250); } }); //CancellationToken parserCanellationToken = new CancellationToken(); /*Task<IHtmlDocument> parseTask = Task.Run(() => { return parser.ParseDocumentAsync(html, parserCanellationToken); }); * * Thread.Sleep(500); * while(document.HtmlDocument == null) * { * * }*/ Window.Window window1 = new Window.Window(engine); window1.document = parser.ParseDocument(html); window1.InitializeEngine(); var jquery = System.IO.File.ReadAllText(@"../../../../BrowseSharpPlayground/jquery.js"); //engine.Execute("window.document.readyState = \"Loading\";"); engine.Execute(jquery); engine.Execute("var $ = window.jQuery;"); engine.Execute(script); waitForScripts = false;; CheckMessage(engine, document, "empty"); engine.Execute("$('#btn').trigger('click');"); CheckMessage(engine, document, "hello there you clicked the button 1 times"); }
public static Jint.Engine GetJsEngine() { if (engine != null) { return(engine); } else { engine = new Jint.Engine(cfg => cfg.AllowClr()); InitJsEngine(engine); return(engine); } }
public void EntityTest() { var account = new Account { Name = "xuefly" }; var engine = new Engine() .SetValue("p", account) .Execute("p.Name = '薛兴帅'") ; Assert.AreEqual("薛兴帅", account.Name); }
public void NullStringPropertiesShouldBeConvertedProperly() { using (var scope = new DefaultScriptedJsonPatcherOperationScope()) { var engine = new Engine(); var jsObject = engine.Object.Construct(Arguments.Empty); jsObject.Put("Test", new JsValue((string)null), true); var result = scope.ToRavenJObject(jsObject); Assert.Null(result.Value<string>("Test")); } }
protected override void RemoveEngineCustomizations(Engine engine, ScriptedJsonPatcherOperationScope scope) { base.RemoveEngineCustomizations(engine, scope); engine.Global.Delete("documentId", true); engine.Global.Delete("replicateTo", true); engine.Global.Delete("toVarchar", true); engine.Global.Delete("toNVarchar", true); foreach (var sqlReplicationTable in config.SqlReplicationTables) { engine.Global.Delete("replicateTo" + sqlReplicationTable.TableName, true); } }
internal string GetAssignScriptResult(string script, string field, Dictionary <string, string> answers) { var engine = new Jint.Engine(); foreach (var variable in answers) { engine.SetValue(variable.Key, variable.Value); } engine.Execute(script); var result = engine.GetCompletionValue(); return(result.IsNull() ? null : result.ToString()); }
/// <summary> /// Constructs an instance of adapter for the Jint JS engine /// </summary> /// <param name="settings">Settings of the Jint JS engine</param> public JintJsEngine(JintSettings settings) { _cancellationTokenSource = new CancellationTokenSource(); _cancellationConstraint = new OriginalCancellationConstraint(_cancellationTokenSource.Token); JintSettings jintSettings = settings ?? new JintSettings(); _debuggerBreakCallback = jintSettings.DebuggerBreakCallback; _debuggerStepCallback = jintSettings.DebuggerStepCallback; var debuggerStatementHandlingMode = Utils.GetEnumFromOtherEnum <JsDebuggerStatementHandlingMode, OriginalDebuggerStatementHandlingMode>( jintSettings.DebuggerStatementHandlingMode); try { _jsEngine = new OriginalEngine(options => { options .WithoutConstraint(c => c is OriginalCancellationConstraint) .Constraint(_cancellationConstraint) .DebuggerStatementHandling(debuggerStatementHandlingMode) .DebugMode(jintSettings.EnableDebugging) .LimitMemory(jintSettings.MemoryLimit) .LimitRecursion(jintSettings.MaxRecursionDepth) .LocalTimeZone(jintSettings.LocalTimeZone ?? TimeZoneInfo.Local) .MaxArraySize(jintSettings.MaxArraySize) .MaxStatements(jintSettings.MaxStatements) .Strict(jintSettings.StrictMode) .TimeoutInterval(jintSettings.TimeoutInterval) ; if (jintSettings.RegexTimeoutInterval.HasValue) { options.RegexTimeoutInterval(jintSettings.RegexTimeoutInterval.Value); } options.AddObjectConverter(new UndefinedConverter()); }); if (_debuggerBreakCallback != null) { _jsEngine.DebugHandler.Break += _debuggerBreakCallback; } if (_debuggerStepCallback != null) { _jsEngine.DebugHandler.Step += _debuggerStepCallback; } } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
private void CheckMessage(Jint.Engine engine, IDocument document, string message) { string messageContentJintJqueryInitial = engine.Execute("$('#message').text();").GetCompletionValue().AsString(); Assert.AreEqual(message, messageContentJintJqueryInitial); string messageContentJintVanillaInitial = engine.Execute("document.getElementById('message').textContent;").GetCompletionValue().AsString(); Assert.AreEqual(message, messageContentJintVanillaInitial); string messageContentAngleSharpInitial = engine.Execute("document.getElementById('message').textContent;").GetCompletionValue().AsString(); Assert.AreEqual(message, document.HtmlDocument.GetElementById("message").TextContent); }
public bool GetCondResult(string condCode, Dictionary <string, string> variables) { condCode = condCode.Replace("&", "&"); var engine = new Jint.Engine(); foreach (var variable in variables) { engine.SetValue(variable.Key, variable.Value); } engine.Execute(condCode); var result = engine.GetCompletionValue().AsBoolean(); return(result); }
public void TestJint() { var ngfmPrototype = new NGFMPrototype(); Jint.Engine JintEngine = new Jint.Engine(); JintEngine.Execute(System.IO.File.ReadAllText(ngfmPrototype.underscore_js)); JintEngine.Execute(System.IO.File.ReadAllText(ngfmPrototype.grammar_ast_js)); string strCDL = "Contract Declarations Subject is Loss to Acme by HU Inception is 5 Jun 2014 Expiration is 4 Jun 2015 PolicyNum is A5059-3 Covers 100% share of 10M Sublimits 10000 by Wind"; strCDL = strCDL.Replace(System.Environment.NewLine, " "); Dictionary <string, object> IR = (Dictionary <string, object>)(AsPOJO(JintEngine.Execute("grammarAst.parse('" + strCDL + "')").GetCompletionValue())); }
public override void Dispose() { if (_disposedFlag.Set()) { lock (_executionSynchronizer) { _jsEngine = null; _cancellationConstraint = null; if (_cancellationTokenSource != null) { _cancellationTokenSource.Dispose(); _cancellationTokenSource = null; } } } }
private void ReassignChangedValues(Jint.Engine engine, Dictionary <string, string> answers) { foreach (var field in answers.ToArray()) { var val = engine.GetValue(field.Key); var newVal = val.IsNull() ? null : val.AsString(); if (string.IsNullOrEmpty(newVal)) { answers.Remove(field.Key); } else if (newVal != field.Value) { answers.Remove(field.Key); answers.Add(field.Key, newVal); } } }
private void SetupScriptingScope() { hgScriptingHost = new ScriptingHost(); hgScriptingHost.SetHost(homegenie, this.Address); if (scriptEngine.GetType() == typeof(ScriptEngine)) { // IronPyton and IronRuby engines ScriptEngine currentEngine = (scriptEngine as ScriptEngine); dynamic scope = scriptScope = currentEngine.CreateScope(); scope.hg = hgScriptingHost; } else if (scriptEngine.GetType() == typeof(Jint.Engine)) { // Jint Javascript engine Jint.Engine javascriptEngine = (scriptEngine as Jint.Engine); javascriptEngine.SetValue("hg", hgScriptingHost); } }