private void makeAsynchronousRequest(JsString url, TranslationsFileLoaded fileLoaded) { XMLHttpRequest request = new XMLHttpRequest(); if (forceReload) { //just bust the cache for now url = url + "?rnd=" + JsMath.random(); } request.open("GET", url, true); request.onreadystatechange = delegate(DOMEvent evt) { if (request.readyState == 4 && request.status == 200) { parseResult(request.responseText); fileLoaded(); } else if (request.readyState >= 3 && request.status == 404) { HtmlContext.alert("Required Content " + url + " cannot be loaded."); throw new JsError("Cannot continue, missing required property file " + url); } }; request.send(""); }
public virtual void Delete(string folder, string functionName, string arn = ARN) { string url = BaseUrl + "/deleteLambda"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("folder", folder); data.Add("functionName", functionName); data.Add("Role", arn); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { throw new Durados.DuradosException("Server return status " + request.status + ", " + request.responseText); } Dictionary <string, object> response = null; try { response = jss.Deserialize <Dictionary <string, object> >(request.responseText); } catch (Exception exception) { throw new Durados.DuradosException("Could not parse upload response", exception); } }
public virtual object Download(Durados.Security.Cloud.ICloudCredentials cloudCredentials, string lambdaFunctionName) { string url = BaseUrl + "/downloadLambda"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("credentials", cloudCredentials.GetCredentials()); data.Add("cloudProvider", cloudCredentials.GetProvider()); data.Add("functionName", lambdaFunctionName); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { throw new NodeJsException(request.responseText.TrimStart("{}; ".ToCharArray())); } object response = null; try { response = jss.Deserialize <object>(request.responseText); } catch (Exception exception) { throw new Durados.DuradosException("Could not parse NodeJS response", exception); } return(response); }
/// <inheritdoc /> public void LoadSoundFont(byte[] data) { if (@typeof(data) == "string") { var url = data.As <string>(); Logger.Info("Start loading Soundfont from url " + url); var request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; request.onload = e => { var buffer = new Uint8Array(request.response.As <ArrayBuffer>()); _synth.postMessage(new { cmd = AlphaSynthWebWorker.CmdLoadSoundFontBytes, data = buffer.As <byte[]>() }); }; request.onerror = e => { Logger.Error("Loading failed: " + e.message); TriggerEvent("soundFontLoadFailed"); }; request.onprogress = e => { Logger.Debug("Soundfont downloading: " + e.loaded + "/" + e.total + " bytes"); TriggerEvent("soundFontLoad", new object[] { new { loaded = e.loaded, total = e.total } }); }; request.send(); } else { _synth.postMessage(new { cmd = AlphaSynthWebWorker.CmdLoadSoundFontBytes, data = data }); } }
private static Dictionary <string, object> getCron(string prefix) { string url = BaseUrl + "/getCron"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("namePrefix", prefix); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { throw new Durados.DuradosException("Server return status " + request.status + ", " + request.responseText); } Dictionary <string, object> response = null; try { response = jss.Deserialize <Dictionary <string, object> >(request.responseText); } catch (Exception exception) { throw new Durados.DuradosException("Could not parse getCron response", exception); } return(response); }
public byte[] LoadBinary(string path) { var ie = GetIEVersion(); if (ie >= 0 && ie <= 9) { // use VB Loader to load binary array dynamic vbArr = VbAjaxLoader("GET", path); var fileContents = vbArr.toArray(); // decode byte array to string var data = new StringBuilder(); var i = 0; while (i < (fileContents.length - 1)) { data.AppendChar((char)(fileContents[i])); i++; } var reader = GetBytesFromString(data.ToString()); return(reader); } XMLHttpRequest xhr = new XMLHttpRequest(); xhr.open("GET", path, false); xhr.responseType = "arraybuffer"; xhr.send(); if (xhr.status == 200) { var reader = NewUint8Array(xhr.response); return(reader); } // Error handling if (xhr.status == 0) { throw new FileLoadException("You are offline!!\n Please Check Your Network."); } if (xhr.status == 404) { throw new FileLoadException("Requested URL not found."); } if (xhr.status == 500) { throw new FileLoadException("Internel Server Error."); } if (xhr.statusText == "parsererror") { throw new FileLoadException("Error.\nParsing JSON Request failed."); } if (xhr.statusText == "timeout") { throw new FileLoadException("Request Time out."); } throw new FileLoadException("Unknow Error: " + xhr.responseText); }
protected AbstractToken <object> sendRequest(string verb, string protocol, string host, string port, string path) { var serviceToken = new ServiceToken <object>(); xmlHttpRequest.open(verb, createUri(protocol, host, port, path), true); xmlHttpRequest.onreadystatechange += serviceToken.onReadyStateChange; xmlHttpRequest.send(""); return(serviceToken); }
private async Task <string> GetAsync(string url) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", url, true); xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*"); var tcs = new TaskCompletionSource <string>(); xmlHttp.onreadystatechange = (e) => { if (xmlHttp.readyState == 0) { tcs.SetException(new Exception("Request aborted")); } else if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200 || xmlHttp.status == 201 || xmlHttp.status == 304) { tcs.SetResult(xmlHttp.responseText); } else { tcs.SetException(new Exception("Request failed")); } } }; xmlHttp.send(); var tcsTask = tcs.Task; while (true) { await Task.WhenAny(tcsTask, Task.Delay(150)); if (tcsTask.IsCompleted) { if (tcsTask.IsFaulted) { throw tcsTask.Exception; } else { return(tcsTask.Result); } } } }
public IHttpActionResult smartListFolder(string path = null) { try { if (path == null) { path = string.Empty; } string url = GetNodeUrl() + "/smartListFolder"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); string appName = Map.AppName; data.Add("bucket", Maps.S3FilesBucket); data.Add("folder", appName); data.Add("pathInFolder", path); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { Maps.Instance.DuradosMap.Logger.Log("files", "folder", request.responseText, null, 1, "status: " + request.status); return(ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, request.responseText))); } Dictionary <string, object>[] response = null; try { response = jss.Deserialize <Dictionary <string, object>[]>(request.responseText); } catch (Exception exception) { Maps.Instance.DuradosMap.Logger.Log("files", "folder", exception.Source, exception, 1, request.responseText); return(ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, "Could not parse upload response: " + request.responseText + ". With the following error: " + exception.Message))); } return(Ok(response)); } catch (Exception exception) { throw new BackAndApiUnexpectedResponseException(exception, this); } }
public void Then(Delegate fulfilledHandler, Delegate errorHandler = null, Delegate progressHandler = null) { var request = new XMLHttpRequest(); request.onreadystatechange = (ev) => { if (request.readyState != 4) { return; } if ((request.status == 200) || (request.status == 304)) { fulfilledHandler.Call(null, request); } else { errorHandler.Call(null, request.responseText); } }; if (!string.IsNullOrWhiteSpace(Options.ContentType)) { request.setRequestHeader("Content-type", Options.ContentType); } request.open(Options.Method, Options.Url); if (Options.Method.ToLower() == "post") { request.send(Options.Data); } else { request.send(); } }
private static void putCron(string name, string schedule, Dictionary <string, object> input, bool?active, string description) { string url = BaseUrl + "/putCron"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("name", name); data.Add("schedule", HandleSchedule(schedule)); data.Add("lambdaArn", LambdaArn); data.Add("input", input); if (active.HasValue) { data.Add("active", active.Value); } else { data.Add("active", null); } data.Add("description", description); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { string message = request.responseText; if (request.responseText.Contains("Parameter ScheduleExpression is not valid")) { message = "The schedule expression '" + schedule + "' is not valid"; } throw new Durados.DuradosException(message); } Dictionary <string, object> response = null; try { response = jss.Deserialize <Dictionary <string, object> >(request.responseText); } catch (Exception exception) { throw new Durados.DuradosException("Could not parse putCron response", exception); } }
/// <summary> /// /// </summary> /// <param name="bucket">bucket is S3</param> /// <param name="folder">app name</param> /// <param name="fileName">the zip file created by the CLI</param> /// <param name="functionName">the lambda function name</param> /// <param name="handlerName">the js file with the root function</param> /// <param name="callFunctionName">the root function name</param> public virtual void Create(string bucket, string folder, string fileName, string functionName, string handlerName, string callFunctionName, string cloudProvider, string arn = ARN, int memorySize = MemorySize, int timeout = Timeout) { string url = BaseUrl + "/createLambda"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("bucket", bucket); data.Add("folder", folder); data.Add("fileName", fileName); data.Add("functionName", functionName); data.Add("handlerName", handlerName); data.Add("callFunctionName", callFunctionName); data.Add("Role", arn); data.Add("memorySize", memorySize); data.Add("timeout", timeout); data.Add("cloudProvider", cloudProvider); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { throw new Durados.DuradosException("Server return status " + request.status + ", " + request.responseText); } Dictionary <string, object> response = null; try { response = jss.Deserialize <Dictionary <string, object> >(request.responseText); } catch (Exception exception) { throw new Durados.DuradosException("Could not parse upload response", exception); } }
/* * * We dont need this right now but keeping the code cause we might need it again someday soon * JsString correctPaths(JsString sheet, JsString urlPrefix) { * //First, fix the path of any objects in the system. This fines url references and preprends paths * //Right now this just works for relative urls, I am going to need to fix it for absolute * //Now using this one instead for optional quotes * //(url\s?\(\s?['"]?)([\w\W]*?)(['"]?\s?\)) * * var pathReplace = new JsRegExp("(url\\s?\\(\\s?[\'\"]?)([\\w\\W]*?)([\'\"]?\\s?\\))", "g"); * JsString replacementString = "$1" + urlPrefix + "/$2$3"; * sheet = sheet.replace(pathReplace, replacementString); * return sheet; * }*/ void resolveSheet(JsString url) { var sheetRequest = new XMLHttpRequest(); JsString behaviorSheet = ""; JsString prefix; sheetRequest.open("GET", url, false); sheetRequest.send(""); if (sheetRequest.status == 404) { throw new JsError("Cannot Find StyleSheet " + url); } int lastSlash = url.lastIndexOf("/"); prefix = url.substring(0, lastSlash); parseAndPersistBehaviors(sheetRequest.responseText); }
private static async Task <Stream> PlatformOpenStreamAsync(string safeName) { var loaded = false; var request = new XMLHttpRequest(); request.open("GET", safeName, true); request.responseType = XMLHttpRequestResponseType.arraybuffer; request.onload += (a) => { loaded = true; }; request.send(); while (!loaded) { await Task.Delay(10); } return(new MemoryStream((new Uint8Array(request.response.As <ArrayBuffer>())).As <byte[]>())); }
public string loadClass(JsString qualifiedClassName) { JsRegExp classNameRegex = new JsRegExp("\\.", "g"); var potentialURL = qualifiedClassName.replace(classNameRegex, "/"); potentialURL = dynamicClassBaseUrl + potentialURL; potentialURL += ".js"; xmlHttpRequest.open("GET", potentialURL, false); xmlHttpRequest.send(""); //Todo Need to handle other status than just 404 if (xmlHttpRequest.status == 404) { //Todo This alert shouldnt be here, we should figure out a way to get it to the UI level HtmlContext.alert("Required Class " + qualifiedClassName + " cannot be loaded."); throw new JsError("Cannot continue, missing required class " + qualifiedClassName); } return(xmlHttpRequest.responseText + "\n//@ sourceURL=" + potentialURL); }
private void makeSynchronousRequest(JsString url) { XMLHttpRequest request = new XMLHttpRequest(); if (forceReload) { //just bust the cache for now url = url + "?rnd=" + JsMath.random(); } request.open("GET", url, false); request.send(""); if (request.status == 404) { HtmlContext.alert("Required Content " + url + " cannot be loaded."); throw new JsError("Cannot continue, missing required property file " + url); } parseResult(request.responseText); }
public void ChangeFolderName(string bucket, string oldFolder, string newFolder) { try { string url = nodeUrl + "/folder/rename"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("bucket", bucket); data.Add("oldFolder", oldFolder); data.Add("newFolder", newFolder); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { Maps.Instance.DuradosMap.Logger.Log("hosting", "folder", request.responseText, null, 1, "status: " + request.status); throw new DuradosException(request.responseText); } Dictionary <string, object>[] response = null; try { response = jss.Deserialize <Dictionary <string, object>[]>(request.responseText); } catch (Exception exception) { Maps.Instance.DuradosMap.Logger.Log("hosting", "folder", exception.Source, exception, 1, request.responseText); throw new DuradosException("Could not parse upload response: " + request.responseText + ". With the following error: " + exception.Message, exception); } } catch (Exception exception) { throw new DuradosException("Failed to rename folder", exception); } }
private void CopyS3(string bucketName, int sourceAppId, int targetAppId) { string sourceAppName = Maps.Instance.GetAppNameById(sourceAppId); string destAppName = Maps.Instance.GetAppNameById(targetAppId); string url = GetNodeUrl() + "/copyFolder"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("bucket", bucketName); data.Add("sourceFolder", sourceAppName); data.Add("destFolder", destAppName); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { Maps.Instance.DuradosMap.Logger.Log("Cloner", "CopyS3", request.responseText, null, 1, "status: " + request.status); throw new DuradosException(request.responseText); } Dictionary <string, object>[] response = null; try { response = jss.Deserialize <Dictionary <string, object>[]>(request.responseText); } catch (Exception exception) { Maps.Instance.DuradosMap.Logger.Log("Cloner", "CopyS3", exception.Source, exception, 1, request.responseText); throw new DuradosException("Could not copy folder, response: " + request.responseText + ". With the following error: " + exception.Message); } }
public JsString synchronousFragmentLoad(JsString fragmentURL) { //We need to check to see if we already have this content. If we do not, then we need to load it now and insert it into the DOM var cachedContent = contentCache.getCachedHtmlForUri(fragmentURL); if (cachedContent != null) { return(cachedContent); } //Else load it now var request = new XMLHttpRequest(); request.open("GET", fragmentURL, false); request.send(""); if (request.status == 404) { throw new JsError("Cannot continue, missing required content " + fragmentURL); } return(request.responseText); }
public void Load() { var request = new XMLHttpRequest(); request.open(Method, Url, true); request.responseType = "arraybuffer"; request.onload = e => { var buffer = NewUint8Array(request.response); if (buffer != null) { FireComplete(buffer); } }; request.onerror = e => { Logger.Error("Loading failed: " + e.message); }; request.onprogress = e => { FireProgress(e.loaded, e.total); }; request.send(); }
public static async Task <SoundEffect> FromURL(string url) { var ret = new SoundEffect(); var loaded = false; var request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = XMLHttpRequestResponseType.arraybuffer; request.onload += (a) => { SoundEffectInstance.Context.decodeAudioData(request.response.As <ArrayBuffer>(), (buffer) => { ret._buffer = buffer; loaded = true; }); }; request.send(); while (!loaded) { await Task.Delay(10); } return(ret); }
public void LoadBinaryAsync(string path, Action <byte[]> success, Action <Exception> error) { var xhr = new XMLHttpRequest(); xhr.open("GET", path); xhr.responseType = "arraybuffer"; xhr.onreadystatechange = e => { if (xhr.readyState == 4) { if (xhr.status == 200) { var reader = NewUint8Array(xhr.response); success(reader); } // Error handling else if (xhr.status == 0) { error(new FileLoadException("You are offline!!\n Please Check Your Network.")); } else if (xhr.status == 404) { error(new FileLoadException("Requested URL not found.")); } else if (xhr.status == 500) { error(new FileLoadException("Internel Server Error.")); } else if (xhr.statusText == "parsererror") { error(new FileLoadException("Error.\nParsing JSON Request failed.")); } else if (xhr.statusText == "timeout") { error(new FileLoadException("Request Time out.")); } else { error(new FileLoadException("Unknow Error: " + xhr.responseText)); } } }; xhr.open("GET", path, true); xhr.responseType = "arraybuffer"; // IE fallback if (xhr.responseType != "arraybuffer") { // use VB Loader to load binary array dynamic vbArr = VbAjaxLoader("GET", path); var fileContents = vbArr.toArray(); // decode byte array to string var data = new StringBuilder(); var i = 0; while (i < (fileContents.length - 1)) { data.Append(((char)(fileContents[i]))); i++; } var reader = GetBytesFromString(data.ToString()); success(reader); return; } xhr.send(); }
public virtual void Execute(object controller, Dictionary <string, Parameter> parameters, View view, Dictionary <string, object> values, DataRow prevRow, string pk, string connectionString, int currentUserId, string currentUserRole, IDbCommand command, IDbCommand sysCommand, string actionName, string arn, Durados.Security.Cloud.ICloudCredentials cloudCredentials, bool isLambda) { bool isDebug = IsDebug(values); string url = BaseUrl + "/invokeFunction"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("credentials", cloudCredentials.GetCredentials()); data.Add("cloudProvider", cloudCredentials.GetProvider()); data.Add("method", GetActionMethod()); Dictionary <string, object> payload = GetCallLambdaPayload(controller, parameters, view, values, prevRow, pk, connectionString, currentUserId, currentUserRole, command); string folder = view.Database.GetCurrentAppName(); string functionArn = arn + folder + "_" + view.Name + "_" + actionName; if (isLambda) { functionArn = arn; payload = GetCallLambdaPayloadExternal(controller, parameters, view, values, prevRow, pk, connectionString, currentUserId, currentUserRole, command); foreach (string key in values.Keys) { string stripedKey = key.StripToken(); if (payload.ContainsKey(stripedKey)) { throw new WorkflowEngineException("You can not add " + stripedKey + " parameter in the request body"); } if (key != DebugKey) { payload.Add(stripedKey, values[key]); } } } data.Add("payload", payload); data.Add("function", cloudCredentials.GetFunctionObject(functionArn)); Guid requestId = Guid.NewGuid(); if (isDebug) { if (!System.Web.HttpContext.Current.Items.Contains(JavaScript.GuidKey)) { System.Web.HttpContext.Current.Items.Add(JavaScript.GuidKey, requestId); } else { requestId = (Guid)System.Web.HttpContext.Current.Items[JavaScript.GuidKey]; } string appName = (string)System.Web.HttpContext.Current.Items["appName"]; string username = (string)System.Web.HttpContext.Current.Items["username"]; string token = (string)System.Web.HttpContext.Current.Request.Headers["authorization"]; data.Add("backandRequest", new { id = requestId.ToString(), appName = appName, username = username, accessToken = token }); data.Add("isProduction", false); } else { data.Add("isProduction", true); } request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (IsFunction(view)) { FunctionResponse(request, jss, values, isDebug, requestId); return; } if (request.status != 200) { throw new NodeJsException(request.responseText.TrimStart("{}; ".ToCharArray())); } Dictionary <string, object> response = null; try { response = jss.Deserialize <Dictionary <string, object> >(request.responseText); } catch (Exception exception) { throw new Durados.DuradosException("Could not parse NodeJS response", exception); } if (response.ContainsKey(FunctionError)) { if (response.ContainsKey(Payload)) { var responsePayload = response[Payload]; if (responsePayload is string) { IDictionary <string, object> responsePayloadError = null; try { responsePayloadError = jss.Deserialize <Dictionary <string, object> >((string)responsePayload); } catch { throw new NodeJsException((string)responsePayload); } if (responsePayloadError.ContainsKey(ErrorMessage)) { throw new NodeJsException(responsePayloadError[ErrorMessage].ToString()); } else { throw new NodeJsException((string)responsePayload); } } else { throw new NodeJsException(request.responseText.TrimStart("{}; ".ToCharArray())); } } else { throw new NodeJsException(request.responseText.TrimStart("{}; ".ToCharArray())); } } if (response != null && values != null) { if (isDebug) { HandleLog(response, requestId); } CleanResponse(response); if (!values.ContainsKey(JavaScript.ReturnedValueKey)) { values.Add(JavaScript.ReturnedValueKey, response); } else { values[JavaScript.ReturnedValueKey] = response; } } }
public virtual void ExecuteOld(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, string arn, Durados.Security.Cloud.ICloudCredentials awsCredentials) { const string Payload = "Payload"; const string ErrorMessage = "errorMessage"; bool isDebug = IsDebug(values); string url = BaseUrl + "/callLambda"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); Dictionary <string, object> data = new Dictionary <string, object>(); Dictionary <string, object> payload = GetCallLambdaPayload(controller, parameters, view, values, prevRow, pk, connectionString, currentUsetId, currentUserRole, command); string functionName = view.Name + "_" + actionName; string folder = view.Database.GetCurrentAppName(); data.Add("folder", folder); data.Add("functionName", functionName); data.Add("payload", payload); data.Add("Role", arn); if (isDebug) { if (!System.Web.HttpContext.Current.Items.Contains(JavaScript.GuidKey)) { System.Web.HttpContext.Current.Items.Add(JavaScript.GuidKey, Guid.NewGuid()); } data.Add("getLog", true); } request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); request.send(jss.Serialize(data)); if (request.status != 200) { throw new NodeJsException(request.responseText.TrimStart("{}; ".ToCharArray())); } Dictionary <string, object> response = null; try { response = jss.Deserialize <Dictionary <string, object> >(request.responseText); } catch (Exception exception) { throw new Durados.DuradosException("Could not parse NodeJS response", exception); } if (response.ContainsKey(FunctionError)) { if (response.ContainsKey(Payload)) { var responsePayload = response[Payload]; if (responsePayload is string) { IDictionary <string, object> responsePayloadError = null; try { responsePayloadError = jss.Deserialize <Dictionary <string, object> >((string)responsePayload); } catch { throw new NodeJsException((string)responsePayload); } if (responsePayloadError.ContainsKey(ErrorMessage)) { throw new NodeJsException(responsePayloadError[ErrorMessage].ToString()); } else { throw new NodeJsException((string)responsePayload); } } else { throw new NodeJsException(request.responseText.TrimStart("{}; ".ToCharArray())); } } else { throw new NodeJsException(request.responseText.TrimStart("{}; ".ToCharArray())); } } if (response != null && values != null) { if (isDebug) { //HandleLog(response); } if (!values.ContainsKey(JavaScript.ReturnedValueKey)) { values.Add(JavaScript.ReturnedValueKey, response); } else { values[JavaScript.ReturnedValueKey] = response; } } }
public IHttpActionResult run(int id, bool test = false, bool async = true) { try { if (async && !test) { return(runAsync(id)); } if (!Map.Database.Crons.ContainsKey(id)) { return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, "The Cron " + id + " does not exist"))); } Cron cron = Map.Database.Crons[id]; if (!IsActive(id)) { return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, "The Cron " + id + " is not active. Please switch active to 'ON'"))); } CronRequestInfo cronInfo = GetRequestInfo(cron, test); XMLHttpRequest request = new XMLHttpRequest(); request.open(cronInfo.method, cronInfo.url, false); string appName = Map.AppName; request.setRequestHeader("content-type", "application/json"); if (cronInfo.headers != null) { foreach (string key in cronInfo.headers.Keys) { try { request.setRequestHeader(key, cronInfo.headers[key].ToString()); } catch { } } } System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); string data = cronInfo.data; request.send(data); if (request.status != 200) { Maps.Instance.DuradosMap.Logger.Log("cron", "run", "failed", new Exception(request.responseText), 1, "status: " + request.status); return(ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, request.responseText))); } Maps.Instance.DuradosMap.Logger.Log("cron", "run", "success app " + Map.AppName, null, 3, request.responseText.Length > 4000 ? request.responseText.Substring(0, 4000) : request.responseText); object response = request.responseText; try { response = jss.Deserialize <object>(request.responseText); } catch { } if (test) { return(Ok(new { request = GetTestRequest(cronInfo), response = response })); } else { return(Ok(response)); } } catch (ActionNotFoundException exception) { return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, exception.Message))); } catch (QueryNotFoundException exception) { return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, exception.Message))); } catch (Exception exception) { throw new BackAndApiUnexpectedResponseException(exception, this); } }
public IHttpActionResult Get(int pageNumber = 1, int pageSize = 100, int minutesAgo = 120) { try { if (pageNumber <= 0) { throw new Durados.DuradosException("pageNumber must be larger than 0"); } if (pageSize <= 0) { throw new Durados.DuradosException("pageSize must be larger than 0"); } if (minutesAgo <= 0) { throw new Durados.DuradosException("minutesAgo must be larger than 0"); } if (pageSize > 1000) { return(ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new { Messsage = "pageSize is limited to 1000" }))); } if (minutesAgo > 1200) { return(ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new { Messsage = "minutesAgo is limited to 1200" }))); } pageNumber = pageNumber - 1; Dictionary <string, object> data = new Dictionary <string, object>(); DateTime now = DateTime.UtcNow; var fromTimeEpochTime = GetEpochTime(now.Subtract(new TimeSpan(0, minutesAgo, 0))); var toTimeEpochTime = GetEpochTime(now.Add(new TimeSpan(0, 1, 0))); Debug.WriteLine("now:" + now); Debug.WriteLine("fromTimeEpochTime:" + fromTimeEpochTime); Debug.WriteLine("toTimeEpochTime:" + toTimeEpochTime); data.Add("appName", Map.AppName); data.Add("fromTimeEpochTime", fromTimeEpochTime); data.Add("toTimeEpochTime", toTimeEpochTime); data.Add("offset", pageNumber); data.Add("count", pageSize); string url = BaseUrl + "/lastHourExceptions"; XMLHttpRequest request = new XMLHttpRequest(); request.open("POST", url, false); request.setRequestHeader("content-type", "application/json"); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); string json = jss.Serialize(data); request.send(json); Dictionary <string, object>[] response = null; if (request.status == 200) { try { response = jss.Deserialize <Dictionary <string, object>[]>(request.responseText); } catch (Exception exception) { throw new Durados.DuradosException("Failed to deserialize response " + request.status + ", " + request.responseText, exception); } } else { throw new Durados.DuradosException("Status: " + request.status + ", " + request.responseText); } return(Ok(response)); } catch (Exception exception) { throw new BackAndApiUnexpectedResponseException(exception, this); } }