Ejemplo n.º 1
0
        /**
         * Invoke request and return response
         */
        private T Invoke <T>(IDictionary <string, string> parameters)
        {
            string actionName = parameters["Action"];
            T      response   = default(T);
            string queueUrl   = parameters.ContainsKey("QueueUrl") ? parameters["QueueUrl"] : config.ServiceURL;

            if (parameters.ContainsKey("QueueUrl"))
            {
                parameters.Remove("QueueUrl");
            }
            HttpStatusCode statusCode = default(HttpStatusCode);

            /* Add required request parameters */
            AddRequiredParameters(parameters, queueUrl);

            string queryString = AWSSDKUtils.GetParametersAsString(parameters);

            byte[] requestData = Encoding.UTF8.GetBytes(queryString);
            bool   shouldRetry = true;
            int    retries     = 0;
            int    maxRetries  = config.IsSetMaxErrorRetry() ? config.MaxErrorRetry : AWSSDKUtils.DefaultMaxRetry;

            do
            {
                string         responseBody = null;
                HttpWebRequest request      = ConfigureWebRequest(requestData.Length, queueUrl, config);
                /* Submit the request and read response body */
                try
                {
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(requestData, 0, requestData.Length);
                    }

                    using (HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse)
                    {
                        if (httpResponse == null)
                        {
                            throw new WebException(
                                      "The Web Response for a successful request is null!",
                                      WebExceptionStatus.ProtocolError
                                      );
                        }

                        statusCode = httpResponse.StatusCode;
                        using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
                        {
                            responseBody = reader.ReadToEnd();
                        }
                    }

                    /* Attempt to deserialize response into <Action> Response type */
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    using (XmlTextReader sr = new XmlTextReader(new StringReader(responseBody)))
                    {
                        response = (T)serializer.Deserialize(sr);
                    }
                    shouldRetry = false;
                }
                /* Web exception is thrown on unsucessful responses */
                catch (WebException we)
                {
                    shouldRetry = false;
                    using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
                    {
                        if (httpErrorResponse == null)
                        {
                            // Abort the unsuccessful request
                            request.Abort();
                            throw we;
                        }
                        statusCode = httpErrorResponse.StatusCode;
                        using (StreamReader reader = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8))
                        {
                            responseBody = reader.ReadToEnd();
                        }

                        // Abort the unsuccessful request
                        request.Abort();
                    }

                    if (statusCode == HttpStatusCode.InternalServerError ||
                        statusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        shouldRetry = true;
                        PauseOnRetry(++retries, maxRetries, statusCode);
                    }
                    else
                    {
                        /* Attempt to deserialize response into ErrorResponse type */
                        try
                        {
                            using (XmlTextReader sr = new XmlTextReader(new StringReader(responseBody)))
                            {
                                XmlSerializer serializer    = new XmlSerializer(typeof(ErrorResponse));
                                ErrorResponse errorResponse = (ErrorResponse)serializer.Deserialize(sr);
                                Error         error         = errorResponse.Error[0];

                                /* Throw formatted exception with information available from the error response */
                                throw new AmazonSQSException(
                                          error.Message,
                                          statusCode,
                                          error.Code,
                                          error.Type,
                                          errorResponse.RequestId,
                                          errorResponse.ToXML()
                                          );
                            }
                        }
                        /* Rethrow on deserializer error */
                        catch (Exception e)
                        {
                            if (e is AmazonSQSException)
                            {
                                throw;
                            }
                            else
                            {
                                throw ReportAnyErrors(responseBody, statusCode);
                            }
                        }
                    }
                }

                /* Catch other exceptions, attempt to convert to formatted exception,
                 * else rethrow wrapped exception */
                catch (Exception)
                {
                    // Abort the unsuccessful request
                    request.Abort();
                    throw;
                }
            } while (shouldRetry);

            return(response);
        }
Ejemplo n.º 2
0
        /**
         * Invoke request and return response
         */
        private T Invoke <T>(IDictionary <string, string> parameters)
        {
            T      response = default(T);
            string queueUrl = parameters.ContainsKey("QueueUrl") ? parameters["QueueUrl"] : config.ServiceURL;

            if (parameters.ContainsKey("QueueUrl"))
            {
                parameters.Remove("QueueUrl");
            }
            HttpStatusCode statusCode = default(HttpStatusCode);

            /* Add required request parameters */
            AddRequiredParameters(parameters, queueUrl);

            string queryString = AWSSDKUtils.GetParametersAsString(parameters);
            bool   shouldRetry = true;
            int    retries     = 0;
            int    maxRetries  = config.IsSetMaxErrorRetry() ? config.MaxErrorRetry : AWSSDKUtils.DefaultMaxRetry;

            do
            {
                string         responseBody = string.Empty;
                HttpWebRequest request      = ConfigureWebRequest(queueUrl, queryString);
                /* Submit the request and read response body */
                try
                {
                    request.BeginGetResponse(asyncResponse =>
                    {
                        try
                        {
                            HttpWebResponse asyncResult = (HttpWebResponse)request.EndGetResponse(asyncResponse);
                            Stream streamResponse       = asyncResult.GetResponseStream();

                            using (StreamReader streamRead = new StreamReader(streamResponse))
                            {
                                responseBody             = streamRead.ReadToEnd();
                                XDocument doc            = XDocument.Parse(responseBody);
                                XmlSerializer serializer = new XmlSerializer(typeof(T));
                                XmlReader xmlReader      = doc.CreateReader();
                                response = (T)serializer.Deserialize(xmlReader);
                                // Disposing StreamReader automatically closes the underlying streams
                            }

                            OnSQSResponse.Invoke(this, new ResponseEventArgs(response as ISQSResponse));
                        }
                        catch (WebException we)
                        {
                            shouldRetry = false;
                            using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
                            {
                                if (httpErrorResponse == null)
                                {
                                    // Abort the unsuccessful request
                                    request.Abort();
                                    throw;
                                }
                                statusCode = httpErrorResponse.StatusCode;
                                using (StreamReader reader = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8))
                                {
                                    responseBody = reader.ReadToEnd();
                                }

                                // Abort the unsuccessful request
                                request.Abort();
                            }

                            if (statusCode == HttpStatusCode.InternalServerError ||
                                statusCode == HttpStatusCode.ServiceUnavailable)
                            {
                                shouldRetry = true;
                                PauseOnRetry(++retries, maxRetries, statusCode);
                            }
                            else
                            {
                                AmazonSQSException amazonException = null;
                                /* Attempt to deserialize response into ErrorResponse type */
                                try
                                {
                                    XDocument doc = XDocument.Parse(responseBody);
                                    using (XmlReader sr = doc.CreateReader())
                                    {
                                        XmlSerializer serializer    = new XmlSerializer(typeof(ErrorResponse));
                                        ErrorResponse errorResponse = (ErrorResponse)serializer.Deserialize(sr);
                                        Error error = errorResponse.Error.ElementAt(0);

                                        ///* Throw formatted exception with information available from the error response */
                                        amazonException = new AmazonSQSException(
                                            error.Message,
                                            statusCode,
                                            error.Code,
                                            error.Type,
                                            errorResponse.RequestId,
                                            errorResponse.ToXML()
                                            );
                                        throw amazonException;
                                    }
                                }
                                /* Rethrow on deserializer error */
                                catch (Exception e)
                                {
                                    if (e is AmazonSQSException)
                                    {
                                        if (null != OnSQSResponse)
                                        {
                                            OnSQSResponse.Invoke(this, new ResponseEventArgs(amazonException));
                                        }
                                    }
                                    else
                                    {
                                        if (null != OnSQSResponse)
                                        {
                                            OnSQSResponse.Invoke(this, new ResponseEventArgs(ReportAnyErrors(responseBody, statusCode)));
                                        }
                                    }
                                }
                            }
                        }
                    }, request);

                    shouldRetry = false;
                }

                /* Catch other exceptions, attempt to convert to formatted exception,
                 * else rethrow wrapped exception */
                catch (Exception)
                {
                    // Abort the unsuccessful request
                    request.Abort();
                    throw;
                }
            } while (shouldRetry);

            return(response);
        }