public void ProcessMessage(object source, Message message) { string jsonScript = "var msg = " + JsonConvert.SerializeXmlNode(message.GetXmlDocument(), Formatting.Indented, true); Engine engine = new Engine(); engine.SetValue("message", message); engine.Execute(jsonScript); engine.Execute(Script); engine.Execute("var jsonMsg = JSON.stringify(msg);"); JsValue obj = engine.GetValue("jsonMsg"); string jsonString = obj.AsString(); var document = JsonConvert.DeserializeXNode(jsonString, "HL7Message"); message.SetValueFrom(document); }
private static Task UpdateKcInfo(double cacheHour = 1) { return Task.Run(() => { infoLock.EnterUpgradeableReadLock(); if((DateTimeOffset.Now - lastUpdate).TotalHours < cacheHour) { infoLock.ExitUpgradeableReadLock(); return; } infoLock.EnterWriteLock(); try { if((DateTimeOffset.Now - lastUpdate).TotalHours < cacheHour) { return; } Engine interpreter = new Engine(cfg => cfg .LocalTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time")) .Culture(System.Globalization.CultureInfo.GetCultureInfo("ja-JP")) .MaxStatements(100) .LimitRecursion(2)); var hwr = Forwarder.CreateRequest(KcsConstantsJs); hwr.Method = "GET"; using(var resp = hwr.GetResponse()) using(var jsRdr = new StreamReader(resp.GetResponseStream())) interpreter.Execute(jsRdr.ReadToEnd()); var urlInfo = interpreter.GetValue("ConstURLInfo"); kcLoginUrl = interpreter.GetValue(urlInfo, "LoginURL").AsString(); //kcTokenUrl = interpreter.GetValue(urlInfo, "GetTokenURL").AsString(); kcWorldUrl = interpreter.GetValue(urlInfo, "GetUserWorldURL").AsString(); var maintenanceInfo = interpreter.GetValue("MaintenanceInfo"); maintenanceOngoing = interpreter.GetValue(maintenanceInfo, "IsDoing").AsNumber() != 0; maintenanceStart = UnixTimestamp.MillisecondTimestampToDateTimeOffset(interpreter.GetValue(maintenanceInfo, "StartDateTime").AsNumber()); maintenanceEnd = UnixTimestamp.MillisecondTimestampToDateTimeOffset(interpreter.GetValue(maintenanceInfo, "EndDateTime").AsNumber()); servers.Clear(); var serverInfo = interpreter.GetValue("ConstServerInfo"); foreach(var kv in serverInfo.AsObject().GetOwnProperties()) { if(kv.Value.Value?.IsString() != true) continue; servers.Add(kv.Key, kv.Value.Value.Value.AsString()); } lastUpdate = DateTimeOffset.UtcNow; } finally { infoLock.ExitWriteLock(); infoLock.ExitUpgradeableReadLock(); } }); }
protected override object InnerCallFunction(string functionName, params object[] args) { object result; lock (_executionSynchronizer) { OriginalValue functionValue; try { functionValue = _jsEngine.GetValue(functionName); } catch (OriginalJavaScriptException e) { throw WrapJavaScriptException(e); } OriginalValue resultValue; try { resultValue = _jsEngine.Invoke(functionValue, args); } catch (OriginalJavaScriptException e) { throw WrapJavaScriptException(e); } catch (OriginalMemoryLimitExceededException e) { throw WrapMemoryLimitExceededException(e); } catch (OriginalRecursionDepthOverflowException e) { throw WrapRecursionDepthOverflowException(e); } catch (OriginalStatementsCountOverflowException e) { throw WrapStatementsCountOverflowException(e); } catch (TimeoutException e) { throw WrapTimeoutException(e); } catch (ArgumentException e) when(e.Message == "Can only invoke functions") { throw new WrapperRuntimeException( string.Format(CoreStrings.Runtime_FunctionNotExist, functionName)); } result = MapToHostType(resultValue); } return(result); }
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; }
/// <summary> /// Executes a snippet of javascript in the /// running jist instance and returns any /// result in JSON format. /// </summary> public string Eval(string snippet) { JsValue returnValue = default(JsValue); if (jsEngine == null || string.IsNullOrEmpty(snippet) == true) { return("undefined"); } try { lock (syncRoot) returnValue = jsEngine.GetValue(jsEngine.Execute(snippet).GetCompletionValue()); if (returnValue.Type == Types.None || returnValue.Type == Types.Null || returnValue.Type == Types.Undefined) { return("undefined"); } } catch (JavaScriptException jex) { StringBuilder sb = new StringBuilder("JavaScript error: " + jex.Message + "\r\n"); //sb.AppendLine(string.Format(" at line {0} column {1}", jex.LineNumber, jex.Column)); //sb.AppendLine(jex.Location.Source); sb.AppendLine(jex.StackTrace); return(sb.ToString()); } catch (ParserException pex) { StringBuilder sb = new StringBuilder("JavaScript parser error: " + pex.Message + "\r\n"); sb.AppendLine(string.Format(" at line {0} column {1}", pex.LineNumber, pex.Column)); sb.AppendLine(pex.Source); sb.AppendLine(pex.StackTrace); return(sb.ToString()); } catch (Exception ex) { return(ex.ToString()); } if (string.IsNullOrEmpty(returnValue.ToString()) == true) { TShock.Log.ConsoleError("[jist eval] result of \"{0}\" is null", snippet); return("undefined"); } return(returnValue.ToString()); }
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); } } }
internal void session_destroy(Engine scriptScope) { var response = (ClientHttpResponse) scriptScope.GetValue("response").ToObject(); var cookieString = response.RequestHttpHeaders["Cookie"]; var hostString = response.RequestHttpHeaders["Host"]; var currentClientcookies = GetAllCookiesFromHeader(cookieString, hostString); var existingSession = currentClientcookies[SessionIdVarName]; if (existingSession != null) { var existingSessionId = existingSession.Value; //Cookie exists if (_session_hasSessionOnDisk(existingSessionId)) { //Session exists _sessions.Remove(existingSessionId); _session_destroySessionOnDisk(existingSessionId); } } }
internal void session_start(Engine scriptScope) { var response = (ClientHttpResponse) scriptScope.GetValue("response").ToObject(); _session_initSession(scriptScope); //Check if a session exists for user: if (response.RequestHttpHeaders.ContainsKey("Cookie")) { var cookieString = response.RequestHttpHeaders["Cookie"]; var hostString = response.RequestHttpHeaders["Host"]; var currentClientcookies = GetAllCookiesFromHeader(cookieString, hostString); var existingSession = currentClientcookies[SessionIdVarName]; if (existingSession != null) { var existingSessionId = existingSession.Value; //Cookie exists if (_session_hasSessionOnDisk(existingSessionId)) { //Session exists response.SendHeader("HTTP/1.1 200 OK"); //Send OK like the other code path if (_sessions.ContainsKey(existingSessionId)) scriptScope.SetValue("_SESSION", _sessions[existingSessionId]); //Assign _SESSION variable else _session_createSession(scriptScope); } else { //Have to recreate _session_createSession(scriptScope); } } else { _session_createSession(scriptScope); } } else { _session_createSession(scriptScope); } }
public void ExecuteScript(string fullPath, Dictionary<string, string> urlParameters, ClientHttpResponse response, string extension, string mimeType, HTTPMethod method, string postData, string documentRoot, dynamic serverHandle, ScriptExecutionParameters executionParameters) { //Prepare JSScript var scriptContents = File.ReadAllText(fullPath); var scriptDir = Path.GetDirectoryName(fullPath); var jsEngine = new Engine(cfg => cfg.AllowClr()); var undefined = Undefined.Instance; //Inject variables if (method == HTTPMethod.Get) { jsEngine.SetValue("_GET", urlParameters); jsEngine.SetValue("_SERVER", response.RequestHttpHeaders); jsEngine.SetValue("_POST", undefined); } if (method == HTTPMethod.Post) { jsEngine.SetValue("_GET", undefined); jsEngine.SetValue("_SERVER", response.RequestHttpHeaders); jsEngine.SetValue("_POST", urlParameters); jsEngine.SetValue("POST_DATA", postData); } //Globals jsEngine.SetValue("DocumentRoot", documentRoot); jsEngine.SetValue("__dirname__", scriptDir); switch (extension) { case ".jscx": //Fully-controlled script { try { //Manipulate Scope jsEngine.SetValue("response", response); jsEngine.SetValue("FireHTTPServer", serverHandle); jsEngine.SetValue("_mimeTypeMappings", CommonVariables.MimeTypeMappings); jsEngine.SetValue("dirSep", _dirSep); DefineScriptingApi(jsEngine); jsEngine.Execute(scriptContents); break; } catch (DeadRequestException) { throw; //Don't catch these. } catch (Exception ex) { var level = (int) jsEngine.GetValue("__error_reporting_level").AsNumber(); if (level > 0) { if (!response.HasFinishedSendingHeaders) { //If headers not sent, send default headers. response.SendHeader("HTTP/1.1 200 OK"); response.SendHeader("Content-Type: text/plain"); response.SendEndHeaders(); } response.OutputStream.WriteLine("Error in script execution. Stack trace:"); response.OutputStream.WriteLine(ex.ToString()); break; } throw; } } } }
private static void startGame(GameManager gameManager) { Engine engine = new Engine(); var promise = getFile(@"./js/promise.js"); var sevens = getFile(@"./js/sevens.js"); var dataClass = new DataClass(gameManager); engine.SetValue("shuff", dataClass); engine.SetValue("exports", new { }); engine.SetValue("require", new Func<string, JsValue>((file) => { var txt = getFile($@"./js/{file}.js"); engine.SetValue("shuff", dataClass); engine.Execute("var exports={};" + txt); return engine.GetValue("exports"); })); engine.Execute(promise + "; " + sevens); engine.Execute("Main.run()"); }
private Engine CreateEngine(Engine engine, params string[] sharedVariables) { var newEngine = CreateDefaultEngine(); if (sharedVariables != null) { foreach(var sharedVariable in sharedVariables) { newEngine.SetValue(sharedVariable, engine.GetValue(sharedVariable)); } } return newEngine; }
private void OutputLog(Engine engine) { var arr = engine.GetValue("debug_outputs"); if (arr == JsValue.Null || arr.IsArray() == false) return; foreach (var property in arr.AsArray().Properties) { if (property.Key == "length") continue; var jsInstance = property.Value.Value; if (!jsInstance.HasValue) continue; var output = jsInstance.Value.IsNumber() ? jsInstance.Value.AsNumber().ToString() : jsInstance.Value.AsString(); Debug.Add(output); } engine.Invoke("clear_debug_outputs"); }
private void OutputLog(Engine engine) { var arr = engine.GetValue("debug_outputs"); if (arr == JsValue.Null || arr.IsArray() == false) return; foreach (var property in arr.AsArray().Properties) { if (property.Key == "length") continue; var jsInstance = property.Value.Value; if (!jsInstance.HasValue) continue; var output = jsInstance.Value.IsNumber() ? jsInstance.Value.AsNumber().ToString(CultureInfo.InvariantCulture) : (jsInstance.Value.IsBoolean() ? //if the parameter is boolean, we need to take it into account, //since jsInstance.Value.AsString() will not work for boolean values jsInstance.Value.AsBoolean().ToString() : jsInstance.Value.AsString()); Debug.Add(output); } engine.Invoke("clear_debug_outputs"); }
public virtual void Execute(object controller, Dictionary <string, Parameter> parameters, View view, Dictionary <string, object> values, DataRow prevRow, string pk, string connectionString, int currentUsetId, string currentUserRole, IDbCommand command, IDbCommand sysCommand, string actionName, Durados.TriggerDataAction dataAction) { if (pk != null && (prevRow == null || dataAction == TriggerDataAction.AfterCreate || dataAction == TriggerDataAction.AfterEdit || dataAction == TriggerDataAction.AfterCreateBeforeCommit || dataAction == TriggerDataAction.AfterEditBeforeCommit) && controller is Durados.Data.IData) { try { if (((Durados.Data.IData)controller).DataHandler != null) { prevRow = ((Durados.Data.IData)controller).DataHandler.GetDataRow(view, pk, command); } } catch { } } var guid = Guid.NewGuid(); //if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request.QueryString[GuidKey] != null) //{ // guid = new Guid(System.Web.HttpContext.Current.Request.QueryString[GuidKey]); //} SetCacheInCurrentRequest("js" + guid, new Dictionary <string, object>() { { "controller", controller }, { "connectionString", connectionString }, { "currentUsetId", currentUsetId }, { "currentUserRole", currentUserRole }, { "command", command }, { "sysCommand", sysCommand }, { "actionName", actionName }, { "dataAction", dataAction } }); SetCacheInCurrentRequest(ConnectionStringKey, view.Database.SysDbConnectionString); SetCacheInCurrentRequest(GuidKey, guid); if (!parameters.ContainsKey("code")) { throw new DuradosException("code was not supplied"); } string code = parameters["code"].Value.Replace(Engine.AsToken(values), ((Durados.Workflow.INotifier)controller).GetTableViewer(), view); string currentUsername = view.Database.GetCurrentUsername(); try { code = code.Replace(Durados.Database.UserPlaceHolder, currentUsetId.ToString(), false).Replace(Durados.Database.SysUserPlaceHolder.AsToken(), currentUsetId.ToString(), false) .Replace(Durados.Database.UsernamePlaceHolder, currentUsername, false).Replace(Durados.Database.SysUsernamePlaceHolder.AsToken(), currentUsername) .Replace(Durados.Database.RolePlaceHolder, currentUserRole, false).Replace(Durados.Database.SysRolePlaceHolder.AsToken(), currentUserRole) .ReplaceConfig(view); } catch { } Dictionary <string, object> clientParameters = new Dictionary <string, object>(); Dictionary <string, object> newRow = new Dictionary <string, object>(); Dictionary <string, object> oldRow = new Dictionary <string, object>(); Dictionary <string, object> userProfile = new Dictionary <string, object>(); bool debug = false; if (IsDebug()) { debug = true; } if (values != null) { foreach (string key in values.Keys) { if (key == "$$debug$$" || key == "$$debug$$".AsToken()) { debug = true; } else { string keyWithoutToken = key.TrimStart("{{".ToCharArray()).TrimEnd("}}".ToCharArray()); if (key.StartsWith("{{")) { if (!clientParameters.ContainsKey(keyWithoutToken)) { clientParameters.Add(keyWithoutToken, values[key]); } } if (view.GetFieldsByJsonName(keyWithoutToken) == null || view.GetFieldsByJsonName(keyWithoutToken).Length == 0) { if (view.Fields.ContainsKey(keyWithoutToken)) { string jsonName = view.Fields[keyWithoutToken].JsonName; if (!newRow.ContainsKey(jsonName)) { newRow.Add(jsonName, values[key]); } } else { if (!clientParameters.ContainsKey(keyWithoutToken)) { clientParameters.Add(keyWithoutToken, values[key]); } } } else { if (!newRow.ContainsKey(keyWithoutToken)) { newRow.Add(keyWithoutToken, values[key]); } } } } } SetCacheInCurrentRequest(Debug, debug); if (prevRow != null) { foreach (Field field in view.Fields.Values) { if (!oldRow.ContainsKey(field.JsonName)) { if (field.FieldType == FieldType.Column && field.IsDate) { oldRow.Add(field.JsonName, prevRow[((ColumnField)field).DataColumn.ColumnName]); } else { oldRow.Add(field.JsonName, field.GetValue(prevRow)); } } } //var shallowRow = view.RowToShallowDictionary(prevRow, pk); //foreach (Field field in view.Fields.Values) //{ // if (oldRow.ContainsKey(field.JsonName) && shallowRow.ContainsKey(field.JsonName)) // { // if (field.FieldType == FieldType.Column && (field.IsBoolean || field.IsPoint || field.IsNumeric)) // { // oldRow[field.JsonName] = shallowRow[field.JsonName]; // } // } //} } userProfile.Add("username", view.Database.GetCurrentUsername()); userProfile.Add("role", currentUserRole); userProfile.Add("app", view.Database.GetCurrentAppName()); userProfile.Add("userId", view.Database.GetCurrentUserId()); userProfile.Add("token", GetUserProfileAuthToken(view)); userProfile.Add("anonymousToken", view.Database.GetAnonymousToken().ToString()); userProfile.Add("info", GetUserProfileInfo(view)); if (!clientParameters.ContainsKey(FILEDATA)) { int parametersLimit = (int)view.Database.GetLimit(Limits.ActionParametersKbSize); HandleParametersSizeLimit(parametersLimit, clientParameters); userProfile.Add("request", GetRequest()); } var CONSTS = new Dictionary <string, object>() { { "apiUrl", System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Host + ":" + System.Web.HttpContext.Current.Request.Url.Port + System.Web.HttpContext.Current.Request.ApplicationPath }, { "actionGuid", System.Web.HttpContext.Current.Request.QueryString[GuidKey] ?? (System.Web.HttpContext.Current.Items[GuidKey] ?? guid.ToString()) } }; //Newtonsoft.Json.JsonConvert.SerializeObject var theJavaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); theJavaScriptSerializer.MaxJsonLength = int.MaxValue; var parser = new Jint.Native.Json.JsonParser(call2); //var userInput = parser.Parse(theJavaScriptSerializer.Serialize(newRow)); //Object clientParametersToSend = null; //if (!clientParameters.ContainsKey("filedata")) //{ // clientParametersToSend = parser.Parse(theJavaScriptSerializer.Serialize(clientParameters)); //} //else //{ // System.Web.HttpContext.Current.Items["file_stream"] = clientParameters["filedata"]; // clientParameters["filedata"] = "file_stream"; // clientParametersToSend = clientParameters; //} //var dbRow = parser.Parse(theJavaScriptSerializer.Serialize(oldRow)); //var userProfile2 = parser.Parse(theJavaScriptSerializer.Serialize(userProfile)); //var CONSTS2 = parser.Parse(theJavaScriptSerializer.Serialize(CONSTS)); //var Config = view.Database.GetConfigDictionary(); //var Config2 = parser.Parse(theJavaScriptSerializer.Serialize(Config)); var userInput = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(newRow)); Object clientParametersToSend = null; bool upload = false; if (!clientParameters.ContainsKey(FILEDATA)) { clientParametersToSend = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(clientParameters)); } else { upload = true; System.Web.HttpContext.Current.Items["file_stream"] = clientParameters[FILEDATA]; clientParameters[FILEDATA] = "file_stream"; clientParametersToSend = clientParameters; } if (clientParameters.ContainsKey(FILEDATA) || clientParameters.ContainsKey(FILENAME)) { System.Web.HttpContext.Current.Items[StorageAccountsKey] = view.Database.CloudStorages; } var dbRow = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(oldRow)); var userProfile2 = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(userProfile)); var CONSTS2 = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(CONSTS)); var Config = view.Database.GetConfigDictionary(); var Config2 = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(Config)); var Environment = view.Database.GetEnvironmentDictionary(); var Environment2 = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(Environment)); Limits limit = Limits.ActionTimeMSec; if (upload) { limit = Limits.UploadTimeMSec; } object actionTimeMSecObject = view.Database.GetLimit(limit); int actionTimeMSec = -1; if (!Int32.TryParse(actionTimeMSecObject.ToString(), out actionTimeMSec)) { throw new DuradosException("actionTimeMSecLimit in web.config is not numeric or too long"); } TimeSpan?timeoutInterval = new TimeSpan(0, 0, 0, 0, actionTimeMSec); if (actionTimeMSec == 0) { timeoutInterval = null; } string actionId = Guid.NewGuid().ToString(); string startMessage = theJavaScriptSerializer.Serialize(new { objectName = view.JsonName, actionName = actionName, id = actionId, @event = "started", time = GetSequence(view), data = new { userInput = newRow, dbRow = oldRow, parameters = clientParameters, userProfile = userProfile } }); Backand.Logger.Log(startMessage, 502); var call = new Jint.Engine(cfg => cfg.AllowClr(typeof(Backand.XMLHttpRequest).Assembly), timeoutInterval, GetLineStart(), new ActionPath() { @object = view.JsonName, action = actionName }); try { call.SetValue("userInput", userInput) .SetValue("btoa", new btoaHandler(Backand.Convert.btoa)) .SetValue("dbRow", dbRow) .SetValue("parameters", clientParametersToSend) .SetValue("userProfile", userProfile2) .SetValue("CONSTS", CONSTS2) .SetValue("Config", Config2) .SetValue("Environment", Environment2) .Execute(GetXhrWrapper() + code + "; function call(){return backandCallback(userInput, dbRow, parameters, userProfile);}"); } catch (TimeoutException exception) { Handle503(theJavaScriptSerializer, view.JsonName, actionName, actionId, exception.Message, view); string errorMessage = "Timeout: The operation took longer than " + actionTimeMSec + " milliseconds limit. at (" + view.JsonName + "/" + actionName + ")"; if (!IsSubAction()) { Backand.Logger.Log(exception.Message, 501); if (IsDebug()) { throw new MainActionInDebugJavaScriptException(errorMessage, exception); } else { throw new MainActionJavaScriptException(errorMessage, exception); } } else { throw new SubActionJavaScriptException(errorMessage, exception); } } catch (Exception exception) { Handle503(theJavaScriptSerializer, view.JsonName, actionName, actionId, exception.Message, view); string errorMessage = "Syntax error: " + HandleLineCodes(exception.Message, view.JsonName, actionName, view, IsDebug()); if (!IsSubAction()) { Backand.Logger.Log(exception.Message, 501); if (IsDebug()) { throw new MainActionInDebugJavaScriptException(errorMessage, exception); } else { throw new MainActionJavaScriptException(errorMessage, exception); } } else { throw new SubActionJavaScriptException(errorMessage, exception); } } object r = null; try { var r2 = call.GetValue("call").Invoke(); if (!r2.IsNull()) { r = r2.ToObject(); } string endMessage = null; try { endMessage = theJavaScriptSerializer.Serialize(new { objectName = view.JsonName, actionName = actionName, id = actionId, @event = "ended", time = GetSequence(view), data = r }); } catch (Exception exception) { if (exception.Message.StartsWith("A circular reference was detected while serializing an object")) { object oNull = null; endMessage = theJavaScriptSerializer.Serialize(new { objectName = view.JsonName, actionName = actionName, id = actionId, @event = "ended", time = GetSequence(view), data = oNull }); } else { endMessage = "Failed to serialize response"; if (!IsSubAction()) { Backand.Logger.Log(endMessage, 501); //if (IsDebug()) //{ // values[ReturnedValueKey] = message; // return; //} //else if (IsDebug()) { throw new MainActionInDebugJavaScriptException(endMessage, exception); } else { throw new MainActionJavaScriptException(endMessage, exception); } } else { throw new SubActionJavaScriptException(endMessage, exception); } } } Backand.Logger.Log(endMessage, 503); } catch (TimeoutException exception) { string message = "Timeout: The operation took longer than " + actionTimeMSec + " milliseconds limit. at (" + view.JsonName + "/" + actionName + ")"; Handle503(theJavaScriptSerializer, view.JsonName, actionName, actionId, message, view); if (!IsSubAction()) { Backand.Logger.Log(message, 501); if (IsDebug()) { throw new MainActionInDebugJavaScriptException(message, exception); } else { throw new MainActionJavaScriptException(message, exception); } } else { throw new SubActionJavaScriptException(message, exception); } } catch (Exception exception) { string message = (exception.InnerException == null) ? exception.Message : exception.InnerException.Message; string trace = message; if (exception is Jint.Runtime.JavaScriptException) { trace = ((Jint.Runtime.JavaScriptException)exception).GetTrace(); } trace = HandleLineCodes(trace, view.JsonName, actionName, view, IsDebug()); Handle503(theJavaScriptSerializer, view.JsonName, actionName, actionId, trace, view); if (!IsSubAction()) { IMainActionJavaScriptException mainActionJavaScriptException; Backand.Logger.Log(trace, 501); if (IsDebug()) { mainActionJavaScriptException = new MainActionInDebugJavaScriptException(message, exception); } else { mainActionJavaScriptException = new MainActionJavaScriptException(message, exception); } mainActionJavaScriptException.JintTrace = trace; throw (Exception)mainActionJavaScriptException; } else { throw new SubActionJavaScriptException(message, exception); } } var v = call.GetValue("userInput").ToObject(); if (v != null && v is System.Dynamic.ExpandoObject) { IDictionary <string, object> newValues = v as IDictionary <string, object>; foreach (string key in newValues.Keys) { if (values.ContainsKey(key)) { object val = newValues[key]; Field[] fields = view.GetFieldsByJsonName(key); val = DateConversion(view, val, fields); values[key] = val; } else { Field[] fields = view.GetFieldsByJsonName(key); if (fields.Length > 0) { string fieldName = fields[0].Name; object val = newValues[key]; val = DateConversion(view, val, fields); if (values.ContainsKey(fieldName)) { values[fieldName] = val; } else { values.Add(fieldName, val); } } else { values.Add(key, newValues[key]); } } } } if (r != null && values != null && dataAction == TriggerDataAction.OnDemand) { if (!values.ContainsKey(ReturnedValueKey)) { values.Add(ReturnedValueKey, r); } else { values[ReturnedValueKey] = r; } } }
private static int EndHeaders(Engine scriptScope) { ((ClientHttpResponse) scriptScope.GetValue("response").ToObject()).SendEndHeaders(); return 0; }
private void OutputLog(Engine engine) { var arr = engine.GetValue("debug_outputs"); if (arr == JsValue.Null || arr.IsArray() == false) return; foreach (var property in arr.AsArray().Properties) { if (property.Key == "length") continue; var jsInstance = property.Value.Value; if (!jsInstance.HasValue) continue; var value = jsInstance.Value; string output = null; switch (value.Type) { case Types.Boolean: output = value.AsBoolean().ToString(); break; case Types.Null: case Types.Undefined: output = value.ToString(); break; case Types.Number: output = value.AsNumber().ToString(CultureInfo.InvariantCulture); break; case Types.String: output = value.AsString(); break; } if (output != null) Debug.Add(output); } engine.Invoke("clear_debug_outputs"); }
private static int Header(Engine scriptScope, string header) { ((ClientHttpResponse) scriptScope.GetValue("response").ToObject()).SendHeader(header); return 0; }
private async Task<Tuple<string, string>> GetChallengeAndSaltAsync() { Uri loginUri = new Uri(this.endpoint.ToString() + LoginPath); using (var webClient = new WebClient()) { webClient.Headers.Add("X-FBX-FREEBOX0S", "1"); string jsonString = await webClient.DownloadStringTaskAsync(loginUri); dynamic jsonObject = JObject.Parse(jsonString); if (jsonObject.success != true) { throw new Exception("Failed to fetch challenge. Response: " + jsonString); } string salt = jsonObject.result.password_salt; string challenge = string.Empty; // The challenge is an array of javacript code. // The code in each cell is executed an the results concatenated. try { foreach (var challengeEntry in jsonObject.result.challenge) { var engine = new Engine(); engine.SetValue("challengeEntry", challengeEntry.ToString()); engine.SetValue("result", ""); engine.SetValue("unescape", (StringTranform)delegate(string s) { return HttpUtility.UrlDecode(s); }); string script = @" result = eval(challengeEntry)"; engine.Execute(script); challenge += engine.GetValue("result").AsString(); } return new Tuple<string, string>(challenge, salt); } catch (Exception exception) { return null; } } }
private void _session_createSession(Engine scriptScope) { var response = (ClientHttpResponse) scriptScope.GetValue("response").ToObject(); var sessionId = Guid.NewGuid().ToString("N"); response.SendHeader("HTTP/1.1 200 OK"); response.SendHeader("Set-Cookie: " + SessionIdVarName + "=" + sessionId + ";path=/"); var currentSessionDict = new SessionData(); _sessions.Add(sessionId, currentSessionDict); //Add a new session dictionary scriptScope.SetValue("_SESSION", currentSessionDict); _session_dumpSession(sessionId, currentSessionDict); }
internal MethodRunResult EvaluateCondition() { MethodRunResult result = null; switch (codeType.ToLower()) { case "python": string pythonScript = this.ScriptCondition; ScriptEngine pythonEngine = (scriptEngine as ScriptEngine); result = new MethodRunResult(); try { pythonEngine.Execute(pythonScript, scriptScope); result.ReturnValue = (scriptScope as dynamic).hg.executeCodeToRun; } catch (Exception e) { result.Exception = e; } break; case "ruby": string rubyScript = this.ScriptCondition; ScriptEngine rubyEngine = (scriptEngine as ScriptEngine); result = new MethodRunResult(); try { rubyEngine.Execute(rubyScript, scriptScope); result.ReturnValue = (scriptScope as dynamic).hg.executeCodeToRun; } catch (Exception e) { result.Exception = e; } break; case "javascript": string jsScript = this.ScriptCondition; Jint.Engine engine = (scriptEngine as Jint.Engine); result = new MethodRunResult(); try { engine.Execute(jsScript); result.ReturnValue = (engine.GetValue("hg").ToObject() as ScriptingHost).executeCodeToRun; } catch (Exception e) { result.Exception = e; } break; case "csharp": if (appAssembly != null && CheckAppInstance()) { result = (MethodRunResult)methodEvaluateCondition.Invoke(assembly, null); } break; } // return(result); }
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); } } }