コード例 #1
0
 private void AssertJavaScriptIsGZiped(object sender, HttpResponseEventArgs e)
 {
     Debug.WriteLine(String.Format("Request for {0}", e.Response.Request.RequestUri));
     if (e.Response.Headers["Content-Type"] != null && e.Response.Headers["Content-Type"].Equals("application/javascript"))
     {
         Assert.AreEqual("gzip", e.Response.Headers["Content-Encoding"]);
     }
 }
コード例 #2
0
        /// <summary>
        /// Handles the <see cref="HttpResponse" /> event.
        /// </summary>
        /// <param name="e">The <see cref="HttpResponseEventArgs"/> instance containing the event data.</param>
        protected virtual void OnHttpResponse(HttpResponseEventArgs e)
        {
            this.SyncState = false;
            var handler = this.HttpResponseEvent;

            if (handler != null)
            {
                handler(this, e);
            }
        }
コード例 #3
0
 private void CheckTypeForImage(object sender, HttpResponseEventArgs e)
 {
     Log.WriteLine(String.Format("Request for {0}", e.Response.Request.RequestUri));
     if (e.Response.IsImage)
     {
         Log.WriteLine(String.Format("Image detected; MIME type: {0}", e.Response.Headers["Content-Type"]));
     }
     else
     {
         Log.WriteLine(String.Format("Not an image; MIME type: {0}", e.Response.Headers["Content-Type"]));
     }
 }
コード例 #4
0
 async void ApiClient_HttpResponseReceived(object sender, HttpResponseEventArgs e)
 {
     if (e.StatusCode == HttpStatusCode.Unauthorized)
     {
         try
         {
             await SessionManager.Logout();
         }
         catch (Exception ex)
         {
             Logger.ErrorException("Error logging out", ex);
         }
     }
 }
コード例 #5
0
        public static void HandleAfterAsyncWebResponse(object sender, HttpResponseEventArgs e)
        {
            if (e.Response.Status == TaskStatus.RanToCompletion)
            {
                if (SuppressOutput)
                {
                    if (e.Response.Result.IsSuccessStatusCode)
                    {
                        return;
                    }
                    else
                    {
                        LogRequest(e.Response.Result.RequestMessage);
                    }
                }

                Console.Error.WriteLine("{0} (Result {1})", DateTime.Now, e.Response.Result.StatusCode);

                if (e.Response.Result.Content != null && e.Response.Result.Content.Headers.ContentType != null)
                {
                    switch (e.Response.Result.Content.Headers.ContentType.MediaType)
                    {
                    case "application/json":
                        LogResult(e.Response.Result, e.Response.Result.Content.ReadAsStringAsync().Result, true);
                        break;

                    case "application/xml":
                    case "text/plain":
                    case "text/html":
                        LogResult(e.Response.Result, e.Response.Result.Content.ReadAsStringAsync().Result, false);
                        break;

                    default:
                        LogResult(e.Response.Result, "[STREAMING CONTENT]", false);
                        break;
                    }
                }
                else
                {
                    LogResult(e.Response.Result, "[NO CONTENT]", false);
                }
            }
            else
            {
                Console.Error.WriteLine("{0} (Result {1})", DateTime.Now, e.Response.Status);
            }
        }
コード例 #6
0
        /// <summary>
        /// Handles the HttpResponseEvent event of the channel control. This event brings the response after FIS registration.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="HttpResponseEventArgs"/> instance containing the event data.</param>
        private void HttpRegistrationResponseEvent(object sender, HttpResponseEventArgs e)
        {
            if (e != null)
            {
                var state = e.State as Tuple <string, Guid>;
                if (state != null)
                {
                    var callbackEndpointAddress = state.Item1;
                    var invokeId = state.Item2;

                    // Create message.
                    var message = new Message(callbackEndpointAddress, invokeId, MessageTypes.FisRegistrationResponse);
                    message.AddParameter(ParameterTypes.FisHttpResponse, e);

                    // Enqueue message.
                    MessageQueue.Instance.Enqueue(message);
                }
            }
        }
コード例 #7
0
        public HttpResponseEventArgs Get(string url)
        {
            HttpResponseEventArgs result = new HttpResponseEventArgs();

            try
            {
                // if (executing)
                //     throw new Exception("Another request is executing.");
                if (!Initialized)
                {
                    throw new Exception("Client was not initialized.");
                }
                while (executing)
                {
                    Thread.Sleep(100);
                }
                executing = true;

                using (HttpResponseMessage response = http.GetAsync(url).Result)
                {
                    result.HTMLInString      = response.Content.ReadAsStringAsync().Result;
                    result.SuccessfulRequest = response.IsSuccessStatusCode;
                    result.StatusCode        = Convert.ToInt32(response.StatusCode);

                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(result.HTMLInString);
                    result.HTMLDocument = doc;
                }
            }
            catch (Exception ex)
            {
                result.SuccessfulRequest = false;
                result.Message           = ex.Message;
            }
            finally
            {
                executing = false;
            }
            return(result);
        }
コード例 #8
0
        public HttpResponseEventArgs Post(string url, Dictionary <string, string> args)
        {
            HttpResponseEventArgs result = new HttpResponseEventArgs();

            try
            {
                // if (executing)
                //     throw new Exception("Another request is executing.");
                if (!Initialized)
                {
                    throw new Exception("Client was not initialized.");
                }
                while (executing)
                {
                    Thread.Sleep(100);
                }
                executing = true;

                var content = new FormUrlEncodedContent(args);
                using (HttpResponseMessage response = http.PostAsync(url, content).Result)
                {
                    result.SuccessfulRequest = response.IsSuccessStatusCode;
                    result.StatusCode        = Convert.ToInt32(response.StatusCode);
                    result.HTMLInString      = response.Content.ReadAsStringAsync().Result;
                }
                content.Dispose();
            }
            catch (Exception ex)
            {
                result.SuccessfulRequest = false;
                result.Message           = ex.Message;
            }
            finally
            {
                executing = false;
            }
            return(result);
        }
コード例 #9
0
 /// <summary>
 /// Handles the HttpResponseEvent event of the channel control. This event brings the response after FIS data send.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="HttpResponseEventArgs"/> instance containing the event data.</param>
 private void HttpDataResponseEvent(object sender, HttpResponseEventArgs e)
 {
     // This event is used only to log possible errors.
     if (e != null)
     {
         if (e.ResultCode)
         {
             if (e.StatusCode == HttpStatusCode.OK || e.StatusCode == HttpStatusCode.Created)
             {
                 Logger.InfoFormat(this, "Data sent to FIS success! HttpStatusDescription: {0}", e.StatusDescription);
             }
             else
             {
                 var t = "Data sent to FIS error. " + e.StatusDescription;
                 Logger.Error(this, t);
                 DiagnosticsCollection.Instance.AddMessage(t);
             }
         }
         else
         {
             if (e.Exception != null)
             {
                 const string T = "Data sent to FIS exception.";
                 Logger.ErrorException(this, T, e.Exception);
                 DiagnosticsCollection.Instance.AddMessage(T);
                 DiagnosticsCollection.Instance.AddMessage(e.Exception);
             }
             else
             {
                 const string T = "Data sent to FIS error.";
                 Logger.Error(this, T);
                 DiagnosticsCollection.Instance.AddMessage(T);
             }
         }
     }
 }
コード例 #10
0
        /// <summary>
        /// Processes the HttpResponseEvent event of the channel control. This event brings the response after FIS registration.
        /// </summary>
        /// <param name="callbackEndpointAddress">The callback endpoint address.</param>
        /// <param name="invokeId">The invoke identifier.</param>
        /// <param name="e">The <see cref="HttpResponseEventArgs" /> instance containing the event data.</param>
        private void ProcessFisRegistrationResponse(string callbackEndpointAddress, Guid invokeId, HttpResponseEventArgs e)
        {
            if (e != null)
            {
                var user = string.Empty;
                var pw   = string.Empty;
                var good = false;

                // Check whether the response is good.
                if (e.ResultCode)
                {
                    // In some case the HttpStatusCode is wrapped into an Exception, in some case not. Check it before continuing.
                    if (e.StatusCode == HttpStatusCode.OK || e.StatusCode == HttpStatusCode.Created)
                    {
                        // Body is included only for first registrations.
                        if (this.FisRegistrationChannel.FirstRegistration)
                        {
                            // Parse the body for the received data.
                            var model        = this.DataManager.Configuration.Gateway.Model;
                            var serialNumber = this.DataManager.Configuration.Gateway.SerialNumber;

                            var parser = new RegistrationParser(e.ResponseString, model, serialNumber);
                            if (parser.ExtractUserPassword(out user, out pw))
                            {
                                good = true;
                            }
                        }
                        else
                        {
                            // It is enough to check here the HttpStatusCode.
                            good = true;
                        }
                    }
                }

                if (good)
                {
                    // Change the FIS authentication for future data send to FIS server.
                    if (this.FisRegistrationChannel.FirstRegistration)
                    {
                        this.ChangeFisAuthentication(user, pw);
                    }

                    Logger.Info(this, "Gateway registered to FIS successfully.");

                    ThreadPool.QueueUserWorkItem(
                        Callbacks.OnFisRegistrationResponse,
                        new object[] { ClientEndPointName, callbackEndpointAddress, invokeId, ResultCodes.Success, null });
                }
                else
                {
                    Logger.ErrorException(this, "Error received Gateway registration response.", e.Exception);
                    DiagnosticsCollection.Instance.AddMessage("Error received Gateway registration response.");
                    DiagnosticsCollection.Instance.AddMessage(e.Exception);

                    ThreadPool.QueueUserWorkItem(
                        Callbacks.OnFisRegistrationResponse,
                        new object[]
                    {
                        ClientEndPointName, callbackEndpointAddress, invokeId, ResultCodes.CannotRegisterFis,
                        e.Exception
                    });
                }
            }
        }
コード例 #11
0
        /// <summary>
        ///  Called on the network thread when it is time to receive an HTTP response from the host/server.
        /// </summary>
        /// <param name="result">Provides the HttpWebRequest object that invoked this method.</param>
        private void OnAsyncGetResponse(IAsyncResult result)
        {
            // Fetch the HTTP request implementation object and settings.
            var httpWebRequest = fHttpWebRequest;
            var settings       = fClonedSettings;

            if ((httpWebRequest == null) || (settings == null))
            {
                return;
            }

            // Do not continue if this operation has been aborted.
            if (object.ReferenceEquals(httpWebRequest, result.AsyncState) == false)
            {
                return;
            }

            // Fetch the HTTP response data.
            System.Net.HttpWebResponse httpWebResponse = null;
            System.IO.Stream           inputStream     = null;
            System.IO.Stream           outputStream    = null;
            try
            {
                // Fetch the HTTP response.
                try
                {
                    httpWebResponse = httpWebRequest.EndGetResponse(result) as System.Net.HttpWebResponse;
                }
                catch (System.Net.WebException ex)
                {
                    // Check if an exception was thrown because we've received an HTTP error response.
                    // This can happen if the response's status code is >= 400.
                    httpWebResponse = ex.Response as System.Net.HttpWebResponse;

                    // If we did not get a response, then assume its a network error and abort.
                    if (httpWebResponse == null)
                    {
                        throw ex;
                    }

#if WINDOWS_PHONE
                    // If the Internet connection is down, then we'll get a fake 404 response.
                    // If this is the case, then error out immediately. (The HTTP response is not real. So, don't provide it.)
                    if (Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable == false)
                    {
                        throw new Exception("Network connection error.");
                    }
#endif
                }

                // If the HTTP request had no content, then the OnAsyncGetRequestStream() never got called.
                // Notify the system that we've finished sending the HTTP request, which happened in EndGetResponse() above.
                if (httpWebRequest.ContentLength < 0)
                {
                    var asyncSentRequestEventHandler = this.AsyncSentRequest;
                    if (asyncSentRequestEventHandler != null)
                    {
                        asyncSentRequestEventHandler.Invoke(this, new HttpProgressEventArgs(0, 0));
                    }
                }

                // Do not continue if the handler for the above event has aborted this operation.
                if (object.ReferenceEquals(httpWebRequest, fHttpWebRequest) == false)
                {
                    return;
                }

                // Fetch the estimated number of bytes in the HTTP response's body.
                // If the value is -1 or 4294967295 (the unsigned version of -1), then the amount of bytes is unknown.
                inputStream = httpWebResponse.GetResponseStream();
                long responseContentLength = httpWebResponse.ContentLength;
                if ((responseContentLength < 0) || (responseContentLength == (long)UInt32.MaxValue))
                {
                    responseContentLength = -1;
                }

                // Open an output stream if set up to download to file.
                if (string.IsNullOrEmpty(settings.DownloadFilePath) == false)
                {
                    // First, create the file's sub-directories if applicable.
                    string directoryPath = System.IO.Path.GetDirectoryName(settings.DownloadFilePath);
                    System.IO.Directory.CreateDirectory(directoryPath);

                    // Attempt to create the file to write to.
                    outputStream = System.IO.File.Open(
                        settings.DownloadFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                }

                // Fetch the response's HTTP headers.
                var headerCollection = new System.Collections.Generic.Dictionary <string, string>();
                foreach (var headerName in httpWebResponse.Headers.AllKeys)
                {
                    headerCollection.Add(headerName, httpWebResponse.Headers[headerName]);
                }
                var readOnlyHeaderCollection =
                    new System.Collections.ObjectModel.ReadOnlyDictionary <string, string>(headerCollection);

                // Notify the system that we've started to receive an HTTP response.
                var asynReceivingResponseEventHandler = this.AsyncReceivingResponse;
                if (asynReceivingResponseEventHandler != null)
                {
                    asynReceivingResponseEventHandler.Invoke(
                        this, new HttpResponseEventArgs((int)httpWebResponse.StatusCode, readOnlyHeaderCollection, null));
                }

                // Do not continue if the handler for the above event has aborted this operation.
                if (object.ReferenceEquals(httpWebRequest, fHttpWebRequest) == false)
                {
                    return;
                }

                // Download the HTTP response's content body.
                var httpBodyBytes = new System.Collections.Generic.List <byte>();
                if (httpWebResponse.ContentLength > 0)
                {
                    int bytesReceived = 0;
                    var byteBuffer    = new byte[2048];
                    while (true)
                    {
                        // Fetch the next batch of response content bytes, if any are left.
                        int bytesRead = inputStream.Read(byteBuffer, 0, byteBuffer.Length);
                        if (bytesRead == 0)
                        {
                            // No more bytes are available. The entire response has been received.
                            break;
                        }

                        // Do not continue if this operation has been aborted.
                        if (object.ReferenceEquals(httpWebRequest, fHttpWebRequest) == false)
                        {
                            return;
                        }

                        // Copy the HTTP response bytes to file or memory.
                        if (outputStream != null)
                        {
                            // Write the response bytes to file.
                            outputStream.Write(byteBuffer, 0, bytesRead);
                        }
                        else if (bytesRead == byteBuffer.Length)
                        {
                            // Write the response bytes to the memory buffer.
                            // Note: This is an optimization. Copying the entire array in one shot is faster.
                            httpBodyBytes.AddRange(byteBuffer);
                        }
                        else
                        {
                            // Write the last portion of response bytes to the memory buffer.
                            // Note: No more response bytes should be available after this.
                            for (int index = 0; index < bytesRead; index++)
                            {
                                httpBodyBytes.Add(byteBuffer[index]);
                            }
                        }

                        // Notify the system how many bytes have been downloaded so far.
                        bytesReceived += bytesRead;
                        if (bytesReceived > 0)
                        {
                            var asyncReceiveProgressChangedEventHandler = this.AsyncReceiveProgressChanged;
                            if (asyncReceiveProgressChangedEventHandler != null)
                            {
                                // Raise a progress event.
                                asyncReceiveProgressChangedEventHandler.Invoke(
                                    this, new HttpProgressEventArgs(bytesReceived, responseContentLength));

                                // Do not continue if the handler for the above event has aborted this operation.
                                if (object.ReferenceEquals(httpWebRequest, fHttpWebRequest) == false)
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
                var immutableHttpBodyBytes = CoronaLabs.WinRT.ImmutableByteBuffer.From(httpBodyBytes);

                // If downloading to file, close its stream.
                if (outputStream != null)
                {
                    outputStream.Close();
                    outputStream.Dispose();
                    outputStream = null;
                }

                // Clear this operation's member variables.
                // This frees up this object to execute another HTTP request.
                fHttpWebRequest = null;
                fClonedSettings = null;

                // Notify the system that we've received the entire response and we're done.
                var asynReceivedResponseEventHandler = this.AsyncReceivedResponse;
                if (asynReceivedResponseEventHandler != null)
                {
                    var eventArgs = new HttpResponseEventArgs(
                        (int)httpWebResponse.StatusCode, readOnlyHeaderCollection, immutableHttpBodyBytes);
                    asynReceivedResponseEventHandler.Invoke(this, eventArgs);
                }
            }
            catch (Exception ex)
            {
                AbortWithError(ex.Message);
                return;
            }
            finally
            {
                // Close all open streams.
                if (inputStream != null)
                {
                    try { inputStream.Close(); }
                    catch (Exception) { }
                }
                if (outputStream != null)
                {
                    try { outputStream.Close(); }
                    catch (Exception) { }
                }
                if (httpWebResponse != null)
                {
                    try { httpWebResponse.Close(); }
                    catch (Exception) { }
                }
            }
        }