Esempio n. 1
0
        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);
            }
        }
Esempio n. 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();
        }
Esempio n. 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("");
        }
Esempio n. 4
0
        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);
        }
Esempio n. 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);
        }
Esempio n. 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);
        }
Esempio n. 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);
            }
        }
Esempio n. 8
0
        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);
        }
Esempio n. 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();
        }
Esempio n. 10
0
 /// <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;
     }
 }
Esempio n. 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 });
     }
 }
 public TargetsService(XMLHttpRequest xmlHttpRequest, ServiceConfig config, TargetsParser targets)
     : base(xmlHttpRequest)
 {
     this.config  = config;
     this.targets = targets;
     this.url     = "assets/data/targets.txt";
 }
Esempio n. 13
0
        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);
        }
Esempio n. 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));
Esempio n. 15
0
        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);
        }
Esempio n. 16
0
        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);
        }
Esempio n. 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();
        }
Esempio n. 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();
        }
        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);
        }
Esempio n. 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);
            }
        }
Esempio n. 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);
        }
        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)
        }
Esempio n. 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);
            }
Esempio n. 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);
        }
Esempio n. 25
0
        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);
            }
        }
Esempio n. 26
0
        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);
        }
Esempio n. 27
0
        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();
        }
Esempio n. 28
0
        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);
                    }
                }
            }
        }
Esempio n. 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();
        }
Esempio n. 30
0
 /// <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();
 }
Esempio n. 31
0
		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 = "";
			}
		}
Esempio n. 32
0
        //*** 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
                }

                //***************************************
            }
        }
Esempio n. 33
0
		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)");
		}
Esempio n. 34
0
		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";
			}
		}