private WebRequestResult <AirportDataThumbnailsJson> RequestThumbnails(string icao, string registration, int maxThumbnails)
        {
            var requestUrl = String.Format("http://www.airport-data.com/api/ac_thumb.json?m={0}&r={1}&n={2}", HttpUtility.UrlEncode(icao), HttpUtility.UrlEncode(registration ?? ""), maxThumbnails);
            var request    = HttpWebRequest.Create(requestUrl);

            request.Timeout = ThumbnailTimeout;

            var result = new WebRequestResult <AirportDataThumbnailsJson>();

            try {
                using (var response = (HttpWebResponse)WebRequestHelper.GetResponse(request)) {
                    result.HttpStatusCode = response.StatusCode;
                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        using (var responseStream = WebRequestHelper.GetResponseStream(response)) {
                            var deserialiser = new DataContractJsonSerializer(typeof(AirportDataThumbnailsJson));
                            result.Result = (AirportDataThumbnailsJson)deserialiser.ReadObject(responseStream);
                        }
                    }
                }
            } catch (WebException ex) {
                var webResponse = ex.Response as HttpWebResponse;
                if (webResponse != null)
                {
                    result.HttpStatusCode = webResponse.StatusCode;
                }
                else
                {
                    throw;
                }
            }

            return(result);
        }
示例#2
0
        IEnumerator WebRequestGet <T>(string _uri, int _timeOut, WebRequestCallBack _timeOutCallBack) where T : WebRequestResult
        {
            _timeOutCallBack("");
            UnityWebRequest request = UnityWebRequest.Get(_uri);

            AsyncOperation res = request.SendWebRequest();

            int cnt = 0;

            while (!res.isDone)
            {
                cnt++;
                if (cnt > _timeOut)
                {
                    _timeOutCallBack(TIME_OUT);
                    yield break;
                }

                yield return(new WaitForSecondsRealtime(0.2f));
            }

            if (!request.isNetworkError)
            {
                string html = request.downloadHandler.text;
                DebugLogMain.hLog(html);
                result = JsonUtility.FromJson <T>(html);
            }
            else
            {
            }


            _timeOutCallBack(request.downloadHandler.text);
        }
示例#3
0
        public void WebRequestResult_Full_Constructor_Initialises_To_Known_Values()
        {
            var request = new WebRequestResult <string>(HttpStatusCode.OK, "Hello");

            Assert.AreEqual(HttpStatusCode.OK, request.HttpStatusCode);
            Assert.AreEqual("Hello", request.Result);
        }
示例#4
0
        public void WebRequestResult_Default_Constructor_Initialises_To_Known_Values_And_Properties_Work()
        {
            var request = new WebRequestResult <string>();

            TestUtilities.TestProperty(request, r => r.HttpStatusCode, HttpStatusCode.NoContent, HttpStatusCode.OK);
            TestUtilities.TestProperty(request, r => r.Result, null, "Hello");
        }
示例#5
0
        /// <summary>
        /// Returns a <see cref="WebRequestResult{T}"/> pre-populated with the <see cref="HttpWebResponse"/> information
        /// </summary>
        /// <typeparam name="TResponse">The type of response to create</typeparam>
        /// <param name="serverResponse">The server response</param>
        /// <returns></returns>
        public static WebRequestResult <TResponse> CreateWebRequestResult <TResponse>(this HttpWebResponse serverResponse)
        {
            // Return a new web request result
            var result = new WebRequestResult <TResponse>
            {
                // Content type
                ContentType = serverResponse.ContentType,

                // Headers
                Headers = serverResponse.Headers,

                // Cookies
                Cookies = serverResponse.Cookies,

                // Status code
                StatusCode = serverResponse.StatusCode,

                // Status description
                StatusDescription = serverResponse.StatusDescription,
            };

            // If we got a successful response...
            if (result.StatusCode == HttpStatusCode.OK)
            {
                // Open the response stream...
                using (var responseStream = serverResponse.GetResponseStream())
                    // Get a stream reader...
                    using (var streamReader = new StreamReader(responseStream))
                        // Read in the response body
                        result.RawServerResponse = streamReader.ReadToEnd();
            }

            return(result);
        }
        /// <summary>
        /// Cheks the web requsts for any errors, displaying them if there are any
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="result"></param>
        /// <returns>Return true if there was an error</returns>
        public static async Task <bool> DisplayErrorIfFailedAsync <T>(this WebRequestResult <T> result, string title)
        {
            if (result == null || result.ServerResponse == null || !result.Successfull)
            {
                var message = "Unknown error from server call";

                if (result.ServerResponse != null)
                {
                    message = result.ErrorMessage;
                }

                else if (!string.IsNullOrWhiteSpace(result?.RawServerResponse))
                {
                    message = $"Unexpected response from server. {result.RawServerResponse}";
                }

                else if (result != null)
                {
                    message = $"Failed to communicate with server. Status code {result.StatusCode}. {result.StatusDescription}";
                }


                await IoC.UI.ShowMessage(new MessageBoxDialogViewModel
                {
                    Title   = title,
                    Message = message
                });

                return(true);
            }
            return(false);
        }
示例#7
0
 static void WebRequestFinished(WebRequestResult callback, WebRequestResultType resultType, string result)
 {
     if (callback != null)
     {
         WorldManager.Instance.TimerMgr.AddOnce(0, delegate()
         {
             callback(resultType, result);
         });
     }
 }
        /// <summary>
        /// Checks the web request result for any errors, displaying them if there are any,
        /// or if we are unauthorized automatically logging us out
        /// </summary>
        /// <typeparam name="T">The type of Api Response</typeparam>
        /// <param name="response">The response to check</param>
        /// <param name="title">The title of the error dialog if there is an error</param>
        /// <returns>Returns true if there was an error, or false if all was OK</returns>
        public static async Task <bool> HandleErrorIfFailedAsync(this WebRequestResult response, string title = "System Error")
        {
            // If there was no response, bad data, or a response with a error message...
            if (response == null || response.ServerResponse == null || (response.ServerResponse as ApiResponse)?.Successful == false)
            {
                // Default error message
                // TODO: Localize strings
                var message = "Unknown error from server call";

                // If we got a response from the server...
                if (response?.ServerResponse is ApiResponse apiResponse)
                {
                    // Set message to servers response
                    message = apiResponse.ErrorMessage;
                }
                // If we have a result but deserialize failed...
                else if (!string.IsNullOrWhiteSpace(response?.RawServerResponse))
                {
                    // Set error message
                    message = $"Unexpected response from server. {response.RawServerResponse}";
                }
                // If we have a result but no server response details at all...
                else if (response != null)
                {
                    // Set message to standard HTTP server response details
                    message = response.ErrorMessage ?? $"Server responded with {response.StatusDescription} ({response.StatusCode})";
                }

                // If this is an unauthorized response...
                if (response?.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    // Log it
                    Logger.LogInformationSource("Logging user out due to unauthorized response from server");

                    // Automatically log the user out
                    //await ViewModelSettings.LogoutAsync();
                }
                else
                {
                    // Display error
                    await UI.ShowMessage(new MessageBoxDialogViewModel
                    {
                        // TODO: Localize strings
                        Title   = title,
                        Message = message
                    });
                }

                // Return that we had an error
                return(true);
            }

            // All was OK, so return false for no error
            return(false);
        }
        public string SubmitUrl(string url)
        {
            WebRequestResult result = WebRequestHelper.SendRequest(url, 10000);

            if (result.IsSuccess)
            {
                return(result.ResponseText);
            }
            else
            {
                return(result.ErrorMessage);
            }
        }
示例#10
0
        public async Task <WebRequestResult> PostMessage(IEnumerable <SendMessage> messages, string channel)
        {
            WebRequestResult response = null;

            foreach (var message in messages)
            {
                response = await PostMessage(message, channel);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    break;
                }
            }

            return(response);
        }
        /// <summary>
        /// Checks the web request result for any errors, displaying them if there are any
        /// </summary>
        /// <typeparam name="T">The type of Api Response</typeparam>
        /// <param name="response">The response to check</param>
        /// <returns>Returns true if there was an error, or false if all was ok</returns>
        public static bool DisplayErrorIfFailedAsync(this WebRequestResult response, string errorMessage = null)
        {
            // If there was no response, bad data or a response with a error message
            if (response == null || response.ServerResponse == null || (response.ServerResponse as ApiResponse)?.Successful == false)
            {
                // Default error message
                // TODO: Localize strings
                var message = "Unknown error from server call";

                // If we got a response from the server
                if (response?.ServerResponse is ApiResponse apiResponse)
                {
                    // Set message to servers response
                    message = apiResponse.ErrorMessage;
                }

                // If we have a result but deserialize failed
                else if (string.IsNullOrWhiteSpace(response?.RawServerResponse))
                {
                    // Set error message
                    message = $"Unexpected response from server. {response?.RawServerResponse}";
                }

                // If we have a result but no server response details at all...
                else if (response != null)
                {
                    // Set message to standard HTTP server response details
                    message = response.ErrorMessage ?? $"{response.StatusCode}. ({response.StatusDescription})";
                }

                // Display error
                //TODO: Localize string
                if (response != null)
                {
                    response.ErrorMessage = errorMessage != null
                        ? $"{errorMessage} - {message}."
                        : $"{message}.";
                }

                // Enough failures
                return(true);
            }

            return(false);
        }
示例#12
0
    // Update is called once per frame
    //void Update () {}

    IEnumerator GetTest()
    {
        yield return(null);

        WebRequestResult result = null;


        yield return(webServiceObj.Get <IdFormat>("http://chanel.ndm.tw/api/getid.ashx", result, 1000, tempCallBack));

        if (result != null)
        {
            DebugLogMain.hLog(((IdFormat)result).KEY);
        }
        else
        {
            DebugLogMain.hLog("error: " + ((IdFormat)webServiceObj.result).KEY);
        }
    }
示例#13
0
        /// <summary>
        /// Checks the web request for any errors, displaying them if there are any
        /// </summary>
        /// <typeparam name="T">The type if Api Response</typeparam>
        /// <param name="response">The response to check</param>
        /// <param name="title">The title of the error dialog if there is an error</param>
        /// <returns>Returns true if there was an error, of false if all was ok</returns>
        public static async Task <bool> DisplayErrorIfFailedAsync <T>(this WebRequestResult <ApiResponse <T> > response, string title)
        {
            // If there was no response, bad data, or a response with a error message...
            if (response?.ServerResponse == null || !response.ServerResponse.Successful)
            {
                // Default error message
                // TODO: Localize strings
                var message = "Unknown error from server call";

                // If we got a response from the server..
                if (response?.ServerResponse != null)
                {
                    // Set message to servers response
                    message = response.ServerResponse.ErrorMessage;
                }
                // If we have a response but deserialize failed...
                else if (!string.IsNullOrWhiteSpace(response?.RawServerResponse))
                {
                    // Set error message
                    message = $"Unexpected response from server. {response.RawServerResponse}";
                }
                // If we have a response but no server response details at all...
                else if (response != null)
                {
                    // Set message to standard HTTP server response details
                    message =
                        $"Failed to communicate with server. Status code {response.StatusCode}. {response.StatusDescription}";
                }

                // Display error
                await UI.ShowMessage(new MessageBoxDialogViewModel
                {
                    // TODO: Localize strings
                    Title   = title,
                    Message = message
                });

                // Return that we had an error
                return(true);
            }

            // All was OK, so return false for no error
            return(false);
        }
示例#14
0
        public static async Task <bool> HandleErrorIfFailedAsync(this WebRequestResult response, string title)
        {
            if (response == null || response.ServerResponse == null || (response.ServerResponse as ApiResponse)?.Successful == false)
            {
                // Default error message
                // TODO: Localize strings
                var message = "Unknown error from server call";

                if (response?.ServerResponse is ApiResponse apiResponse)
                {
                    message = apiResponse.ErrorMessage;
                }
                else if (!string.IsNullOrWhiteSpace(response?.RawServerResponse))
                {
                    message = $"Unexpected response from server. {response.RawServerResponse}";
                }
                else if (response != null)
                {
                    message = response.ErrorMessage ?? $"Server responded with {response.StatusDescription} ({response.StatusCode})";
                }

                if (response?.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    FrameworkDI.Logger.LogInformationSource("Logging user out due to unauthorized response from server");

                    await DI.Di.ViewModelSettings.LogoutAsync();
                }
                else
                {
                    await DI.Di.Ui.ShowMessage(new MessageBoxDialogViewModel
                    {
                        // TODO: Localize strings
                        Title   = title,
                        Message = message
                    });
                }

                return(true);
            }

            return(false);
        }
示例#15
0
        private async Task <WebRequestResult> SendMultiple(IEnumerable <SendMessage> messages, string channelUrl)
        {
            WebRequestResult lastResult = null;

            foreach (var message in messages)
            {
                message.SetNonce();

                lastResult = await PostRequest(message.ToJson(), channelUrl);

                if (lastResult.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        var responseMessage = JObject.Parse(lastResult.Data).ToObject <Message>();
                        if (responseMessage.Nonce != message.Nonce)
                        {
                            Logger.LogWarning($"Response contained a different Nonce value\n" +
                                              $"{responseMessage.ToJson()}");
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex);
                    }
                }
                else
                {
                    Logger.LogWarning($"Did not receive Http response 200 (OK) when sending separated messages\n" +
                                      $"{lastResult.StatusCode}: {lastResult.Data}");
                    return(lastResult);
                }

                Logger.LogInfo(lastResult.Data);
            }

            return(lastResult);
        }
        public void WhenWhenMakeRequestUsingTheTemplate()
        {
            var path = _scenarioContext.Get <string>(ContextDefinedValues.TemplateFilePath);

            var templateData = TemplateTester.LoadTemplateData(path);

            if (string.IsNullOrWhiteSpace(templateData))
            {
                Assert.Fail("Failed to load template data");
            }

            Postmanv3template template = JsonConvert.DeserializeObject <Postmanv3template>(templateData);
            var templateItem           = template.item[0];

            if (templateItem._event != null)
            {
                foreach (Event eventType in templateItem._event)
                {
                    if (eventType.listen == "test")
                    {
                        _scenarioContext.Set(eventType.script, ContextDefinedValues.ResponseTests);
                    }
                }
            }

            var request = templateItem.request;

            var requestMethod = request.method;
            var urlTemplate   = request.url.raw;

            var url = ConfigurationParser.GetFullUrlFromTemplate(urlTemplate);

            _scenarioContext.Set(requestMethod, ContextDefinedValues.RequestMethod);

            WebRequestResult testResult = WebRequestProvider.MakeRequest(requestMethod, url, request.header);

            _scenarioContext.Set(JsonConvert.SerializeObject(testResult), ContextDefinedValues.RequestResult);
        }
示例#17
0
    public static void GetAsync(string url, WebRequestResult resultCallback)
    {
        try
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(url);

            var request = new RequestObject();
            request.webRequest = webRequest;
            request.webResult  = resultCallback;

            var result = webRequest.BeginGetResponse(new AsyncCallback(WebRequestCallback), request);
            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(WebRequestTimeoutCallback), request, WAIT_TIME, true);
        }
        catch (WebException e)
        {
            LogUtil.E("WebException raised, {0} {1}!", e.Status, e.Message);
            WebRequestFinished(resultCallback, WebRequestResultType.ConnectFailure, string.Empty);
        }
        catch (Exception e)
        {
            LogUtil.E("Exception raised, {0} {1}!", e.Source, e.Message);
            WebRequestFinished(resultCallback, WebRequestResultType.Unknown, string.Empty);
        }
    }
        /// <summary>
        /// Checks the web requests response for error and displays them
        /// </summary>
        /// <param name="response">Response to check</param>
        /// <param name="title">Title of the error dialog if there was any</param>
        /// <returns>bool indicating if there was an error</returns>
        public static async Task <bool> DisplayErrorIfFailedAsync <T>(this WebRequestResult <ApiResponse <T> > response, string title)
        {
            // if there was no response, bad data or an error response  ->  error
            if (response == null || response.ServerResponse == null || !response.ServerResponse.Successful)
            {
                // Default error message
                // Todo localize strings
                var message = "Unknown error from server response";

                // Set message to server response
                if (response?.ServerResponse != null)
                {
                    message = response.ServerResponse.ErrorMessage;
                }
                // if we have a response but deserialization failed
                else if (!string.IsNullOrWhiteSpace(response?.RawServerResponse))
                {
                    // set error message
                    message = $"Unexpected response from server. {response.RawServerResponse}";
                }
                // if we have a response but no response details
                else if (response != null)
                {
                    // Set message to standard http server response details
                    message = $"Failed to communicate to server. Status code {response.StatusCode}. {response.StatusDescription}";
                }

                // Display error
                await IoC.UI.ShowMessageBoxDialog(new DialogMessageBoxViewModel { Message = message }, title);

                // return that we hat an error
                return(true);
            }
            //all good
            return(false);
        }
示例#19
0
        private void SetupAirportDataDotCom(string icao, string registration, int maxThumbs, HttpStatusCode statusCode, AirportDataThumbnailsJson response)
        {
            var result = new WebRequestResult <AirportDataThumbnailsJson>(statusCode, response);

            _AirportDataDotCom.Setup(r => r.GetThumbnails((icao ?? "").ToUpper(), (registration ?? "").ToUpper(), maxThumbs)).Returns(result);
        }
示例#20
0
        public Coroutine Get <T>(string _uri, WebRequestResult _result, int _timeOut, WebRequestCallBack _timeOutCallBack) where T : WebRequestResult
        {
            _result = result;

            return(CoroutimeGameObj.StartCoroutine(WebRequestGet <T>(_uri, _timeOut, _timeOutCallBack)));
        }