コード例 #1
0
ファイル: NodeJS.cs プロジェクト: yarivat/Admin
        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);
            }
        }
コード例 #2
0
        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();
        }
コード例 #3
0
        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("");
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: dubhcait/LiftedProxy
        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);
        }
コード例 #5
0
        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);
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        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);
            }
        }
コード例 #8
0
ファイル: NodeJS.cs プロジェクト: yarivat/Admin
        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);
        }
コード例 #9
0
        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();
        }
コード例 #10
0
ファイル: Storage.cs プロジェクト: h7ga40/BlockFactory
 /// <summary>
 /// Callback function for AJAX call.
 /// </summary>
 private static void handleRequest_()
 {
     if (BlocklyStorage.httpRequest_.ReadyState == 4)
     {
         if (BlocklyStorage.httpRequest_.Status != 200)
         {
             BlocklyStorage.alert(BlocklyStorage.HTTPREQUEST_ERROR + "\n" +
                                  "httpRequest_.status: " + BlocklyStorage.httpRequest_.Status);
         }
         else
         {
             var data = BlocklyStorage.httpRequest_.ResponseText.Trim();
             if (BlocklyStorage.httpRequest_.Name == "xml")
             {
                 Window.Location.Hash = data;
                 BlocklyStorage.alert(BlocklyStorage.LINK_ALERT.Replace("%1",
                                                                        Window.Location.Href));
             }
             else if (BlocklyStorage.httpRequest_.Name == "key")
             {
                 if (data.Length == 0)
                 {
                     BlocklyStorage.alert(BlocklyStorage.HASH_ERROR.Replace("%1",
                                                                            Window.Location.Hash));
                 }
                 else
                 {
                     BlocklyStorage.loadXml_(data, (WorkspaceSvg)BlocklyStorage.httpRequest_["workspace"]);
                 }
             }
             BlocklyStorage.monitorChanges_((WorkspaceSvg)BlocklyStorage.httpRequest_["workspace"]);
         }
         BlocklyStorage.httpRequest_ = null;
     }
 }
コード例 #11
0
 /// <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 });
     }
 }
コード例 #12
0
 public TargetsService(XMLHttpRequest xmlHttpRequest, ServiceConfig config, TargetsParser targets)
     : base(xmlHttpRequest)
 {
     this.config  = config;
     this.targets = targets;
     this.url     = "assets/data/targets.txt";
 }
コード例 #13
0
ファイル: CronHelper.cs プロジェクト: yarivat/Admin
        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);
        }
コード例 #14
0
        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));
コード例 #15
0
ファイル: JS.cs プロジェクト: Zaid-Ajaj/Bridge.Ractive
        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);
        }
コード例 #16
0
ファイル: App.cs プロジェクト: My-Bridge-NET-Sample/MusicGame
        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);
        }
コード例 #17
0
        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();
        }
コード例 #18
0
        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();
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        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);
            }
        }
コード例 #21
0
        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);
        }
コード例 #22
0
        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)
        }
コード例 #23
0
            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);
            }
コード例 #24
0
        /// <summary>
        /// Gets a value indicating if a response has any text.
        /// </summary>
        /// <param name="response">The response object.</param>
        /// <returns>True if the response was successful and has text.</returns>
        public static bool HasResponse(this XMLHttpRequest response)
        {
            if (response.status != 200)
            {
                return(false);
            }

            if (!(dynamic)response.responseText)
            {
                return(false);
            }

            return(true);
        }
コード例 #25
0
ファイル: filesController.cs プロジェクト: yarivat/Admin
        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);
            }
        }
コード例 #26
0
ファイル: TreeStateStore.cs プロジェクト: wischi-chr/ZenTuree
        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);
        }
コード例 #27
0
ファイル: N3384.cs プロジェクト: zwmyint/Bridge
        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();
        }
コード例 #28
0
ファイル: DropdownSample.cs プロジェクト: gitter-badger/h5
        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);
                    }
                }
            }
        }
コード例 #29
0
        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();
        }
コード例 #30
0
ファイル: babylon.tools.cs プロジェクト: ARLM-Attic/babylon
 /// <summary>
 /// </summary>
 /// <param name="xhr">
 /// </param>
 /// <param name="dataType">
 /// </param>
 /// <returns>
 /// </returns>
 /// <exception cref="NotImplementedException">
 /// </exception>
 public static bool ValidateXHRData(XMLHttpRequest xhr, int dataType = 7)
 {
     /*
      * try
      * {
      *  if ((dataType & 1) > 0)
      *  {
      *      if (xhr.responseText != null && xhr.responseText.Length > 0)
      *      {
      *          return true;
      *      }
      *      else
      *          if (dataType == 1)
      *          {
      *              return false;
      *          }
      *  }
      *  if ((dataType & 2) > 0)
      *  {
      *      var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
      *      if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0)
      *      {
      *          return true;
      *      }
      *      else
      *          if (dataType == 2)
      *          {
      *              return false;
      *          }
      *  }
      *  if ((dataType & 4) > 0)
      *  {
      *      var ddsHeader = new Uint8Array(xhr.response, 0, 3);
      *      if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83)
      *      {
      *          return true;
      *      }
      *      else
      *      {
      *          return false;
      *      }
      *  }
      * }
      * catch (Exception e) { }
      * return false;
      */
     throw new NotImplementedException();
 }
コード例 #31
0
ファイル: Controller.cs プロジェクト: davelondon/dontstayin
		void gotCalendar(string data, string textStatus, XMLHttpRequest req, string args)
		{
			
			int requestIdFromArgs = int.ParseInvariant((string)args);
			if (requestId == requestIdFromArgs)
			{
				loadId++;
				view.CalendarHolder.InnerHTML = data;
				view.CalendarHolderOuter.Style.Display = "";
				view.CalendarLoadingOverlay.Style.Display = "none";
				view.LoadingLabel.Style.Display = "none";
				view.MonthLabel.Style.Display = "";
			}
		}
コード例 #32
0
ファイル: Global.cs プロジェクト: hultqvist/SharpKit-SDK
        //*** 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
                }

                //***************************************
            }
        }
コード例 #33
0
ファイル: Controller.cs プロジェクト: davelondon/dontstayin
		void gotCalendar(string data, string textStatus, XMLHttpRequest req, string args)
		{
			
			int requestIdFromArgs = int.ParseInvariant((string)args);
			if (requestId == requestIdFromArgs)
			{
				//Debug("gotCalendar data.Length = " + data.Length.ToString() + ", args = " + (args == null ? "null" : args.ToString()) + " (processing)");
				loadId++;
				view.CalendarHolder.InnerHTML = data;
				view.CalendarHolderOuter.Style.Display = "";
				view.CalendarLoadingOverlay.Style.Display = "none";
				view.LoadingLabel.Style.Display = "none";
				view.MonthLabel.Style.Display = "";
			}
			//else
			//	Debug("gotCalendar data.Length = " + data.Length.ToString() + ", args = " + (args == null ? "null" : args.ToString()) + " (skipping)");
		}
コード例 #34
0
ファイル: Controller.cs プロジェクト: davelondon/dontstayin
		void gotContent(string data, string textStatus, XMLHttpRequest req, string args)
		{
			int requestIdFromArgs = int.ParseInvariant((string)args);
			if (requestId == requestIdFromArgs)
			{
				loadId++;
				view.Result.InnerHTML = data;
				view.ResultOuter.Style.Display = "";
				view.LoadingOverlay.Style.Display = "none";
			}
		}