示例#1
0
        /// <summary>
        /// Begins the read response string.
        /// </summary>
        private async Task <string> ReadResponseStringAsync()
        {
            if (isRequestSentToServer)
            {
                throw new InvalidOperationException("Request was already sent to the server, cannot retry request.");
            }

            isRequestSentToServer = true;

            await WaitForTask;

            if (writeCalled == false)
            {
                Task <HttpResponseMessage> sendTask;
                sendTask = httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(Method), Url))
                           .ConvertSecurityExceptionToServerNotFound()
                           // .MaterializeBadRequestAsException()
                           .AddUrlIfFaulting(new Uri(Url));
                Response = await sendTask;
                SetResponseHeaders(Response);
            }


            if (Response.IsSuccessStatusCode == false)
            {
                throw ErrorResponseException.FromResponseMessage(Response);
            }

            return(await ReadStringInternal());

            ;
        }
示例#2
0
        public void PutContainer(string containerName)
        {
            var url = GetUrl(containerName) + "?restype=container";

            var now     = SystemTime.UtcNow;
            var content = new EmptyContent
            {
                Headers =
                {
                    { "x-ms-date",    now.ToString("R") },
                    { "x-ms-version", "2011-08-18"      },
                }
            };

            var client = GetClient();

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("PUT", url, content.Headers);

            var response = AsyncHelpers.RunSync(() => client.PutAsync(url, content));

            if (response.IsSuccessStatusCode)
            {
                return;
            }

            if (response.StatusCode == HttpStatusCode.Conflict)
            {
                return;
            }

            throw ErrorResponseException.FromResponseMessage(response);
        }
示例#3
0
        public void PutBlob(string containerName, string key, Stream stream, Dictionary <string, string> metadata)
        {
            var url = GetUrl(containerName) + "/" + key;

            var now     = SystemTime.UtcNow;
            var content = new StreamContent(stream)
            {
                Headers =
                {
                    { "x-ms-date",      now.ToString("R")                                    },
                    { "x-ms-version",   "2011-08-18"                                         },
                    { "x-ms-blob-type", "BlockBlob"                                          },
                    { "Content-Length", stream.Length.ToString(CultureInfo.InvariantCulture) }
                }
            };

            foreach (var metadataKey in metadata.Keys)
            {
                content.Headers.Add("x-ms-meta-" + metadataKey.ToLower(), metadata[metadataKey]);
            }

            var client = GetClient(TimeSpan.FromHours(1));

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("PUT", url, content.Headers);

            var response = AsyncHelpers.RunSync(() => client.PutAsync(url, content));

            if (response.IsSuccessStatusCode)
            {
                return;
            }

            throw ErrorResponseException.FromResponseMessage(response);
        }
示例#4
0
        public async Task PutContainer()
        {
            var url = azureServerUrl + "?restype=container";

            var now     = SystemTime.UtcNow;
            var content = new EmptyContent
            {
                Headers =
                {
                    { "x-ms-date",    now.ToString("R")   },
                    { "x-ms-version", AzureStorageVersion },
                }
            };

            var client = GetClient();

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("PUT", url, content.Headers);

            var response = await client.PutAsync(url, content).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                return;
            }

            if (response.StatusCode == HttpStatusCode.Conflict)
            {
                return;
            }

            throw ErrorResponseException.FromResponseMessage(response);
        }
示例#5
0
        private async Task PutBlockList(string baseUrl, List <string> blockIds, Dictionary <string, string> metadata)
        {
            var url       = baseUrl + "?comp=blocklist";
            var now       = SystemTime.UtcNow;
            var doc       = CreateXmlDocument(blockIds);
            var xmlString = doc.OuterXml;

            var content = new StringContent(xmlString, Encoding.UTF8, "text/plain")
            {
                Headers =
                {
                    { "x-ms-date",      now.ToString("R")                                                               },
                    { "x-ms-version",   AzureStorageVersion                                                             },
                    { "Content-Length", Encoding.UTF8.GetBytes(xmlString).Length.ToString(CultureInfo.InvariantCulture) }
                }
            };

            foreach (var metadataKey in metadata.Keys)
            {
                content.Headers.Add("x-ms-meta-" + metadataKey.ToLower(), metadata[metadataKey]);
            }

            var client = GetClient(TimeSpan.FromHours(1));

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("PUT", url, content.Headers);

            var response = await client.PutAsync(url, content).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                return;
            }

            throw ErrorResponseException.FromResponseMessage(response);
        }
示例#6
0
        private async Task PutBlock(byte[] streamAsByteArray, HttpClient client,
                                    string url, CancellationTokenSource cts, bool retryRequest)
        {
            var now = SystemTime.UtcNow;
            //stream is disposed by the HttpClient
            var stream  = new MemoryStream(streamAsByteArray);
            var content = new StreamContent(stream)
            {
                Headers =
                {
                    { "x-ms-date",      now.ToString("R")                                    },
                    { "x-ms-version",   AzureStorageVersion                                  },
                    { "Content-Length", stream.Length.ToString(CultureInfo.InvariantCulture) }
                }
            };

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("PUT", url, content.Headers);

            HttpResponseMessage response = null;

            try
            {
                response = await client.PutAsync(url, content, cts.Token).ConfigureAwait(false);

                if (response.IsSuccessStatusCode)
                {
                    return;
                }
            }
            catch (Exception)
            {
                if (cts.IsCancellationRequested)
                {
                    return;
                }

                if (retryRequest == false)
                {
                    throw;
                }
            }

            if (retryRequest == false ||
                (response != null && response.StatusCode == HttpStatusCode.RequestEntityTooLarge))
            {
                throw ErrorResponseException.FromResponseMessage(response);
            }

            //wait for one second before trying again to send the request
            //maybe there was a network issue?
            await Task.Delay(1000).ConfigureAwait(false);

            await PutBlock(streamAsByteArray, client, url, cts, retryRequest : false).ConfigureAwait(false);
        }
示例#7
0
        public async Task WriteAsync(RavenJToken tokenToWrite)
        {
            writeCalled = true;
            Response    = await httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(Method), Url)
            {
                Content = new JsonContent(tokenToWrite)
            });

            if (Response.IsSuccessStatusCode == false)
            {
                throw ErrorResponseException.FromResponseMessage(Response);
            }
        }
示例#8
0
        public async Task JsonErrorsShouldIncludeOriginalData()
        {
            var responseMesage = new HttpResponseMessage
            {
                ReasonPhrase = "<>,./:",
                Content      = new MultiGetSafeStringContent("<>,./:")
            };

            var responseException = ErrorResponseException.FromResponseMessage(responseMesage, true);
            var exception         = await AssertAsync.Throws <InvalidOperationException>(async() => await responseException.TryReadErrorResponseObject <string>());

            Assert.Contains("Exception occured reading the string: ", exception.Message);
        }
示例#9
0
        private static async Task <ErrorResponseException> CreateErrorResponseExceptionAsync(HttpResponseMessage response)
        {
            using (var sr = new StreamReader(await response.GetResponseStreamWithHttpDecompression().ConfigureAwait(false)))
            {
                var readToEnd = sr.ReadToEnd();

                if (string.IsNullOrWhiteSpace(readToEnd))
                {
                    throw ErrorResponseException.FromResponseMessage(response);
                }

                RavenJObject ravenJObject;
                try
                {
                    ravenJObject = RavenJObject.Parse(readToEnd);
                }
                catch (Exception e)
                {
                    throw new ErrorResponseException(response, readToEnd, e);
                }

                if (response.StatusCode == HttpStatusCode.BadRequest && ravenJObject.ContainsKey("Message"))
                {
                    throw new BadRequestException(ravenJObject.Value <string>("Message"), ErrorResponseException.FromResponseMessage(response));
                }

                if (ravenJObject.ContainsKey("Error"))
                {
                    var sb = new StringBuilder();
                    foreach (var prop in ravenJObject)
                    {
                        if (prop.Key == "Error")
                        {
                            continue;
                        }

                        sb.Append(prop.Key).Append(": ").AppendLine(prop.Value.ToString(Formatting.Indented));
                    }

                    if (sb.Length > 0)
                    {
                        sb.AppendLine();
                    }
                    sb.Append(ravenJObject.Value <string>("Error"));

                    throw new ErrorResponseException(response, sb.ToString(), readToEnd);
                }

                throw new ErrorResponseException(response, readToEnd);
            }
        }
        public async static Task AssertNotFailingResponse(this HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                return;
            }

            using (var sr = new StreamReader(await response.GetResponseStreamWithHttpDecompression().ConfigureAwait(false)))
            {
                var readToEnd = sr.ReadToEnd();

                if (string.IsNullOrWhiteSpace(readToEnd))
                {
                    throw ErrorResponseException.FromResponseMessage(response);
                }

                RavenJObject ravenJObject;
                try
                {
                    ravenJObject = RavenJObject.Parse(readToEnd);
                }
                catch (Exception e)
                {
                    throw new ErrorResponseException(response, readToEnd, e);
                }

                if (ravenJObject.ContainsKey("Error"))
                {
                    var sb = new StringBuilder();
                    foreach (var prop in ravenJObject)
                    {
                        if (prop.Key == "Error")
                        {
                            continue;
                        }

                        sb.Append(prop.Key).Append(": ").AppendLine(prop.Value.ToString(Formatting.Indented));
                    }

                    if (sb.Length > 0)
                    {
                        sb.AppendLine();
                    }
                    sb.Append(ravenJObject.Value <string>("Error"));

                    throw new ErrorResponseException(response, sb.ToString(), readToEnd);
                }

                throw new ErrorResponseException(response, readToEnd);
            }
        }
示例#11
0
        /// <summary>
        /// Begins the write operation
        /// </summary>
        public async Task WriteAsync(Stream stream)
        {
            writeCalled = true;
            postedData  = stream;

            Response = await httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(Method), Url)
            {
                Content = new CompressedStreamContent(stream, factory.DisableRequestCompression)
            });

            if (Response.IsSuccessStatusCode == false)
            {
                throw ErrorResponseException.FromResponseMessage(Response);
            }
        }
示例#12
0
        /// <summary>
        /// Begins the write operation
        /// </summary>
        public async Task WriteAsync(string data)
        {
            await WaitForTask;

            writeCalled = true;
            Response    = await httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(Method), Url)
            {
                Content = new CompressedStringContent(data, factory.DisableRequestCompression),
            });

            if (Response.IsSuccessStatusCode == false)
            {
                throw ErrorResponseException.FromResponseMessage(Response);
            }
        }
示例#13
0
        public async Task <byte[]> ReadResponseBytesAsync()
        {
            await WaitForTask;

            Response = await httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(Method), Url))
                       .ConvertSecurityExceptionToServerNotFound()
                       .AddUrlIfFaulting(new Uri(Url));

            SetResponseHeaders(Response);
            if (Response.IsSuccessStatusCode == false)
            {
                throw ErrorResponseException.FromResponseMessage(Response);
            }

            // TODO: Use RetryIfNeedTo(task, ReadResponseBytesAsync)
            return(ConvertStreamToBytes(await Response.GetResponseStreamWithHttpDecompression()));
        }
示例#14
0
        public async Task <Blob> GetObject(string bucketName, string key)
        {
            await ValidateAwsRegion();

            var url = GetUrl(bucketName) + "/" + key;

            var now = SystemTime.UtcNow;

            var payloadHash = RavenAwsHelper.CalculatePayloadHash(null);

            var requestMessage = new HttpRequestMessage(HttpMethods.Get, url)
            {
                Headers =
                {
                    { "x-amz-date",           RavenAwsHelper.ConvertToString(now) },
                    { "x-amz-content-sha256", payloadHash                         }
                }
            };

            var headers = ConvertToHeaders(bucketName, requestMessage.Headers);

            var client = GetClient();

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue(HttpMethods.Get, url, now, headers);

            var response = await client.SendAsync(requestMessage);

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }

            if (response.IsSuccessStatusCode == false)
            {
                throw ErrorResponseException.FromResponseMessage(response);
            }

            var data = await response.Content.ReadAsStreamAsync();

            var metadataHeaders = response.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault());

            return(new Blob(data, metadataHeaders));
        }
示例#15
0
        public async Task PutBlob(string key, Stream stream, Dictionary <string, string> metadata)
        {
            if (stream.Length > MaxUploadPutBlobInBytes)
            {
                //for blobs over 64MB
                await PutBlockApi(key, stream, metadata).ConfigureAwait(false);

                return;
            }

            var url = azureServerUrl + "/" + key;

            var now     = SystemTime.UtcNow;
            var content = new StreamContent(stream)
            {
                Headers =
                {
                    { "x-ms-date",      now.ToString("R")                                    },
                    { "x-ms-version",   AzureStorageVersion                                  },
                    { "x-ms-blob-type", "BlockBlob"                                          },
                    { "Content-Length", stream.Length.ToString(CultureInfo.InvariantCulture) }
                }
            };

            foreach (var metadataKey in metadata.Keys)
            {
                content.Headers.Add("x-ms-meta-" + metadataKey.ToLower(), metadata[metadataKey]);
            }

            var client = GetClient(TimeSpan.FromHours(1));

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("PUT", url, content.Headers);

            var response = await client.PutAsync(url, content).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                return;
            }

            throw ErrorResponseException.FromResponseMessage(response);
        }
        public async Task <string> UploadArchive(string glacierVaultName, Stream stream, string archiveDescription, int timeoutInSeconds)
        {
            await ValidateAwsRegion();

            var url = $"{GetUrl(null)}/-/vaults/{glacierVaultName}/archives";

            var now = SystemTime.UtcNow;

            var payloadHash     = RavenAwsHelper.CalculatePayloadHash(stream);
            var payloadTreeHash = RavenAwsHelper.CalculatePayloadTreeHash(stream);

            var content = new StreamContent(stream)
            {
                Headers =
                {
                    { "x-amz-glacier-version",     "2012-06-01"                        },
                    { "x-amz-date",                RavenAwsHelper.ConvertToString(now) },
                    { "x-amz-content-sha256",      payloadHash                         },
                    { "x-amz-sha256-tree-hash",    payloadTreeHash                     },
                    { "x-amz-archive-description", archiveDescription                  }
                }
            };

            var headers = ConvertToHeaders(glacierVaultName, content.Headers);

            var client = GetClient(TimeSpan.FromSeconds(timeoutInSeconds));
            var authorizationHeaderValue = CalculateAuthorizationHeaderValue(HttpMethods.Post, url, now, headers);

            client.DefaultRequestHeaders.Authorization = authorizationHeaderValue;

            var response = await client.PostAsync(url, content);

            if (response.IsSuccessStatusCode)
            {
                return(ReadArchiveId(response));
            }

            throw ErrorResponseException.FromResponseMessage(response);
        }
示例#17
0
        public void PutObject(string bucketName, string key, Stream stream, Dictionary <string, string> metadata, int timeoutInSeconds)
        {
            var url = GetUrl(bucketName) + "/" + key;

            var now = SystemTime.UtcNow;

            var payloadHash = RavenAwsHelper.CalculatePayloadHash(stream);

            var content = new StreamContent(stream)
            {
                Headers =
                {
                    { "x-amz-date",           RavenAwsHelper.ConvertToString(now) },
                    { "x-amz-content-sha256", payloadHash                         }
                }
            };

            foreach (var metadataKey in metadata.Keys)
            {
                content.Headers.Add("x-amz-meta-" + metadataKey.ToLower(), metadata[metadataKey]);
            }

            var headers = ConvertToHeaders(bucketName, content.Headers);

            var client = GetClient(TimeSpan.FromSeconds(timeoutInSeconds));
            var authorizationHeaderValue = CalculateAuthorizationHeaderValue("PUT", url, now, headers);

            client.DefaultRequestHeaders.Authorization = authorizationHeaderValue;

            var response = AsyncHelpers.RunSync(() => client.PutAsync(url, content));

            if (response.IsSuccessStatusCode)
            {
                return;
            }

            throw ErrorResponseException.FromResponseMessage(response);
        }
示例#18
0
        public async Task <Blob> GetBlob(string key)
        {
            var url = azureServerUrl + "/" + key;

            var now = SystemTime.UtcNow;

            var requestMessage = new HttpRequestMessage(HttpMethods.Get, url)
            {
                Headers =
                {
                    { "x-ms-date",    now.ToString("R")   },
                    { "x-ms-version", AzureStorageVersion }
                }
            };

            var client = GetClient();

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("GET", url, requestMessage.Headers);

            var response = await client.SendAsync(requestMessage).ConfigureAwait(false);

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }

            if (response.IsSuccessStatusCode == false)
            {
                throw ErrorResponseException.FromResponseMessage(response);
            }

            var data = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

            var headers = response.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault());

            return(new Blob(data, headers));
        }
示例#19
0
        public Blob GetBlob(string containerName, string key)
        {
            var url = GetUrl(containerName) + "/" + key;

            var now = SystemTime.UtcNow;

            var requestMessage = new HttpRequestMessage(HttpMethods.Get, url)
            {
                Headers =
                {
                    { "x-ms-date",    now.ToString("R") },
                    { "x-ms-version", "2011-08-18"      }
                }
            };

            var client = GetClient();

            client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("GET", url, requestMessage.Headers);

            var response = AsyncHelpers.RunSync(() => client.SendAsync(requestMessage));

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }

            if (response.IsSuccessStatusCode == false)
            {
                throw ErrorResponseException.FromResponseMessage(response);
            }

            var data    = AsyncHelpers.RunSync(() => response.Content.ReadAsStreamAsync());
            var headers = response.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault());

            return(new Blob(data, headers));
        }
示例#20
0
        public async Task <Action <HttpClient> > DoOAuthRequestAsync(string baseUrl, string oauthSource, string apiKey)
        {
            if (oauthSource == null)
            {
                throw new ArgumentNullException("oauthSource");
            }

            string serverRSAExponent = null;
            string serverRSAModulus  = null;
            string challenge         = null;

            // Note that at two tries will be needed in the normal case.
            // The first try will get back a challenge,
            // the second try will try authentication. If something goes wrong server-side though
            // (e.g. the server was just rebooted or the challenge timed out for some reason), we
            // might get a new challenge back, so we try a third time just in case.
            int tries = 0;

            while (true)
            {
                tries++;

#if !SILVERLIGHT && !NETFX_CORE
                var handler = new WebRequestHandler();
#else
                var handler = new HttpClientHandler();
#endif

                var httpClient = new HttpClient(handler);
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("grant_type", "client_credentials");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")
                {
                    CharSet = "UTF-8"
                });

                string data = null;
                if (!string.IsNullOrEmpty(serverRSAExponent) && !string.IsNullOrEmpty(serverRSAModulus) && !string.IsNullOrEmpty(challenge))
                {
                    var exponent = OAuthHelper.ParseBytes(serverRSAExponent);
                    var modulus  = OAuthHelper.ParseBytes(serverRSAModulus);

                    var apiKeyParts = apiKey.Split(new[] { '/' }, StringSplitOptions.None);
                    if (apiKeyParts.Length > 2)
                    {
                        apiKeyParts[1] = string.Join("/", apiKeyParts.Skip(1));
                    }
                    if (apiKeyParts.Length < 2)
                    {
                        throw new InvalidOperationException("Invalid API key");
                    }

                    var apiKeyName = apiKeyParts[0].Trim();
                    var apiSecret  = apiKeyParts[1].Trim();

                    data = OAuthHelper.DictionaryToString(new Dictionary <string, string>
                    {
                        { OAuthHelper.Keys.RSAExponent, serverRSAExponent },
                        { OAuthHelper.Keys.RSAModulus, serverRSAModulus },
                        {
                            OAuthHelper.Keys.EncryptedData,
                            OAuthHelper.EncryptAsymmetric(exponent, modulus, OAuthHelper.DictionaryToString(new Dictionary <string, string>
                            {
                                { OAuthHelper.Keys.APIKeyName, apiKeyName },
                                { OAuthHelper.Keys.Challenge, challenge },
                                { OAuthHelper.Keys.Response, OAuthHelper.Hash(string.Format(OAuthHelper.Keys.ResponseFormat, challenge, apiSecret)) }
                            }))
                        }
                    });
                }

                var requestUri = oauthSource
#if SILVERLIGHT
                                 .NoCache()
#endif
                ;

                var response = await httpClient.PostAsync(requestUri, data != null?(HttpContent) new CompressedStringContent(data, true) : new StringContent(""))
                               .AddUrlIfFaulting(new Uri(requestUri))
                               .ConvertSecurityExceptionToServerNotFound();

                if (response.IsSuccessStatusCode == false)
                {
                    // We've already tried three times and failed
                    if (tries >= 3)
                    {
                        throw ErrorResponseException.FromResponseMessage(response);
                    }

                    if (response.StatusCode != HttpStatusCode.PreconditionFailed)
                    {
                        throw ErrorResponseException.FromResponseMessage(response);
                    }

                    var header = response.Headers.GetFirstValue("WWW-Authenticate");
                    if (header == null || header.StartsWith(OAuthHelper.Keys.WWWAuthenticateHeaderKey) == false)
                    {
                        throw new ErrorResponseException(response, "Got invalid WWW-Authenticate value");
                    }

                    var challengeDictionary = OAuthHelper.ParseDictionary(header.Substring(OAuthHelper.Keys.WWWAuthenticateHeaderKey.Length).Trim());
                    serverRSAExponent = challengeDictionary.GetOrDefault(OAuthHelper.Keys.RSAExponent);
                    serverRSAModulus  = challengeDictionary.GetOrDefault(OAuthHelper.Keys.RSAModulus);
                    challenge         = challengeDictionary.GetOrDefault(OAuthHelper.Keys.Challenge);

                    if (string.IsNullOrEmpty(serverRSAExponent) || string.IsNullOrEmpty(serverRSAModulus) || string.IsNullOrEmpty(challenge))
                    {
                        throw new InvalidOperationException("Invalid response from server, could not parse raven authentication information: " + header);
                    }

                    continue;
                }

                using (var stream = await response.GetResponseStreamWithHttpDecompression())
                    using (var reader = new StreamReader(stream))
                    {
                        CurrentOauthToken = reader.ReadToEnd();


#if SILVERLIGHT
                        BrowserCookieToAllowUserToUseStandardRequests(baseUrl, reader.ReadToEnd());
#endif
                        return((Action <HttpClient>)(SetAuthorization));
                    }
            }
        }
示例#21
0
        private async Task <RavenJToken> CheckForErrorsAndReturnCachedResultIfAnyAsync(bool readErrorString)
        {
            if (Response.IsSuccessStatusCode)
            {
                return(null);
            }
            if (Response.StatusCode == HttpStatusCode.Unauthorized ||
                Response.StatusCode == HttpStatusCode.NotFound ||
                Response.StatusCode == HttpStatusCode.Conflict)
            {
                if (factory.CanLogRequest)
                {
                    factory.OnLogRequest(owner, new RequestResultArgs
                    {
                        DurationMilliseconds = CalculateDuration(),
                        Method     = Method,
                        HttpResult = (int)Response.StatusCode,
                        Status     = RequestStatus.ErrorOnServer,
                        Result     = Response.StatusCode.ToString(),
                        Url        = Url,
                        PostedData = postedData
                    });
                }


                throw ErrorResponseException.FromResponseMessage(Response, readErrorString);
            }

            if (Response.StatusCode == HttpStatusCode.NotModified &&
                CachedRequestDetails != null)
            {
                factory.UpdateCacheTime(this);
                var result = factory.GetCachedResponse(this, ResponseHeaders);

                // here we explicitly need to get Response.Headers, and NOT ResponseHeaders because we are
                // getting the value _right now_ from the secondary, and don't care about the 304, the force check
                // is still valid
                HandleReplicationStatusChanges(ResponseHeaders, primaryUrl, operationUrl);

                if (factory.CanLogRequest)
                {
                    factory.OnLogRequest(owner, new RequestResultArgs
                    {
                        DurationMilliseconds = CalculateDuration(),
                        Method     = Method,
                        HttpResult = (int)Response.StatusCode,
                        Status     = RequestStatus.Cached,
                        Result     = result.ToString(),
                        Url        = Url,
                        PostedData = postedData
                    });
                }


                return(result);
            }


            using (var sr = new StreamReader(await Response.GetResponseStreamWithHttpDecompression().ConfigureAwait(false)))
            {
                var readToEnd = sr.ReadToEnd();

                if (factory.CanLogRequest)
                {
                    factory.OnLogRequest(owner, new RequestResultArgs
                    {
                        DurationMilliseconds = CalculateDuration(),
                        Method     = Method,
                        HttpResult = (int)Response.StatusCode,
                        Status     = RequestStatus.Cached,
                        Result     = readToEnd,
                        Url        = Url,
                        PostedData = postedData
                    });
                }

                if (string.IsNullOrWhiteSpace(readToEnd))
                {
                    throw ErrorResponseException.FromResponseMessage(Response);
                }

                RavenJObject ravenJObject;
                try
                {
                    ravenJObject = RavenJObject.Parse(readToEnd);
                }
                catch (Exception e)
                {
                    throw new ErrorResponseException(Response, readToEnd, e);
                }
                if (ravenJObject.ContainsKey("IndexDefinitionProperty"))
                {
                    throw new IndexCompilationException(ravenJObject.Value <string>("Message"))
                          {
                              IndexDefinitionProperty = ravenJObject.Value <string>("IndexDefinitionProperty"),
                              ProblematicText         = ravenJObject.Value <string>("ProblematicText")
                          };
                }
                if (Response.StatusCode == HttpStatusCode.BadRequest && ravenJObject.ContainsKey("Message"))
                {
                    throw new BadRequestException(ravenJObject.Value <string>("Message"), ErrorResponseException.FromResponseMessage(Response));
                }
                if (ravenJObject.ContainsKey("Error"))
                {
                    var sb = new StringBuilder();
                    foreach (var prop in ravenJObject)
                    {
                        if (prop.Key == "Error")
                        {
                            continue;
                        }

                        sb.Append(prop.Key).Append(": ").AppendLine(prop.Value.ToString(Formatting.Indented));
                    }

                    if (sb.Length > 0)
                    {
                        sb.AppendLine();
                    }
                    sb.Append(ravenJObject.Value <string>("Error"));

                    throw new ErrorResponseException(Response, sb.ToString(), readToEnd);
                }
                throw new ErrorResponseException(Response, readToEnd);
            }
        }
示例#22
0
        private async Task <RavenJToken> CheckForErrorsAndReturnCachedResultIfAnyAsync()
        {
            if (Response.IsSuccessStatusCode == false)
            {
                if (Response.StatusCode == HttpStatusCode.Unauthorized ||
                    Response.StatusCode == HttpStatusCode.NotFound ||
                    Response.StatusCode == HttpStatusCode.Conflict)
                {
                    throw ErrorResponseException.FromResponseMessage(Response);
                }

                using (var sr = new StreamReader(await Response.GetResponseStreamWithHttpDecompression()))
                {
                    var readToEnd = sr.ReadToEnd();

                    if (string.IsNullOrWhiteSpace(readToEnd))
                    {
                        throw ErrorResponseException.FromResponseMessage(Response);
                    }

                    RavenJObject ravenJObject;
                    try
                    {
                        ravenJObject = RavenJObject.Parse(readToEnd);
                    }
                    catch (Exception e)
                    {
                        throw new ErrorResponseException(Response, readToEnd, e);
                    }
                    if (ravenJObject.ContainsKey("IndexDefinitionProperty"))
                    {
                        throw new IndexCompilationException(ravenJObject.Value <string>("Message"))
                              {
                                  IndexDefinitionProperty = ravenJObject.Value <string>("IndexDefinitionProperty"),
                                  ProblematicText         = ravenJObject.Value <string>("ProblematicText")
                              };
                    }
                    if (Response.StatusCode == HttpStatusCode.BadRequest && ravenJObject.ContainsKey("Message"))
                    {
                        throw new BadRequestException(ravenJObject.Value <string>("Message"), ErrorResponseException.FromResponseMessage(Response));
                    }
                    if (ravenJObject.ContainsKey("Error"))
                    {
                        var sb = new StringBuilder();
                        foreach (var prop in ravenJObject)
                        {
                            if (prop.Key == "Error")
                            {
                                continue;
                            }

                            sb.Append(prop.Key).Append(": ").AppendLine(prop.Value.ToString(Formatting.Indented));
                        }

                        if (sb.Length > 0)
                        {
                            sb.AppendLine();
                        }
                        sb.Append(ravenJObject.Value <string>("Error"));

                        throw new ErrorResponseException(Response, sb.ToString());
                    }
                    throw new ErrorResponseException(Response, readToEnd);
                }
            }
            return(null);
        }