Example #1
0
        private RestClientException getRestClientException(HttpWebResponse res, WebException webex)
        {
            string message = "";

            if (res == null && webex != null)
            {
                res = (HttpWebResponse)webex.Response;
            }
            if (res == null)
            {
                message = "Request Failed. Error: " + webex.Message;
            }
            else
            {
                message = string.Format("Request Failed. Received HTTP {0}", (int)res.StatusCode);
            }
            RestClientException ex = null;

            if (webex != null)
            {
                ex = new RestClientException(message, webex);
            }
            else
            {
                ex = new RestClientException(message);
            }
            if (res != null)
            {
                ex.Response     = res;
                ex.ErrorDetails = StringHelper.getJsonAsDictionary((new StreamReader(res.GetResponseStream())).ReadToEnd());
            }
            return(ex);
        }
Example #2
0
 public static Exception CreateFailedException(HttpClient restClient, HttpRequestMessage requestMessage, HttpRequestException ex)
 {
     return(RestClientException.Create(HttpStatusCode.InternalServerError,
                                       ex.Message,
                                       requestMessage.ToRestClientRequest(restClient.BaseAddress),
                                       new Response(string.Empty, 0)));
 }
Example #3
0
        public void RestClientExceptionTest_InstantiationWithMessage_MessageCorrect()
        {
            // Arrange
            const string ExpectedMessage = "Message";

            // Act
            RestClientException target = new RestClientException(ExpectedMessage);

            // Assert
            Assert.AreEqual(ExpectedMessage, target.Message);
        }
Example #4
0
 private void throwError(RestClientException clientException)
 {
     if (clientException.Response.StatusCode == (HttpStatusCode)422)
     {
         var validationError = new ValidationErrorException("Validation has failed", clientException);
         validationError.ErrorDetails = StringHelper.getJsonAsDictionary((new StreamReader(clientException.Response.GetResponseStream())).ReadToEnd());
         throw validationError;
     }
     else
     {
         throw clientException;
     }
 }
        public void RestClientException_default_ctor()
        {
            // Arrange
            const string expectedMessage = "Exception of type 'Activout.RestClient.RestClientException' was thrown.";

            // Act
            var sut = new RestClientException(RequestUri, HttpStatusCode.InternalServerError, null);

            // Assert
            Assert.Null(sut.ErrorResponse);
            Assert.Null(sut.InnerException);
            Assert.Equal(HttpStatusCode.InternalServerError, sut.StatusCode);
            Assert.Equal(expectedMessage, sut.Message);
        }
        public void RestClientException_ctor_string()
        {
            // Arrange
            const string expectedMessage = "message";

            // Act
            var sut = new RestClientException(RequestUri, HttpStatusCode.InternalServerError, expectedMessage);

            // Assert
            Assert.Equal(expectedMessage, sut.ErrorResponse);
            Assert.Null(sut.InnerException);
            Assert.Equal(HttpStatusCode.InternalServerError, sut.StatusCode);
            Assert.Equal(expectedMessage, sut.Message);
        }
Example #7
0
        private ResourceProviderClientException HandleAggregateException(AggregateException aex)
        {
            RestClientException <VmBackupErrorResource> restClientException = aex.InnerException as RestClientException <VmBackupErrorResource>;
            HttpRequestException httpRequestException = aex.InnerException as HttpRequestException;

            if (httpRequestException != null)
            {
                WebException webEx = httpRequestException.InnerException as WebException;
                if (webEx != null)
                {
                    return(new ResourceProviderClientException(webEx.Message, webEx)
                    {
                        HttpStatusCode = HttpStatusCode.BadRequest
                    });
                }

                return(new ResourceProviderClientException(httpRequestException.Message, httpRequestException)
                {
                    HttpStatusCode = HttpStatusCode.BadRequest
                });
            }

            if (restClientException != null)
            {
                VmBackupErrorResource error = restClientException.MessageContent;

                if (error != null)
                {
                    return(new ResourceProviderClientException(error.Message)
                    {
                        HttpStatusCode = restClientException.StatusCode, ErrorCode = error.Code, State = error.State, Severity = error.Severity
                    });
                }
                else
                {
                    return(new ResourceProviderClientException("ServerResources.InternalError")
                    {
                        HttpStatusCode = HttpStatusCode.InternalServerError, ErrorCode = "Constants.UnknownErrorCode"
                    });
                }
            }

            return(new ResourceProviderClientException(aex.InnerException.Message, aex.InnerException)
            {
                HttpStatusCode = HttpStatusCode.InternalServerError
            });
        }
Example #8
0
        public void RestClientExceptionTest_SerializationDeserialization_InputEqualOutput()
        {
            // Arrange
            IOException innerException = new IOException("IOException");
            RestClientException expected = new RestClientException("Message", "ErrorCode", innerException);

            // Act
            RestClientException actual = Deserialize<RestClientException>(Serialize(expected));

            // Assert
            Assert.AreEqual(expected.Message, actual.Message);
            Assert.AreEqual(expected.ErrorCode, actual.ErrorCode);

            Assert.IsNotNull(expected.InnerException);
            Assert.IsNotNull(actual.InnerException);
            Assert.AreEqual(expected.InnerException.Message, actual.InnerException.Message);
        }
        public void RestClientException_serialization_deserialization_test()
        {
            // Arrange
            var innerEx           = new Exception("foo");
            var originalException =
                new RestClientException(RequestUri, HttpStatusCode.InternalServerError, "message", innerEx);
            var buffer    = new byte[4096];
            var ms        = new MemoryStream(buffer);
            var ms2       = new MemoryStream(buffer);
            var formatter = new BinaryFormatter();

            // Act
            formatter.Serialize(ms, originalException);
            var deserializedException = (RestClientException)formatter.Deserialize(ms2);

            // Assert
            Assert.Equal(originalException.StatusCode, deserializedException.StatusCode);
            Assert.Equal(originalException.InnerException.Message, deserializedException.InnerException.Message);
            Assert.Equal(originalException.Message, deserializedException.Message);
            Assert.Equal(originalException.ErrorResponse, deserializedException.ErrorResponse);
        }
        private RestClientException GetRestClientException(HttpWebResponse response, WebException webEx)
        {
            string message;

            if (response == null && webEx != null)
            {
                response = (HttpWebResponse)webEx.Response;
            }

            if (response == null)
            {
                message = "Request Failed. Error: " + webEx.Message;
            }
            else
            {
                message = string.Format("Request Failed. Received HTTP {0}", (int)response.StatusCode);
            }

            RestClientException ex;

            if (webEx != null)
            {
                ex = new RestClientException(message, webEx);
            }
            else
            {
                ex = new RestClientException(message);
            }

            if (response != null)
            {
                ex.Response     = response;
                ex.ErrorDetails = new Dictionary <string, object>();
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    ex.ErrorDetails["Response Message"] = reader.ReadToEnd();
                }
            }
            return(ex);
        }
 public static string ToLogErrorMessage(this RestClientException @this)
 => $"Request: {@this.Request.ToString()}{Environment.NewLine}Response: {@this.Response.ToString()}";
Example #12
0
 public static string ToLogErrorMessage(this RestClientException @this)
 => $"Fecha UTC: {DateTime.UtcNow.ToIsoString()}{Environment.NewLine}" +
 $"Request: {@this.Request?.ToString()}{Environment.NewLine}Response: {@this.Response?.ToString()}{Environment.NewLine}" +
 $"Message: {@this.ToFormattedString()}{Environment.NewLine}StackTrace: {@this.StackTrace}";
Example #13
0
        /// <summary>
        /// Invokes the specified method against the url provided
        /// </summary>
        /// <param name="method">Method.</param>
        /// <param name="url">URL.</param>
        /// <param name="contentType">Content type.</param>
        /// <param name="body">Body.</param>
        /// <param name="query">Query.</param>
        /// <typeparam name="TBody">The 1st type parameter.</typeparam>
        /// <typeparam name="TResult">The 2nd type parameter.</typeparam>
        protected override TResult InvokeInternal <TBody, TResult>(string method, string url, string contentType, WebHeaderCollection additionalHeaders, out WebHeaderCollection responseHeaders, TBody body, NameValueCollection query)
        {
            if (String.IsNullOrEmpty(method))
            {
                throw new ArgumentNullException(nameof(method));
            }
            //if (String.IsNullOrEmpty(url))
            //    throw new ArgumentNullException(nameof(url));


            // Credentials provided ?
            HttpWebRequest requestObj = this.CreateHttpRequest(url, query) as HttpWebRequest;

            if (!String.IsNullOrEmpty(contentType))
            {
                requestObj.ContentType = contentType;
            }
            requestObj.Method = method;

            // Additional headers
            if (additionalHeaders != null)
            {
                foreach (var hdr in additionalHeaders.AllKeys)
                {
                    if (hdr == "If-Modified-Since")
                    {
                        requestObj.IfModifiedSince = DateTime.Parse(additionalHeaders[hdr]);
                    }
                    else
                    {
                        requestObj.Headers.Add(hdr, additionalHeaders[hdr]);
                    }
                }
            }

#if PERFMON
            Stopwatch sw = new Stopwatch();
            sw.Start();
#endif
            // Get request object

            // Body was provided?
            try
            {
                // Try assigned credentials
                IBodySerializer serializer = null;
                if (body != null)
                {
                    // GET Stream,
                    Stream requestStream = null;
                    try
                    {
                        // Get request object
                        var cancellationTokenSource = new CancellationTokenSource();
                        cancellationTokenSource.CancelAfter(this.Description.Endpoint[0].Timeout);
                        using (var requestTask = Task.Run(async() => { return(await requestObj.GetRequestStreamAsync()); }, cancellationTokenSource.Token))
                        {
                            try
                            {
                                requestStream = requestTask.Result;
                            }
                            catch (AggregateException e)
                            {
                                requestObj.Abort();
                                throw e.InnerExceptions.First();
                            }
                        }

                        if (contentType == null && typeof(TResult) != typeof(Object))
                        {
                            throw new ArgumentNullException(nameof(contentType));
                        }

                        serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(contentType, typeof(TBody));
                        // Serialize and compress with deflate
                        using (MemoryStream ms = new MemoryStream())
                        {
                            if (this.Description.Binding.Optimize)
                            {
                                switch ((this.Description.Binding as ServiceClientBinding)?.OptimizationMethod)
                                {
                                case OptimizationMethod.Lzma:
                                    requestObj.Headers.Add("Content-Encoding", "lzma");
                                    using (var df = new LZipStream(new NonDisposingStream(requestStream), CompressionMode.Compress))
                                        serializer.Serialize(df, body);
                                    break;

                                case OptimizationMethod.Bzip2:
                                    requestObj.Headers.Add("Content-Encoding", "bzip2");
                                    using (var df = new BZip2Stream(new NonDisposingStream(requestStream), CompressionMode.Compress, false))
                                        serializer.Serialize(df, body);
                                    break;

                                case OptimizationMethod.Gzip:
                                    requestObj.Headers.Add("Content-Encoding", "gzip");
                                    using (var df = new GZipStream(new NonDisposingStream(requestStream), CompressionMode.Compress))
                                        serializer.Serialize(df, body);
                                    break;

                                case OptimizationMethod.Deflate:
                                    requestObj.Headers.Add("Content-Encoding", "deflate");
                                    using (var df = new DeflateStream(new NonDisposingStream(requestStream), CompressionMode.Compress))
                                        serializer.Serialize(df, body);
                                    break;

                                case OptimizationMethod.None:
                                default:
                                    serializer.Serialize(ms, body);
                                    break;
                                }
                            }
                            else
                            {
                                serializer.Serialize(ms, body);
                            }

                            // Trace
                            if (this.Description.Trace)
                            {
                                this.m_tracer.TraceVerbose("HTTP >> {0}", Convert.ToBase64String(ms.ToArray()));
                            }

                            using (var nms = new MemoryStream(ms.ToArray()))
                                nms.CopyTo(requestStream);
                        }
                    }
                    finally
                    {
                        if (requestStream != null)
                        {
                            requestStream.Dispose();
                        }
                    }
                }

                // Response
                HttpWebResponse response = null;
                try
                {
                    var cancellationTokenSource = new CancellationTokenSource();
                    cancellationTokenSource.CancelAfter(this.Description.Endpoint[0].Timeout);
                    using (var responseTask = Task.Run(async() => { return(await requestObj.GetResponseAsync()); }, cancellationTokenSource.Token))
                    {
                        try
                        {
                            response = (HttpWebResponse)responseTask.Result;
                        }
                        catch (AggregateException e)
                        {
                            requestObj.Abort();
                            throw e.InnerExceptions.First();
                        }
                    }

                    responseHeaders = response.Headers;

                    // No content - does the result want a pointer maybe?
                    if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.Continue || response.StatusCode == HttpStatusCode.NotModified)
                    {
                        return(default(TResult));
                    }
                    else if (response.StatusCode == HttpStatusCode.RedirectKeepVerb)
                    {
                        return(this.InvokeInternal <TBody, TResult>(method, response.Headers[HttpResponseHeader.Location], contentType, additionalHeaders, out responseHeaders, body, query));
                    }
                    else if (response.StatusCode == HttpStatusCode.RedirectMethod)
                    {
                        return(this.InvokeInternal <TBody, TResult>("GET", response.Headers[HttpResponseHeader.Location], contentType, additionalHeaders, out responseHeaders, default(TBody), query));
                    }
                    else
                    {
                        // De-serialize
                        var responseContentType = response.ContentType;
                        if (String.IsNullOrEmpty(responseContentType))
                        {
                            return(default(TResult));
                        }

                        if (responseContentType.Contains(";"))
                        {
                            responseContentType = responseContentType.Substring(0, responseContentType.IndexOf(";"));
                        }

                        if (response.StatusCode == HttpStatusCode.NotModified)
                        {
                            return(default(TResult));
                        }

                        serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(responseContentType, typeof(TResult));

                        TResult retVal = default(TResult);
                        // Compression?
                        using (MemoryStream ms = new MemoryStream())
                        {
                            if (this.Description.Trace)
                            {
                                this.m_tracer.TraceVerbose("Received response {0} : {1} bytes", response.ContentType, response.ContentLength);
                            }

                            response.GetResponseStream().CopyTo(ms);

                            ms.Seek(0, SeekOrigin.Begin);

                            // Trace
                            if (this.Description.Trace)
                            {
                                this.m_tracer.TraceVerbose("HTTP << {0}", Convert.ToBase64String(ms.ToArray()));
                            }

                            switch (response.Headers[HttpResponseHeader.ContentEncoding])
                            {
                            case "deflate":
                                using (DeflateStream df = new DeflateStream(new NonDisposingStream(ms), CompressionMode.Decompress))
                                    retVal = (TResult)serializer.DeSerialize(df);
                                break;

                            case "gzip":
                                using (GZipStream df = new GZipStream(new NonDisposingStream(ms), CompressionMode.Decompress))
                                    retVal = (TResult)serializer.DeSerialize(df);
                                break;

                            case "bzip2":
                                using (var bzs = new BZip2Stream(new NonDisposingStream(ms), CompressionMode.Decompress, false))
                                    retVal = (TResult)serializer.DeSerialize(bzs);
                                break;

                            case "lzma":
                                using (var lzmas = new LZipStream(new NonDisposingStream(ms), CompressionMode.Decompress))
                                    retVal = (TResult)serializer.DeSerialize(lzmas);
                                break;

                            default:
                                retVal = (TResult)serializer.DeSerialize(ms);
                                break;
                            }
                            //retVal = (TResult)serializer.DeSerialize(ms);
                        }

                        return(retVal);
                    }
                }
                finally
                {
                    if (response != null)
                    {
                        response.Close();
                        response.Dispose();
                    }
                    //responseTask.Dispose();
                }
            }
            catch (TimeoutException e)
            {
                this.m_tracer.TraceError("Request timed out:{0}", e.Message);
                throw;
            }
            catch (WebException e) when(e.Response is HttpWebResponse errorResponse && errorResponse.StatusCode == HttpStatusCode.NotModified)
            {
                this.m_tracer.TraceInfo("Server indicates not modified {0} {1} : {2}", method, url, e.Message);
                responseHeaders = errorResponse?.Headers;
                return(default(TResult));
            }
            catch (WebException e) when(e.Response is HttpWebResponse errorResponse && e.Status == WebExceptionStatus.ProtocolError)
            {
                this.m_tracer.TraceError("Error executing {0} {1} : {2}", method, url, e.Message);
                // Deserialize
                object errorResult = null;

                var responseContentType = errorResponse.ContentType;

                if (responseContentType.Contains(";"))
                {
                    responseContentType = responseContentType.Substring(0, responseContentType.IndexOf(";"));
                }

                var ms = new MemoryStream(); // copy response to memory

                errorResponse.GetResponseStream().CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);

                try
                {
                    var serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(responseContentType, typeof(TResult));

                    switch (errorResponse.Headers[HttpResponseHeader.ContentEncoding])
                    {
                    case "deflate":
                        using (DeflateStream df = new DeflateStream(new NonDisposingStream(ms), CompressionMode.Decompress))
                            errorResult = serializer.DeSerialize(df);
                        break;

                    case "gzip":
                        using (GZipStream df = new GZipStream(new NonDisposingStream(ms), CompressionMode.Decompress))
                            errorResult = serializer.DeSerialize(df);
                        break;

                    case "bzip2":
                        using (var bzs = new BZip2Stream(new NonDisposingStream(ms), CompressionMode.Decompress, false))
                            errorResult = serializer.DeSerialize(bzs);
                        break;

                    case "lzma":
                        using (var lzmas = new LZipStream(new NonDisposingStream(ms), CompressionMode.Decompress))
                            errorResult = serializer.DeSerialize(lzmas);
                        break;

                    default:
                        errorResult = serializer.DeSerialize(ms);
                        break;
                    }
                }
                catch
                {
                    errorResult = new RestServiceFault(e);
                }

                Exception exception = null;

                if (errorResult is RestServiceFault rse)
                {
                    exception = new RestClientException <RestServiceFault>(rse, e, e.Status, e.Response);
                }
                else if (errorResponse is TResult)
                {
                    exception = new RestClientException <TResult>((TResult)errorResult, e, e.Status, e.Response);
                }
                else
                {
                    exception = new RestClientException <object>(errorResult, e, e.Status, e.Response);
                }

                switch (errorResponse.StatusCode)
                {
                case HttpStatusCode.Unauthorized:     // Validate the response

                    throw exception;

                case HttpStatusCode.NotModified:
                    responseHeaders = errorResponse?.Headers;
                    return(default(TResult));

                case (HttpStatusCode)422:
                    throw exception;

                default:
                    throw exception;
                }
            }
            catch (WebException e) when(e.Status == WebExceptionStatus.Timeout)
            {
                this.m_tracer.TraceError("Error executing {0} {1} : {2}", method, url, e.Message);
                throw new TimeoutException($"Timeout executing REST operation {method} {url}", e);
            }
            catch (WebException e) when(e.Status == WebExceptionStatus.ConnectFailure)
            {
                this.m_tracer.TraceError("Error executing {0} {1} : {2}", method, url, e.Message);
                if ((e.InnerException as SocketException)?.SocketErrorCode == SocketError.TimedOut)
                {
                    throw new TimeoutException();
                }
                else
                {
                    throw;
                }
            }
            catch (WebException e)
            {
                this.m_tracer.TraceError("Error executing {0} {1} : {2}", method, url, e.Message);
                throw;
            }
            catch (InvalidOperationException e)
            {
                this.m_tracer.TraceError("Invalid Operation: {0}", e.Message);
                throw;
            }

            responseHeaders = new WebHeaderCollection();
            return(default(TResult));
        }
Example #14
0
        /// <summary>
        /// Invokes the specified method against the url provided
        /// </summary>
        /// <param name="method">Method.</param>
        /// <param name="url">URL.</param>
        /// <param name="contentType">Content type.</param>
        /// <param name="body">Body.</param>
        /// <param name="query">Query.</param>
        /// <typeparam name="TBody">The 1st type parameter.</typeparam>
        /// <typeparam name="TResult">The 2nd type parameter.</typeparam>
        protected override TResult InvokeInternal <TBody, TResult>(string method, string url, string contentType, WebHeaderCollection additionalHeaders, out WebHeaderCollection responseHeaders, TBody body, NameValueCollection query)
        {
            if (String.IsNullOrEmpty(method))
            {
                throw new ArgumentNullException(nameof(method));
            }
            //if (String.IsNullOrEmpty(url))
            //    throw new ArgumentNullException(nameof(url));

            // Three times:
            // 1. With provided credential
            // 2. With challenge
            // 3. With challenge again
            for (int i = 0; i < 2; i++)
            {
                // Credentials provided ?
                HttpWebRequest requestObj = this.CreateHttpRequest(url, query) as HttpWebRequest;
                if (!String.IsNullOrEmpty(contentType))
                {
                    requestObj.ContentType = contentType;
                }
                requestObj.Method = method;

                // Additional headers
                if (additionalHeaders != null)
                {
                    foreach (var hdr in additionalHeaders.AllKeys)
                    {
                        if (hdr == "If-Modified-Since")
                        {
                            requestObj.IfModifiedSince = DateTime.Parse(additionalHeaders[hdr]);
                        }
                        else
                        {
                            requestObj.Headers.Add(hdr, additionalHeaders[hdr]);
                        }
                    }
                }

#if PERFMON
                Stopwatch sw = new Stopwatch();
                sw.Start();
#endif
                // Body was provided?
                try
                {
                    // Try assigned credentials
                    IBodySerializer serializer = null;
                    if (body != null)
                    {
                        // GET Stream,
                        Stream requestStream = null;
                        try
                        {
                            // Get request object
                            using (var requestTask = Task.Run(async() => { return(await requestObj.GetRequestStreamAsync()); }))
                            {
                                try
                                {
                                    if (!requestTask.Wait(this.Description.Endpoint[0].Timeout))
                                    {
                                        requestObj.Abort();
                                        throw new TimeoutException();
                                    }

                                    requestStream = requestTask.Result;
                                }
                                catch (AggregateException e)
                                {
                                    requestObj.Abort();
                                    throw e.InnerExceptions.First();
                                }
                            }

                            if (contentType == null && typeof(TResult) != typeof(Object))
                            {
                                throw new ArgumentNullException(nameof(contentType));
                            }

                            serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(contentType, typeof(TBody));
                            // Serialize and compress with deflate
                            using (MemoryStream ms = new MemoryStream())
                            {
                                if (this.Description.Binding.Optimize)
                                {
                                    switch ((this.Description.Binding as ServiceClientBinding)?.OptimizationMethod)
                                    {
                                    case OptimizationMethod.Lzma:
                                        requestObj.Headers.Add("Content-Encoding", "lzma");
                                        using (var df = new LZipStream(requestStream, CompressionMode.Compress, leaveOpen: true))
                                            serializer.Serialize(df, body);
                                        break;

                                    case OptimizationMethod.Bzip2:
                                        requestObj.Headers.Add("Content-Encoding", "bzip2");
                                        using (var df = new BZip2Stream(requestStream, CompressionMode.Compress, leaveOpen: true))
                                            serializer.Serialize(df, body);
                                        break;

                                    case OptimizationMethod.Gzip:
                                        requestObj.Headers.Add("Content-Encoding", "gzip");
                                        using (var df = new GZipStream(requestStream, CompressionMode.Compress, leaveOpen: true))
                                            serializer.Serialize(df, body);
                                        break;

                                    case OptimizationMethod.Deflate:
                                        requestObj.Headers.Add("Content-Encoding", "deflate");
                                        using (var df = new DeflateStream(requestStream, CompressionMode.Compress, leaveOpen: true))
                                            serializer.Serialize(df, body);
                                        break;

                                    case OptimizationMethod.None:
                                    default:
                                        serializer.Serialize(ms, body);
                                        break;
                                    }
                                }
                                else
                                {
                                    serializer.Serialize(ms, body);
                                }

                                // Trace
                                if (this.Description.Trace)
                                {
                                    this.m_tracer.TraceVerbose("HTTP >> {0}", Convert.ToBase64String(ms.ToArray()));
                                }

                                using (var nms = new MemoryStream(ms.ToArray()))
                                    nms.CopyTo(requestStream);
                            }
                        }
                        finally
                        {
                            if (requestStream != null)
                            {
                                requestStream.Dispose();
                            }
                        }
                    }

                    // Response
                    HttpWebResponse response = null;
                    try
                    {
                        // Get request object
                        using (var responseTask = Task.Run(async() => { return(await requestObj.GetResponseAsync()); }))
                        {
                            try
                            {
                                if (!responseTask.Wait(this.Description.Endpoint[0].Timeout))
                                {
                                    requestObj.Abort();
                                    throw new TimeoutException();
                                }
                                response = (HttpWebResponse)responseTask.Result;
                            }
                            catch (AggregateException e)
                            {
                                requestObj.Abort();
                                throw e.InnerExceptions.First();
                            }
                        }


#if PERFMON
                        sw.Stop();
                        ApplicationContext.Current.PerformanceLog(nameof(RestClient), "InvokeInternal", $"{nameof(TBody)}-RCV", sw.Elapsed);
                        sw.Reset();
                        sw.Start();
#endif

                        responseHeaders = response.Headers;
                        var validationResult = this.ValidateResponse(response);
                        if (validationResult != ServiceClientErrorType.Valid)
                        {
                            this.m_tracer.TraceError("Response failed validation : {0}", validationResult);
                            throw new WebException(Strings.err_response_failed_validation, null, WebExceptionStatus.Success, response);
                        }

                        // No content - does the result want a pointer maybe?
                        if (response.StatusCode == HttpStatusCode.NoContent)
                        {
                            return(default(TResult));
                        }
                        else
                        {
                            // De-serialize
                            var responseContentType = response.ContentType;
                            if (String.IsNullOrEmpty(responseContentType))
                            {
                                return(default(TResult));
                            }

                            if (responseContentType.Contains(";"))
                            {
                                responseContentType = responseContentType.Substring(0, responseContentType.IndexOf(";"));
                            }

                            if (response.StatusCode == HttpStatusCode.NotModified)
                            {
                                return(default(TResult));
                            }

                            serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(responseContentType, typeof(TResult));

                            TResult retVal = default(TResult);
                            // Compression?
                            using (MemoryStream ms = new MemoryStream())
                            {
                                if (this.Description.Trace)
                                {
                                    this.m_tracer.TraceVerbose("Received response {0} : {1} bytes", response.ContentType, response.ContentLength);
                                }

                                response.GetResponseStream().CopyTo(ms);

#if PERFMON
                                sw.Stop();
                                ApplicationContext.Current.PerformanceLog(nameof(RestClient), "InvokeInternal", $"{nameof(TBody)}-INT", sw.Elapsed);
                                sw.Reset();
                                sw.Start();
#endif

                                ms.Seek(0, SeekOrigin.Begin);

                                // Trace
                                if (this.Description.Trace)
                                {
                                    this.m_tracer.TraceVerbose("HTTP << {0}", Convert.ToBase64String(ms.ToArray()));
                                }

                                switch (response.Headers[HttpResponseHeader.ContentEncoding])
                                {
                                case "deflate":
                                    using (DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        retVal = (TResult)serializer.DeSerialize(df);
                                    break;

                                case "gzip":
                                    using (GZipStream df = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        retVal = (TResult)serializer.DeSerialize(df);
                                    break;

                                case "bzip2":
                                    using (var bzs = new BZip2Stream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        retVal = (TResult)serializer.DeSerialize(bzs);
                                    break;

                                case "lzma":
                                    using (var lzmas = new LZipStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        retVal = (TResult)serializer.DeSerialize(lzmas);
                                    break;

                                default:
                                    retVal = (TResult)serializer.DeSerialize(ms);
                                    break;
                                }
                                //retVal = (TResult)serializer.DeSerialize(ms);
                            }

#if PERFMON
                            sw.Stop();
                            ApplicationContext.Current.PerformanceLog(nameof(RestClient), "InvokeInternal", $"{nameof(TBody)}-RET", sw.Elapsed);
                            sw.Reset();
                            sw.Start();
#endif

                            return(retVal);
                        }
                    }
                    finally
                    {
                        if (response != null)
                        {
                            response.Close();
                            response.Dispose();
                        }
                        //responseTask.Dispose();
                    }
                }
                catch (TimeoutException e)
                {
                    this.m_tracer.TraceError("Request timed out:{0}", e.Message);
                    throw;
                }
                catch (WebException e)
                {
                    var errorResponse = (e.Response as HttpWebResponse);
                    if (errorResponse?.StatusCode == HttpStatusCode.NotModified)
                    {
                        this.m_tracer.TraceInfo("Server indicates not modified {0} {1} : {2}", method, url, e.Message);
                        responseHeaders = errorResponse?.Headers;
                        return(default(TResult));
                    }

                    this.m_tracer.TraceError("Error executing {0} {1} : {2}", method, url, e.Message);

                    // status
                    switch (e.Status)
                    {
                    case WebExceptionStatus.ProtocolError:

                        // Deserialize
                        object errorResult = default(ErrorResult);

                        var responseContentType = errorResponse.ContentType;
                        if (responseContentType.Contains(";"))
                        {
                            responseContentType = responseContentType.Substring(0, responseContentType.IndexOf(";"));
                        }

                        var ms = new MemoryStream();     // copy response to memory
                        errorResponse.GetResponseStream().CopyTo(ms);
                        ms.Seek(0, SeekOrigin.Begin);

                        try
                        {
                            var serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(responseContentType, typeof(TResult));

                            try
                            {
                                switch (errorResponse.Headers[HttpResponseHeader.ContentEncoding])
                                {
                                case "deflate":
                                    using (DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        errorResult = (TResult)serializer.DeSerialize(df);
                                    break;

                                case "gzip":
                                    using (GZipStream df = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        errorResult = (TResult)serializer.DeSerialize(df);
                                    break;

                                case "bzip2":
                                    using (var bzs = new BZip2Stream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        errorResult = (TResult)serializer.DeSerialize(bzs);
                                    break;

                                case "lzma":
                                    using (var lzmas = new LZipStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        errorResult = (TResult)serializer.DeSerialize(lzmas);
                                    break;

                                default:
                                    errorResult = (TResult)serializer.DeSerialize(ms);
                                    break;
                                }
                            }
                            catch
                            {
                                serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(responseContentType, typeof(ErrorResult));

                                ms.Seek(0, SeekOrigin.Begin);     // rewind and try generic error codes
                                switch (errorResponse.Headers[HttpResponseHeader.ContentEncoding])
                                {
                                case "deflate":
                                    using (DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        errorResult = (ErrorResult)serializer.DeSerialize(df);
                                    break;

                                case "gzip":
                                    using (GZipStream df = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        errorResult = (ErrorResult)serializer.DeSerialize(df);
                                    break;

                                case "bzip2":
                                    using (var bzs = new BZip2Stream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        errorResult = (ErrorResult)serializer.DeSerialize(bzs);
                                    break;

                                case "lzma":
                                    using (var lzmas = new LZipStream(ms, CompressionMode.Decompress, leaveOpen: true))
                                        errorResult = (ErrorResult)serializer.DeSerialize(lzmas);
                                    break;

                                default:
                                    errorResult = (ErrorResult)serializer.DeSerialize(ms);
                                    break;
                                }
                            }
                            //result = (TResult)serializer.DeSerialize(errorResponse.GetResponseStream());
                        }
                        catch (Exception dse)
                        {
                            this.m_tracer.TraceError("Could not de-serialize error response! {0}", dse.Message);
                        }

                        Exception exception = null;
                        if (errorResult is TResult)
                        {
                            exception = new RestClientException <TResult>((TResult)errorResult, e, e.Status, e.Response);
                        }
                        else
                        {
                            exception = new RestClientException <ErrorResult>((ErrorResult)errorResult, e, e.Status, e.Response);
                        }

                        switch (errorResponse.StatusCode)
                        {
                        case HttpStatusCode.Unauthorized:         // Validate the response
                            if (this.ValidateResponse(errorResponse) != ServiceClientErrorType.Valid)
                            {
                                throw exception;
                            }
                            break;

                        case HttpStatusCode.NotModified:
                            responseHeaders = errorResponse?.Headers;
                            return(default(TResult));

                        default:
                            throw exception;
                        }
                        break;

                    case WebExceptionStatus.ConnectFailure:
                        if ((e.InnerException as SocketException)?.SocketErrorCode == SocketError.TimedOut)
                        {
                            throw new TimeoutException();
                        }
                        else
                        {
                            throw;
                        }

                    case WebExceptionStatus.Timeout:
                        throw new TimeoutException();

                    default:
                        throw;
                    }
                }
            }

            responseHeaders = new WebHeaderCollection();
            return(default(TResult));
        }
 public static void RemoveRestClientExceptionErrors(this ScenarioContext scenarioContext, RestClientException response)
 {
     scenarioContext.AllRestClientExceptionErrors().Remove(response);
 }
Example #16
0
 public static RestClientException CreateFailedException(RSharp.RestClient restClient, RSharp.IRestResponse restResponse)
 => RestClientException.Create(restResponse.StatusCode,
                               restResponse.StatusDescription,
                               restResponse.Request.ToRestClientRequest(restClient.BaseUrl),
                               restResponse.ToRestClientRequest());
Example #17
0
 public static RestClientException CreateFailedException(HttpClient restClient, Request request, Response response, HttpResponseMessage httpResponse)
 => RestClientException.Create(httpResponse.StatusCode,
                               httpResponse.ReasonPhrase,
                               request,
                               response);