Exemplo n.º 1
0
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            // Get and fill the RequestState
            RequestState state = (RequestState)asynchronousResult.AsyncState;

            HttpWebRequest request = state.Request;

            HttpWebResponse response = null;

            Stream       streamResponse = null;
            StreamReader streamRead     = null;

            try
            {
                // End the Asynchronous response and get the actual response object
                //To-Do: This has the potential for cross-domain calls, which are tricky in SL. This line doesn't work in the MDT POC.
                response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                state.StatusCode = response.StatusCode;

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Created:
                case HttpStatusCode.Accepted:
                    break;

                case HttpStatusCode.NoContent:
                    state.ErrorMessage = String.Format("No Content returned: Result {0} for {1}", state.StatusCode, state.Uri);
                    MXDevice.Log.Warn(state.ErrorMessage);
                    state.Expiration = DateTime.UtcNow;
                    OnComplete(state);
                    return;

                default:
                    state.ErrorMessage = String.Format("{0} failed. Received HTTP {1} for {2}", state.Verb, response.StatusCode, state.Uri);
                    MXDevice.Log.Error(state.ErrorMessage);
                    state.Expiration = DateTime.UtcNow;
                    OnComplete(state);

                    return;
                }

                // extract response into bytes and string.
                WebResponse webResponse = NetworkUtils.ExtractResponse(response);
                state.ResponseBytes  = webResponse.ResponseBytes;
                state.ResponseString = webResponse.ResponseString;

                state.Expiration = response.Headers["Expires"].TryParseDateTimeUtc();

                OnComplete(state);
            }
            catch (WebException ex)
            {
                // To-Do: Consider adding custom post exceptions...
                string message = string.Format("Call to {0} had a Webexception. {1}   Status: {2}", state.Request.RequestUri, ex.Message, ex.Status);
                ex.Data.Add("ResponseStatusCode", ex.Status);
                ex.Data.Add("Uri", state.Uri);
                ex.Data.Add("Verb", state.Verb);

                state.StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
                ex.Data.Add("StatusCode", state.StatusCode);
                ex.Data.Add("StatusDescription", ((HttpWebResponse)ex.Response).StatusDescription);
                state.Exception = ex;

                OnError(state);
            }
            catch (Exception ex)
            {
                // To-Do: Consider adding custom post exceptions...
                string    message = string.Format("Call to {0} had an Exception. {1}", state.Request.RequestUri, ex.Message);
                Exception qexc    = new Exception(message, ex);
                qexc.Data.Add("Uri", state.Uri);
                qexc.Data.Add("Verb", state.Verb);
                state.Exception = qexc;

                OnError(state);
            }
            finally
            {
                // Close the stream object
                if (streamResponse != null)
                {
                    streamResponse.Close();
                }

                if (streamRead != null)
                {
                    streamRead.Close();
                }

                // Release the HttpWebResponse
                if (response != null)
                {
                    response.Close();
                }
                state.Request = null;

                allDone.Set();
            }
        }
Exemplo n.º 2
0
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            // Get and fill the RequestState
            RequestState state = (RequestState)asynchronousResult.AsyncState;

            HttpWebRequest  request  = state.Request;
            HttpWebResponse response = null;

            try
            {
                // End the Asynchronous response and get the actual response object
                response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                state.StatusCode = response.StatusCode;

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Created:
                case HttpStatusCode.Accepted:
                    break;

                case HttpStatusCode.NoContent:
                    Device.Log.Info("Empty payload returned in PosterAsynch: Result {0} for {1}", state.StatusCode, request.RequestUri);
                    break;

                default:
                    state.ErrorMessage = String.Format("{0} failed. Received HTTP {1} for {2}", state.Verb, response.StatusCode, state.Uri);
                    Device.Log.Error(state.ErrorMessage);
                    state.Expiration       = DateTime.UtcNow;
                    state.AttemptToRefresh = DateTime.UtcNow;
                    OnComplete(state);

                    return;
                }

                // extract response into bytes and string.
                WebResponse webResponse = NetworkUtils.ExtractResponse(response);
                state.ResponseBytes    = webResponse.ResponseBytes;
                state.ResponseString   = webResponse.ResponseString;
                state.ResponseHeaders  = webResponse.ResponseHeaders;
                state.Expiration       = response.Headers["Expires"].TryParseDateTimeUtc();
                state.AttemptToRefresh = response.Headers["MonoCross-Attempt-Refresh"].TryParseDateTimeUtc();
                OnComplete(state);
            }
            catch (WebException ex)
            {
                string StatusDescription = string.Empty;
                string message           = string.Format("Call to {0} had a Webexception. {1}   Status: {2}", state.Request.RequestUri, ex.Message, ex.Status);
                ex.Data.Add("WebException.StatusCode", ex.Status);
                ex.Data.Add("Uri", state.Uri);
                ex.Data.Add("Verb", state.Verb);

                ex.Data.Add("StatusCode", state.StatusCode);
                if (ex.Response != null)
                {
                    state.StatusCode      = ((HttpWebResponse)ex.Response).StatusCode;
                    StatusDescription     = ((HttpWebResponse)ex.Response).StatusDescription;
                    state.ResponseHeaders = ex.Response.Headers;
                }
                else if (ex.Message.ToLower().Contains("request was aborted"))
                {
                    state.StatusCode  = HttpStatusCode.RequestTimeout;
                    StatusDescription = "Request cancelled by client because the server did not respond within timeout";
                }
                else
                {
                    state.StatusCode = (HttpStatusCode)(-2);
                }
                state.WebExceptionStatusCode = ex.Status;
                ex.Data.Add("WebException.Status", ex.Status);
                ex.Data.Add("StatusDescription", StatusDescription);
                state.ErrorMessage     = message;
                state.Exception        = ex;
                state.Expiration       = DateTime.UtcNow;
                state.AttemptToRefresh = DateTime.UtcNow;

                OnError(state);
            }
            catch (Exception ex)
            {
                // TODO: Consider adding custom post exceptions...
                string    message = string.Format("Call to {0} had an Exception. {1}", state.Request.RequestUri, ex.Message);
                Exception qexc    = new Exception(message, ex);
                qexc.Data.Add("Uri", state.Uri);
                qexc.Data.Add("Verb", state.Verb);
                state.ErrorMessage           = message;
                state.Exception              = qexc;
                state.Expiration             = DateTime.UtcNow;
                state.AttemptToRefresh       = DateTime.UtcNow;
                state.StatusCode             = (HttpStatusCode)(-1);
                state.WebExceptionStatusCode = (WebExceptionStatus)(-1);

                OnError(state);
            }
            finally
            {
                // Release the HttpWebResponse
                if (response != null)
                {
                    ((IDisposable)response).Dispose();
                }
                state.Request = null;

                allDone.Set();
            }
        }
Exemplo n.º 3
0
        public NetworkResponse PostBytes(string uri, byte[] postBytes, string contentType, string verb, Dictionary <string, string> headers)
        {
#if !SILVERLIGHT && !MONO
            // Create the request obj
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            // Set values for the request back
            request.Method                 = verb; // "POST";
            request.ContentType            = contentType;
            request.ContentLength          = postBytes.Length;
            request.AutomaticDecompression = DecompressionMethods.Deflate;

            NetworkResponse networkResponse = new NetworkResponse()
            {
                URI  = request.RequestUri.AbsoluteUri,
                Verb = verb
            };
            DateTime dtMetric = DateTime.UtcNow;

            Stream postStream = null;

            HttpWebResponse response       = null;
            Stream          streamResponse = null;
            StreamReader    streamRead     = null;
            try
            {
                #region Send Post object to Request stream

                // To-Do: Refactor this central storage of header values to inject into an abstract network object.
                if (headers != null && headers.Count() > 0)
                {
                    foreach (string key in headers.Keys)
                    {
                        request.Headers[key] = headers[key];
                    }
                }

                postStream = request.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);
                postStream.Close();

                #endregion

                #region Get Response state from Response stream

                response = (HttpWebResponse)request.GetResponse();

                networkResponse.StatusCode = response.StatusCode;

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Created:
                case HttpStatusCode.Accepted:
                    break;

                case HttpStatusCode.NoContent:
                    networkResponse.Expiration = DateTime.UtcNow;
                    networkResponse.Message    = String.Format("No Content returned: Result {0} for {1}", response.StatusCode, uri);
                    MXDevice.Log.Warn(networkResponse.Message);
                    break;

                default:
                    networkResponse.Expiration = DateTime.UtcNow;
                    networkResponse.Message    = String.Format("{0} failed. Received HTTP {1} for {2}", request.Method, response.StatusCode, uri);
                    MXDevice.Log.Error(networkResponse.Message);
                    return(networkResponse);
                }

                // extract response into bytes and string.
                WebResponse webResponse = NetworkUtils.ExtractResponse(response);
                networkResponse.ResponseBytes  = webResponse.ResponseBytes;
                networkResponse.ResponseString = webResponse.ResponseString;

                MXDevice.Log.Debug(string.Format("PostBytes Completed: Uri: {0} Time: {1} milliseconds  Size: {2} ", uri, DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds, (networkResponse.ResponseBytes != null ? networkResponse.ResponseBytes.Length : -1)));

                // set expiration values
                networkResponse.Expiration = response.Headers["Expires"].TryParseDateTimeUtc();

                #endregion
            }
            catch (WebException ex)
            {
                ex.Data.Add("ResponseStatusCode", ex.Status);
                ex.Data.Add("Uri", request.RequestUri);
                ex.Data.Add("Verb", request.Method);

                MXDevice.Log.Error(string.Format("Call to {0} had a Webexception. {1}  Status: {2}", request.RequestUri, ex.Message, ex.Status));
                MXDevice.Log.Error(ex);

                networkResponse.ResponseBytes  = null;
                networkResponse.ResponseString = null;
                networkResponse.Expiration     = DateTime.MinValue.ToUniversalTime();

                networkResponse.StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
                ex.Data.Add("StatusCode", networkResponse.StatusCode);
                ex.Data.Add("StatusDescription", ((HttpWebResponse)ex.Response).StatusDescription);

                networkResponse.Message   = ex.Message;
                networkResponse.Exception = ex;
            }
            catch (Exception ex)
            {
                ex.Data.Add("Uri", request.RequestUri);
                ex.Data.Add("Verb", request.Method);

                networkResponse.ResponseBytes  = null;
                networkResponse.ResponseString = null;
                networkResponse.Expiration     = DateTime.MinValue.ToUniversalTime();
                networkResponse.StatusCode     = (HttpStatusCode)(-1);
                networkResponse.Message        = ex.Message;
                networkResponse.Exception      = ex;
            }
            finally
            {
                // Close the stream object
                if (streamResponse != null)
                {
                    streamResponse.Close();
                }

                if (streamRead != null)
                {
                    streamRead.Close();
                }

                // Release the HttpWebResponse
                if (response != null)
                {
                    response.Close();
                }
            }

            return(networkResponse);
#else
            throw new NotSupportedException("PosterSynch is not supported in Silverlight");
#endif
        }
Exemplo n.º 4
0
        // Define other methods and classes here
        private void ResponseCallback(IAsyncResult result)
        {
            // Get and fill the RequestState
            RequestState state = (RequestState)result.AsyncState;

            try
            {
                HttpWebRequest request = state.Request;

                // End the Asynchronous response and get the actual response object
                state.Response = (HttpWebResponse)request.EndGetResponse(result);
#if !NETCF
                state.Expiration       = state.Response.Headers["Expires"].TryParseDateTimeUtc();
                state.AttemptToRefresh = state.Response.Headers["MonoCross-Attempt-Refresh"].TryParseDateTimeUtc();
#endif
                // apply web response headers to data collection.
                // TODO: evaluate which headers are actually needed and skip those that aren't. So, what's our logic for "needed headers" ?
                foreach (string key in state.Response.Headers.AllKeys)
                {
                    state.Data[key] = state.Response.Headers[key];
                }

                state.StatusCode = state.Response.StatusCode;

                switch (state.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Created:
                case HttpStatusCode.Accepted:
                    break;

                case HttpStatusCode.NoContent:
                    Device.Log.Info("Empty payload returned in FetcherAsynch: Result {0} for {1}", state.StatusCode, request.RequestUri);
                    break;

                default:
                    state.ErrorMessage = String.Format("Get failed. Received HTTP {0} for {1}", state.StatusCode, request.RequestUri);
                    Device.Log.Error(state.ErrorMessage);
                    state.Expiration       = DateTime.UtcNow;
                    state.AttemptToRefresh = DateTime.UtcNow;
                    state.Downloaded       = DateTime.UtcNow;
                    OnDownloadComplete(state);

                    return;
                }

                // extract response into bytes and string.
                WebResponse webResponse = NetworkUtils.ExtractResponse(state.Response, state.FileName);
                state.ResponseBytes   = webResponse.ResponseBytes;
                state.ResponseString  = webResponse.ResponseString;
                state.ResponseHeaders = webResponse.ResponseHeaders;

                OnDownloadComplete(state);
            }
            catch (WebException ex)
            {
                string StatusDescription = string.Empty;
#if !NETCF
                ex.Data.Add("Uri", state.Request.RequestUri);
                ex.Data.Add("Verb", state.Request.Method);
#endif
                if (ex.Response != null)
                {
                    state.StatusCode      = ((HttpWebResponse)ex.Response).StatusCode;
                    StatusDescription     = ((HttpWebResponse)ex.Response).StatusDescription;
                    state.ResponseHeaders = ex.Response.Headers;
                }
                else if (ex.Message.ToLower().Contains("request was aborted"))
                {
                    state.StatusCode  = HttpStatusCode.RequestTimeout;
                    StatusDescription = "Request cancelled by client because the server did not respond within timeout";
                }
                else
                {
                    state.StatusCode = (HttpStatusCode)(-2);
                }
                state.WebExceptionStatusCode = ex.Status;
#if !NETCF
                ex.Data.Add("StatusCode", state.StatusCode);
                ex.Data.Add("WebException.Status", ex.Status);
                ex.Data.Add("StatusDescription", StatusDescription);
#endif
                state.ErrorMessage     = string.Format("Call to {0} had a Webexception. {1}   Status: {2}   Desc: {3}", state.Request.RequestUri, ex.Message, ex.Status, StatusDescription);
                state.Exception        = ex;
                state.Expiration       = DateTime.UtcNow;
                state.AttemptToRefresh = DateTime.UtcNow;

                OnError(state);
            }
            catch (Exception ex)
            {
#if !NETCF
                ex.Data.Add("Uri", state.Request.RequestUri);
                ex.Data.Add("Verb", state.Request.Method);
#endif
                state.ErrorMessage           = string.Format("Call to {0} had an Exception. {1}", state.Request.RequestUri, ex.Message);
                state.Exception              = ex;
                state.StatusCode             = (HttpStatusCode)(-1);
                state.WebExceptionStatusCode = (WebExceptionStatus)(-1);
                state.Expiration             = DateTime.UtcNow;
                state.AttemptToRefresh       = DateTime.UtcNow;

                OnError(state);
            }
            finally
            {
                if (state.Response != null)
                {
                    ((IDisposable)state.Response).Dispose();
                }
                state.Request = null;

                allDone.Set();
            }
        }
Exemplo n.º 5
0
        public NetworkResponse Fetch(string uri, string filename, Dictionary <string, string> headers)
        {
#if SILVERLIGHT || MONO
            throw new NotSupportedException("FetcherSynch is not supported in Silverlight");
#else
            NetworkResponse networkResponse = new NetworkResponse()
            {
                URI  = uri,
                Verb = "GET"
            };

            DateTime dtMetric = DateTime.UtcNow;

            Stream          stream   = null;
            StreamReader    reader   = null;
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;
            try
            {
                request        = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
                request.AutomaticDecompression = DecompressionMethods.Deflate;

                //// If required by the server, set the credentials.
                //request.Credentials = CredentialCache.DefaultCredentials;

                // To-Do: Refactor this central storage of header values to inject into an abstract network object.
                if (headers != null && headers.Count() > 0)
                {
                    foreach (string key in headers.Keys)
                    {
                        request.Headers[key] = headers[key];
                    }
                }


                #region Get Response state from Response stream


                response = (HttpWebResponse)request.GetResponse();

                networkResponse.StatusCode = response.StatusCode;

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Created:
                case HttpStatusCode.Accepted:
                    break;

                case HttpStatusCode.NoContent:
                    networkResponse.Expiration = DateTime.UtcNow;
                    networkResponse.Message    = String.Format("No Content returned: Result {0} for {1}", response.StatusCode, uri);
                    MXDevice.Log.Warn(networkResponse.Message);
                    break;

                default:
                    networkResponse.Expiration = DateTime.UtcNow;
                    networkResponse.Message    = String.Format("{0} failed. Received HTTP {1} for {2}", request.Method, response.StatusCode, uri);
                    MXDevice.Log.Error(networkResponse.Message);
                    return(networkResponse);
                }

                // extract response into bytes and string.
                WebResponse webResponse = NetworkUtils.ExtractResponse(response, filename);
                networkResponse.ResponseBytes  = webResponse.ResponseBytes;
                networkResponse.ResponseString = webResponse.ResponseString;

                MXDevice.Log.Debug(string.Format("Fetch Completed: Uri: {0} Time: {1} milliseconds  Size: {2} ", uri, DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds, (networkResponse.ResponseBytes != null ? networkResponse.ResponseBytes.Length : -1)));

                #endregion

                networkResponse.Expiration = response.Headers["Expires"].TryParseDateTimeUtc();
            }
            catch (WebException ex)
            {
                ex.Data.Add("Uri", networkResponse.URI);
                ex.Data.Add("Verb", networkResponse.Verb);

                networkResponse.Message = string.Format("Call to {0} had a Webexception. {1}   Status: {2}   Desc: {3}", networkResponse.URI, ex.Message, ex.Status, ((HttpWebResponse)ex.Response).StatusDescription);

                networkResponse.StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
                ex.Data.Add("StatusCode", networkResponse.StatusCode);
                ex.Data.Add("StatusDescription", ((HttpWebResponse)ex.Response).StatusDescription);

                networkResponse.Exception  = ex;
                networkResponse.Expiration = DateTime.UtcNow;

                MXDevice.Log.Error(networkResponse.Message);
                MXDevice.Log.Error(ex);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Uri", networkResponse.URI);
                ex.Data.Add("Verb", networkResponse.Verb);

                networkResponse.Message    = string.Format("Call to {0} had an Exception. {1}", networkResponse.URI, ex.Message);
                networkResponse.Exception  = ex;
                networkResponse.StatusCode = (HttpStatusCode)(-1);
                networkResponse.Expiration = DateTime.UtcNow;

                MXDevice.Log.Error(networkResponse.Message);
                MXDevice.Log.Error(ex);
            }
            finally
            {
                // Cleanup the streams and the response.
                if (reader != null)
                {
                    reader.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }

            return(networkResponse);
#endif
        }