public static async Task <TResult> PostJsonAsync <TData, TResult>(PostAsyncConfig <TData> config) { var tcs = new TaskCompletionSource <TResult>(); var xmlHttp = new XMLHttpRequest(); xmlHttp.Open("POST", config.Url, true); xmlHttp.OnReadyStateChange = () => { if (xmlHttp.ReadyState == AjaxReadyState.Done) { if (xmlHttp.Status == 200 || xmlHttp.Status == 304) { var result = JSON.Parse(xmlHttp.ResponseText); tcs.SetResult(Script.Write <TResult>("result")); } else { tcs.SetException(new Exception(xmlHttp.StatusText)); } } }; var stringified = JSON.Stringify(config.Data); xmlHttp.Send(stringified); return(await tcs.Task); }
public void LoadSoundFontFromUrl(string data) { var url = data.As <string>(); Logger.Info("AlphaSynth", "Start loading Soundfont from url " + url); var request = new XMLHttpRequest(); request.Open("GET", url, true); request.ResponseType = XMLHttpRequestResponseType.ARRAYBUFFER; request.OnLoad = (Action <Event>)(e => { var buffer = new Uint8Array(request.Response); _synth.PostMessage(new { cmd = AlphaSynthWebWorker.CmdLoadSoundFontBytes, data = buffer.As <byte[]>() }); }); request.OnError = (Action <Event>)(e => { Logger.Error("AlphaSynth", "Loading failed: " + e.Member <string>("message")); TriggerEvent("soundFontLoadFailed"); }); request.OnProgress = (Action <Event>)(e => { Logger.Debug("AlphaSynth", "Soundfont downloading: " + e.Member <int>("loaded") + "/" + e.Member <int>("total") + " bytes"); TriggerEvent("soundFontLoad", new object[] { new { loaded = e.Member <int>("loaded"), total = e.Member <int>("total") } }); }); request.Send(); }
public static Task <T> FetchJson <T>(string path, Dictionary <string, string> args = null) where T : class { var tcs = new TaskCompletionSource <T>(); var req = new XMLHttpRequest(); req.Open("GET", path + (args != null ? "?" + EncodeUriComponents(args) : "")); req.OnReadyStateChange = () => { if (req.ReadyState != AjaxReadyState.Done) { return; } try { if (req.Status == 200) { tcs.SetResult(JsonConvert.DeserializeObject <T>(req.ResponseText)); } else { tcs.SetException(new Exception("Response code does not indicate success: " + req.StatusText)); } } catch (Exception e) { tcs.SetException(e); } }; req.Send(); return(tcs.Task); }
private static object PostJsonSync(string url, Type returnType, object[] data) { var xmlHttp = new XMLHttpRequest(); xmlHttp.Open("POST", url, false); var serialized = Json.Serialize(data); xmlHttp.Send(serialized); if (xmlHttp.Status == 200 || xmlHttp.Status == 304) { var json = JSON.Parse(xmlHttp.ResponseText); if (Script.IsDefined(json["$exception"]) && json["$exception"].As <bool>()) { throw new Exception(json["$exceptionMessage"].As <string>()); } else { var result = Json.Deserialize(xmlHttp.ResponseText, returnType); return(result); } } else { throw new Exception("Error: " + xmlHttp.StatusText + "\n" + xmlHttp.ResponseText); } }
public async static System.Threading.Tasks.Task <string> httpPost(string url, string username, string token, File file) { Bridge.Html5.XMLHttpRequest _http = new XMLHttpRequest(); _http.Open("post", url, true); string returnv = ""; _http.OnReadyStateChange = () => { if (_http.ReadyState == AjaxReadyState.Done) { returnv = _http.ResponseText; } }; FormData formdata = new FormData(); formdata.Append(file.Name, file); formdata.Append("user", username); formdata.Append("token", token); _http.Send(formdata); while (_http.ReadyState != AjaxReadyState.Done) { await System.Threading.Tasks.Task.Delay(100); } return(returnv); }
public static async Task <string> GetAsync(string url) { var tcs = new TaskCompletionSource <string>(); var xmlHttp = new XMLHttpRequest(); xmlHttp.Open("GET", url, true); xmlHttp.SetRequestHeader("Content-Type", "application/json"); xmlHttp.OnReadyStateChange = () => { if (xmlHttp.ReadyState == AjaxReadyState.Done) { if (xmlHttp.Status == 200 || xmlHttp.Status == 304) { tcs.SetResult(xmlHttp.ResponseText); } else { tcs.SetException(new Exception(xmlHttp.ResponseText)); } } }; xmlHttp.Send(); return(await tcs.Task); }
static void HttpRequest(string url, Action <Uint8Array> CallBack, string partName) { XMLHttpRequest req = new XMLHttpRequest(); req.ResponseType = XMLHttpRequestResponseType.ArrayBuffer; req.OnReadyStateChange = () => { if (req.ReadyState != AjaxReadyState.Done) { return; } ArrayBuffer DownloadRes = req.Response as ArrayBuffer; if (DownloadRes == null) { endWithError(partName + " download failed, check the url"); return; } var arr = new Uint8Array(DownloadRes); DownloadRes = null; if (arr.Length == 0) { endWithError(string.Format(DwnErr, partName)); return; } CallBack(arr); }; req.Open("GET", url, true); req.Send(); }
public static Task <string> ReuseMediaAssetIdOrHttpGet(string urlToGet, IStorage storage, string variableName) => Task.FromPromise <string>(new TypeSafePromise <string>((onSucc, onFail) => { var result = storage.GetStringOrNull(variableName); if (result != null && HasMediaAsset(result)) { Logger.Debug(typeof(IawAppApi), "ReuseMediaAssetOrFetch={0} is reusable", result); onSucc(result); return; } Logger.Debug(typeof(IawAppApi), "ReuseMediaAssetOrFetch={0} is not usable", result); var req = new XMLHttpRequest(); req.Open("GET", urlToGet, true); req.ResponseType = XMLHttpRequestResponseType.ArrayBuffer; req.OnLoad = async ev => { var content = new Uint8Array(req.Response).ToString(); result = await RegisterMediaAsset(content); storage.Set(variableName, result); Logger.Debug(typeof(IawAppApi), "ReuseMediaAssetOrFetch registered {0}", result); onSucc(result); }; req.Send(string.Empty); }), (Func <string, string>)(x => x));
static string HttpGet(string theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.Open("GET", theUrl, false); // false for synchronous request xmlHttp.ToDynamic().send(null); return(xmlHttp.ResponseText); }
static void BeginLoadRom(string rom) { var req = new XMLHttpRequest(); req.ResponseType = XMLHttpRequestResponseType.ArrayBuffer; req.Open("GET", rom); req.OnLoad = e => EndLoadRom(GetResponseAsByteArray(req)); req.Send(); }
public void Load(string url) { if (Loaded) { Console.WriteLine("Already loaded resources!"); return; } var request = new XMLHttpRequest(); request.OnReadyStateChange = () => { if (request.ReadyState != AjaxReadyState.Done) { return; } if ((request.Status == 200) || (request.Status == 304)) { var jsonResources = JSON.Parse(request.Response.ToString()).As <JSONResources>(); if (jsonResources == null) { throw new ArgumentNullException(nameof(jsonResources)); } var total = jsonResources.Audio.Count() + jsonResources.Image.Count(); var amountLoaded = 0; jsonResources.Audio.ForEach(_ => Audio.Add(_.Title, new HTMLAudioElement() { Src = _.Src, OnLoadedData = (e) => { amountLoaded++; if (amountLoaded == total) { Loaded = true; } } })); jsonResources.Image.ForEach(_ => Images.Add(_.Title, new HTMLImageElement() { Src = _.Src, OnLoad = (e) => { amountLoaded++; if (amountLoaded == total) { Loaded = true; } } })); } }; request.Open("GET", url); request.Send(); }
public static void addArduinoLightBox(HTMLBoxStructure parent, string text, string url, string json = null) { HTMLBox box = new HTMLBox(text); box.Action(delegate { Action <Event> actionError = delegate(Event e) { Bridge.Console.Error("Error", e); box.Color(error, 1000); }; Action <Event> actionSucces = delegate(Event e) { Bridge.Console.Info("Succes", e); box.Color(succes, 1000); Vibrate(250); }; XMLHttpRequest request = new XMLHttpRequest(); if (json != null) { request.Open("POST", url, true); request.SetRequestHeader("Content-Type", "application/json"); request.Timeout = 1250; request.Send(json); } else { request.Open("GET", url, true); request.Timeout = 1250; request.Send(); } request.OnTimeout += actionError; request.OnAbort += actionError; request.OnError += actionError; request.OnLoad += (Event e) => { if (request.ResponseText.Contains("Geaccepteerd")) { actionSucces(e); } else { actionError(e); } }; }); parent.addBox(box); }
public void Then( Delegate fulfilledHandler, Delegate errorHandler = null, Delegate progressHandler = null) { var req = new XMLHttpRequest(); req.OnReadyStateChange = () => { if (req.ReadyState != AjaxReadyState.Done) { return; } if (req.Status >= 200 && req.Status < 400) { Logger.Debug(GetType(), "upload success"); fulfilledHandler?.Call(null, ResultHolder <XMLHttpRequest> .CreateSuccess(req)); return; } Logger.Debug(GetType(), "upload error"); fulfilledHandler?.Call( null, ResultHolder <XMLHttpRequest> .CreateFailure(req.ResponseText, null, req)); }; req.Open(_method, _url, true); req.SetRequestHeader("Cache-Control", "no-cache"); req.SetRequestHeader("Pragma", "no-cache"); var tzOffset = Script.Eval <string>("new Date().getTimezoneOffset() + \"\""); req.SetRequestHeader(Philadelphia.Common.Model.Magics.TimeZoneOffsetFieldName, tzOffset); try { var tzCode = Script.Eval <object>("Intl.DateTimeFormat().resolvedOptions().timeZone"); if (Script.IsDefined(tzCode)) { req.SetRequestHeader(Philadelphia.Common.Model.Magics.TimeZoneCodeFieldName, tzCode.ToString()); } } catch (Exception) { //most likely it is unsupported Logger.Error(GetType(), "could not determine timeZone"); } if (CsrfToken != null) { req.SetRequestHeader(Philadelphia.Common.Model.Magics.CsrfTokenFieldName, CsrfToken); } if (_frmData != null) { req.Send(_frmData); } else { req.Send(_dataToPost); } }
public static string loadDoc(string url, Action onReadyStateChange = null) { XMLHttpRequest doc = new XMLHttpRequest(); doc.Open("GET", url, false); if (onReadyStateChange != null) { doc.OnReadyStateChange += onReadyStateChange; } doc.Send(); return(doc.ResponseText); }
public static void Open(string ArchiveFile, Action <JSONArchive> action) { XMLHttpRequest XHR = new XMLHttpRequest(); //XHR.ResponseType = XMLHttpRequestResponseType.Blob; XHR.OnLoad = Evt => { action(new JSONArchive(XHR.ResponseText)); }; XHR.Open("GET", ArchiveFile, false); XHR.Send(); //if (XHR.Status) }
public static void TestProgressEventType() { var xhr = new XMLHttpRequest(); var done = Assert.Async(); xhr.OnLoadEnd = ev => { Assert.AreEqual(typeof(ulong), ((ProgressEvent)ev).Loaded.GetType(), "ProgressEvent.Loaded is ulong."); Assert.AreEqual(typeof(ulong), ((ProgressEvent)ev).Total.GetType(), "ProgressEvent.Total is ulong."); done(); }; xhr.Open("GET", "/"); xhr.Send(); }
public void Send(TSend obj) { var xhr = new XMLHttpRequest(); xhr.Open("POST", this.url); xhr.OnReadyStateChange = () => { if (xhr.ReadyState == XMLHttpRequestReadyState.Done) { var data = xhr.RecvJson <TRecv>(); this.onRecv(data); } }; xhr.SendJson(obj); }
public Task <HttpResponse> SetAsync(string token, string value) { var url = GetUrlWithToken(token); var xhr = new XMLHttpRequest(); xhr.Open("POST", url); var source = GetCompletionSourceForRequest(xhr); xhr.Send(value); return(source.Task); }
private void tryLoadChildFromServer() { var req = new XMLHttpRequest(); req.OnReadyStateChange = () => { if (req.ReadyState == AjaxReadyState.Done && req.Status == 200) { var loader = new XamlReader(); this.child = loader.Parse(req.ResponseText); } }; req.Open("GET", this.typename.Replace(".", "/") + ".xml", true); req.Send(); }
public static void UpdateButton_Click(Event e) { var request = new XMLHttpRequest(); Action <Event> onLoad = delegate { var val = JSON.Parse <string>(request.ResponseText); var dateTime = DateTime.Parse(val); Document.GetElementById <InputElement>("dateTimeInput").Value = dateTime.ToString("yyyy-MM-dd hh:mm:ss"); }; request.OnLoad = onLoad; request.Open("GET", Config.GET_SERVER_TIME_URL + "?" + DateTime.Now.GetTime(), true); request.Send(); }
public static Task <GitHubUser[]> GetNextUsers() { var tcs = new TaskCompletionSource <GitHubUser[]>(); var req = new XMLHttpRequest(); req.ResponseType = XMLHttpRequestResponseType.Json; req.Open("GET", "https://api.github.com/users?since=" + LastUserId); req.OnLoadEnd += e => { var users = (GitHubUser[])req.Response; LastUserId += users.Length; tcs.SetResult(users); }; req.Send(); return(tcs.Task); }
internal static Task <ArrayBuffer> ReadBytesAsync(string path) { var tcs = new TaskCompletionSource <ArrayBuffer>(); if (Script.IsNode) { var fs = Script.Write <dynamic>(@"require(""fs"")"); fs.readFile(path, new Action <object, ArrayBuffer>((err, data) => { if (err != null) { throw new IOException(); } tcs.SetResult(data); })); } else { var req = new XMLHttpRequest(); req.Open("GET", path, true); req.OverrideMimeType("text/plain; charset=binary-data"); req.Send(null); req.OnReadyStateChange = () => { if (req.ReadyState != 4) { return; } if (req.Status != 200) { throw new IOException($"Status of request to {path} returned status: {req.Status}"); } string text = req.ResponseText; var resultArray = new Uint8Array(text.Length); text.ToCharArray().ForEach((v, index, array) => resultArray[index] = (byte)(v & byte.MaxValue)); tcs.SetResult(resultArray.Buffer); }; } return(tcs.Task); }
public static void loadText(string url, Action <string, Bridge.Error> fun) { var req = new XMLHttpRequest();//ness req.Open("GET", url); req.OnReadyStateChange = () => { if (req.ReadyState == Bridge.Html5.AjaxReadyState.Done) { fun(req.ResponseText, null); } }; req.OnError = (e) => { var err = new Bridge.Error(); err.Message = "onerr in req:"; fun(null, err); //ness }; req.Send(); }
private string loadTextFileAjaxSync(string filePath, string mimeType) { var xmlhttp = new XMLHttpRequest(); xmlhttp.Open("GET", filePath, false); if (mimeType != null) { xmlhttp.OverrideMimeType(mimeType); } xmlhttp.Send(); if (xmlhttp.Status == 200) { return(xmlhttp.ResponseText); } else { // TODO Throw exception return(null); } }
static async Task <object> PostJsonAsync(string url, Type returnType, object[] parameters) { var tcs = new TaskCompletionSource <object>(); var xmlHttp = new XMLHttpRequest(); xmlHttp.Open("POST", url, true); xmlHttp.SetRequestHeader("Content-Type", "application/json"); xmlHttp.OnReadyStateChange = () => { if (xmlHttp.ReadyState == AjaxReadyState.Done) { if (xmlHttp.Status == 200 || xmlHttp.Status == 304) { var json = JSON.Parse(xmlHttp.ResponseText); if (json == null) { tcs.SetResult(null); } else if (Script.IsDefined(json["$exception"]) && json["$exception"].As <bool>()) { tcs.SetException(new Exception(json["$exceptionMessage"].As <string>())); } else { var result = Json.Deserialize(xmlHttp.ResponseText, returnType); tcs.SetResult(result); } } else { tcs.SetException(new Exception(xmlHttp.ResponseText)); } } }; var serialized = Json.Serialize(parameters); xmlHttp.Send(serialized); return(await tcs.Task); }
static void Main(string[] args) { Charachter[] charachters; string jsonUrl = "http://hp-api.herokuapp.com/api/characters"; XMLHttpRequest jsonData = new XMLHttpRequest(); jsonData.Open(XMLHttpRequest.EnumMethod.Get, jsonUrl); jsonData.Send(); using (StreamReader streamReader = new StreamReader(jsonData.ResponseStream)) { string jsonFile = streamReader.ReadToEnd(); var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "dd-MM-yyyy" }; charachters = JsonConvert.DeserializeObject <Charachter[]>(jsonFile, dateTimeConverter); } }
public async Task <HttpResponse> NewAsync() { var url = GetUrlWithToken("new"); var xhr = new XMLHttpRequest(); xhr.Open("POST", url); var source = GetCompletionSourceForRequest(xhr); xhr.Send(); var resp = await source.Task; if (resp.StatusCode != 200) { return(resp); } return(new HttpResponse(200, GetTokenFromUrl(resp.Content))); }
public async static System.Threading.Tasks.Task <string> httpGet(string url) { Bridge.Html5.XMLHttpRequest _http = new XMLHttpRequest(); _http.Open("get", url, true); string returnv = ""; _http.OnReadyStateChange = () => { if (_http.ReadyState == AjaxReadyState.Done) { returnv = _http.ResponseText; } }; _http.Send(); while (_http.ReadyState != AjaxReadyState.Done) { await System.Threading.Tasks.Task.Delay(100); } return(returnv); }
public static void Get(GetConfig config) { var http = new XMLHttpRequest(); http.Open("GET", config.Url, true); http.SetRequestHeader("Content-Type", "application/json"); http.OnReadyStateChange = () => { if (http.ReadyState == AjaxReadyState.Done && http.Status == 200) { config.Success(http.ResponseText); } if (http.Status == 500 || http.Status == 404) { config.Error(); } }; http.Send(); }
public static void HttpRequest(string url, Action <string> CallBack, string partName) { XMLHttpRequest req = new XMLHttpRequest(); req.ResponseType = XMLHttpRequestResponseType.String; req.OnReadyStateChange = () => { if (req.ReadyState != AjaxReadyState.Done) { return; } string DownloadRes = req.Response as string; if (DownloadRes == null || DownloadRes.Length == 0) { endWithError(string.Format(DwnErr, partName)); return; } CallBack(DownloadRes); }; req.Open("GET", url, true); req.Send(); }
//*** Device Ready Code ******************* //This event handler is fired once the AppMobi libraries are ready public static void DeviceReady(XdkDeviceEvent evt) { //use AppMobi viewport Xdk.display.UseViewport(iPortraitWidth, iLandscapeWidth); //lock orientation Xdk.device.SetRotateOrientation(XdkDeviceOrientation.Portrait); Xdk.device.SetAutoRotate(false); //manage power Xdk.device.ManagePower(true, false); try { //for playing podcasts Xdk.OnPlayerAudioStop += OnPodcastComplete; Xdk.OnPlayerAudioError += OnPodcastError; } catch (JsError e) { } //hide splash screen Xdk.device.HideSplashScreen(); if (Xdk.device.appmobiVersion != "3.2.4") { Xdk.device.GetRemoteData(podcastRSSURL, GetPost.GET, "", "DataLoaded", "DataFailed"); } else { //********* Use XMLHTTP on an error *************** try { XMLHttpRequest xmlhttp = new XMLHttpRequest(); // instantiate it xmlhttp.OnReadyStateChange += delegate(XMLHttpRequestEvent evt_delegate) { if (xmlhttp.readyState == XMLHttpRequestState.DONE) { if (xmlhttp.status == 200 || xmlhttp.responseText != "") { //XML file read, now parse it DataLoaded(xmlhttp.responseText); } } }; try { xmlhttp.Open(GetPost.GET, podcastRSSURL); // open server interface } catch (JsError err) { Alert("XMLHttpRequest.open() failed.\n" + err.message + " \n URL : " + podcastRSSURL); //Permission Denied return; } xmlhttp.Send(@null as JsString); } catch (JsError err) { Alert("Error initializing XMLHttpRequest.\n" + err); // show error } //*************************************** } }