Ejemplo n.º 1
0
        private async Task <AccountProperties> GetDatabaseAccountAsync(Uri serviceEndpoint)
        {
            INameValueCollection headers = new DictionaryNameValueCollection(StringComparer.Ordinal);
            string authorizationToken    = string.Empty;

            if (this.hasAuthKeyResourceToken)
            {
                authorizationToken = HttpUtility.UrlEncode(this.authKeyResourceToken);
            }
            else
            {
                // Retrieve the document service properties.
                string xDate = DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture);
                headers.Set(HttpConstants.HttpHeaders.XDate, xDate);

                authorizationToken = AuthorizationHelper.GenerateKeyAuthorizationSignature(
                    HttpConstants.HttpMethods.Get,
                    serviceEndpoint,
                    headers,
                    this.authKeyHashFunction);
            }

            headers.Set(HttpConstants.HttpHeaders.Authorization, authorizationToken);
            using (HttpResponseMessage responseMessage = await this.httpClient.GetAsync(serviceEndpoint, headers))
            {
                using (DocumentServiceResponse documentServiceResponse = await ClientExtensions.ParseResponseAsync(responseMessage))
                {
                    return(CosmosResource.FromStream <AccountProperties>(documentServiceResponse));
                }
            }
        }
Ejemplo n.º 2
0
        public static async Task <DocumentServiceResponse> ParseResponseAsync(HttpResponseMessage responseMessage, JsonSerializerSettings serializerSettings = null, bool throwOnKnownClientErrorCodes = true)
        {
            using (responseMessage)
            {
                if ((int)responseMessage.StatusCode < 400)
                {
                    MemoryStream bufferedStream = new MemoryStream();

                    await responseMessage.Content.CopyToAsync(bufferedStream);

                    bufferedStream.Position = 0;

                    INameValueCollection headers = ClientExtensions.ExtractResponseHeaders(responseMessage);
                    return(new DocumentServiceResponse(bufferedStream, headers, responseMessage.StatusCode, serializerSettings));
                }
                else if (!throwOnKnownClientErrorCodes && (responseMessage.StatusCode == HttpStatusCode.NotFound || responseMessage.StatusCode == HttpStatusCode.PreconditionFailed || responseMessage.StatusCode == HttpStatusCode.Conflict))
                {
                    INameValueCollection headers = ClientExtensions.ExtractResponseHeaders(responseMessage);
                    return(new DocumentServiceResponse(null, headers, responseMessage.StatusCode, serializerSettings));
                }
                else
                {
                    throw await ClientExtensions.CreateDocumentClientException(responseMessage);
                }
            }
        }
Ejemplo n.º 3
0
        public static async Task <DocumentServiceResponse> ParseResponseAsync(HttpResponseMessage responseMessage, JsonSerializerSettings serializerSettings = null, DocumentServiceRequest request = null)
        {
            using (responseMessage)
            {
                if ((int)responseMessage.StatusCode < 400)
                {
                    MemoryStream bufferedStream = new MemoryStream();

                    await responseMessage.Content.CopyToAsync(bufferedStream);

                    bufferedStream.Position = 0;

                    INameValueCollection headers = ClientExtensions.ExtractResponseHeaders(responseMessage);
                    return(new DocumentServiceResponse(bufferedStream, headers, responseMessage.StatusCode, serializerSettings));
                }
                else if (request != null &&
                         request.IsValidStatusCodeForExceptionlessRetry((int)responseMessage.StatusCode))
                {
                    INameValueCollection headers = ClientExtensions.ExtractResponseHeaders(responseMessage);
                    return(new DocumentServiceResponse(null, headers, responseMessage.StatusCode, serializerSettings));
                }
                else
                {
                    throw await ClientExtensions.CreateDocumentClientException(responseMessage);
                }
            }
        }
Ejemplo n.º 4
0
 public static async Task <DocumentServiceResponse> ParseMediaResponseAsync(HttpResponseMessage responseMessage, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     if ((int)responseMessage.StatusCode < 400)
     {
         INameValueCollection headers     = ClientExtensions.ExtractResponseHeaders(responseMessage);
         MediaStream          mediaStream = new MediaStream(responseMessage, await responseMessage.Content.ReadAsStreamAsync());
         return(new DocumentServiceResponse(mediaStream, headers, responseMessage.StatusCode));
     }
     else
     {
         throw await ClientExtensions.CreateDocumentClientException(responseMessage);
     }
 }
Ejemplo n.º 5
0
        private async Task <CosmosAccountSettings> GetDatabaseAccountAsync(Uri serviceEndpoint)
        {
            HttpClient httpClient = this.messageHandler == null ? new HttpClient() : new HttpClient(this.messageHandler);

            httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Version,
                                                 HttpConstants.Versions.CurrentVersion);

            // Send client version.
            httpClient.AddUserAgentHeader(this.connectionPolicy.UserAgentContainer);
            httpClient.AddApiTypeHeader(this.apiType);

            string authorizationToken = string.Empty;

            if (this.hasAuthKeyResourceToken)
            {
                authorizationToken = HttpUtility.UrlEncode(this.authKeyResourceToken);
            }
            else
            {
                // Retrieve the document service properties.
                string xDate = DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture);
                httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.XDate, xDate);

                INameValueCollection headersCollection = new StringKeyValueCollection();
                headersCollection.Add(HttpConstants.HttpHeaders.XDate, xDate);

                authorizationToken = AuthorizationHelper.GenerateKeyAuthorizationSignature(
                    HttpConstants.HttpMethods.Get,
                    serviceEndpoint,
                    headersCollection,
                    this.authKeyHashFunction);
            }

            httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Authorization, authorizationToken);

            using (HttpResponseMessage responseMessage = await httpClient.GetHttpAsync(
                       serviceEndpoint))
            {
                using (DocumentServiceResponse documentServiceResponse = await ClientExtensions.ParseResponseAsync(responseMessage))
                {
                    CosmosAccountSettings databaseAccount = documentServiceResponse.GetInternalResource <CosmosAccountSettings>(CosmosAccountSettings.CreateNewInstance);

                    return(databaseAccount);
                }
            }
        }
        async private Task <DocumentServiceResponse> InvokeAsync(DocumentServiceRequest request, ResourceType resourceType, CancellationToken cancellationToken)
        {
            Func <Task <DocumentServiceResponse> > funcDelegate = async() =>
            {
                using (HttpRequestMessage requestMessage = await this.PrepareRequestMessageAsync(request))
                {
                    DateTime sendTimeUtc = DateTime.UtcNow;
                    Guid     localGuid   = Guid.NewGuid(); // For correlating HttpRequest and HttpResponse Traces

                    this.eventSource.Request(
                        Guid.Empty,
                        localGuid,
                        requestMessage.RequestUri.ToString(),
                        resourceType.ToResourceTypeString(),
                        requestMessage.Headers);

                    using (HttpResponseMessage responseMessage = await this.httpClient.SendAsync(requestMessage, cancellationToken))
                    {
                        DateTime receivedTimeUtc        = DateTime.UtcNow;
                        double   durationInMilliSeconds = (receivedTimeUtc - sendTimeUtc).TotalMilliseconds;

                        IEnumerable <string> headerValues;
                        Guid activityId = Guid.Empty;
                        if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.ActivityId, out headerValues) &&
                            headerValues.Count() != 0)
                        {
                            activityId = new Guid(headerValues.First());
                        }

                        this.eventSource.Response(
                            activityId,
                            localGuid,
                            (short)responseMessage.StatusCode,
                            durationInMilliSeconds,
                            responseMessage.Headers);

                        return(await ClientExtensions.ParseResponseAsync(responseMessage, request.SerializerSettings ?? this.SerializerSettings, request));
                    }
                }
            };

            return(await BackoffRetryUtility <DocumentServiceResponse> .ExecuteAsync(funcDelegate, new WebExceptionRetryPolicy(), cancellationToken));
        }
Ejemplo n.º 7
0
        public async Task TestBadRequestParseHandling()
        {
            HttpRequestMessage  httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://localhost:8081");
            HttpResponseMessage message            = new HttpResponseMessage(HttpStatusCode.BadRequest);

            message.ReasonPhrase   = "Invalid Parameter";
            message.RequestMessage = httpRequestMessage;
            message.Headers.Add("x-ms-activity-id", Guid.NewGuid().ToString());
            message.Content = new StringContent("<html>Your response text</html>", encoding: Encoding.Default, mediaType: "text/html");

            try
            {
                DocumentServiceResponse dsr = await ClientExtensions.ParseResponseAsync(message);
            }
            catch (DocumentClientException dce)
            {
                Assert.IsNotNull(dce.Message);
                Assert.AreEqual(HttpStatusCode.BadRequest, dce.StatusCode);
                Assert.AreEqual("Invalid Parameter", dce.StatusDescription);
            }
        }
Ejemplo n.º 8
0
        public async Task TestJsonParseHandling()
        {
            HttpRequestMessage  httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://*****:*****@"{ ""id"": ""test"", ""message"": ""Conflict"", ""Code"": ""409""}",
                encoding: Encoding.Default,
                mediaType: "application/json");

            try
            {
                DocumentServiceResponse dsr = await ClientExtensions.ParseResponseAsync(message);
            }
            catch (DocumentClientException dce)
            {
                Assert.IsNotNull(dce.Message);
                Assert.AreEqual(HttpStatusCode.Conflict, dce.StatusCode);
                Assert.AreEqual("Id already exists", dce.StatusDescription);
            }
        }
Ejemplo n.º 9
0
        public virtual async Task <AccountProperties> GetDatabaseAccountAsync(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
        {
            AccountProperties databaseAccount = null;

            // Get the ServiceDocumentResource from the gateway.
            using (HttpResponseMessage responseMessage =
                       await this.gatewayStoreClient.SendHttpAsync(requestMessage, cancellationToken))
            {
                using (DocumentServiceResponse documentServiceResponse = await ClientExtensions.ParseResponseAsync(responseMessage))
                {
                    databaseAccount = CosmosResource.FromStream <AccountProperties>(documentServiceResponse);
                }

                long longValue;
                IEnumerable <string> headerValues;
                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.MaxMediaStorageUsageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.MaxMediaStorageUsageInMB = longValue;
                    }
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.CurrentMediaStorageUsageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.MediaStorageUsageInMB = longValue;
                    }
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.DatabaseAccountConsumedDocumentStorageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.ConsumedDocumentStorageInMB = longValue;
                    }
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.DatabaseAccountProvisionedDocumentStorageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.ProvisionedDocumentStorageInMB = longValue;
                    }
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.DatabaseAccountReservedDocumentStorageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.ReservedDocumentStorageInMB = longValue;
                    }
                }
            }

            return(databaseAccount);
        }
Ejemplo n.º 10
0
        public virtual async Task <CosmosAccountSettings> GetDatabaseAccountAsync(HttpRequestMessage requestMessage)
        {
            CosmosAccountSettings databaseAccount = null;

            // Get the ServiceDocumentResource from the gateway.
            using (HttpResponseMessage responseMessage =
                       await this.httpClient.SendHttpAsync(requestMessage))
            {
                using (DocumentServiceResponse documentServiceResponse = await ClientExtensions.ParseResponseAsync(responseMessage))
                {
                    databaseAccount = documentServiceResponse.GetInternalResource <CosmosAccountSettings>(CosmosAccountSettings.CreateNewInstance);
                }

                long longValue;
                IEnumerable <string> headerValues;
                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.MaxMediaStorageUsageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.MaxMediaStorageUsageInMB = longValue;
                    }
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.CurrentMediaStorageUsageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.MediaStorageUsageInMB = longValue;
                    }
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.DatabaseAccountConsumedDocumentStorageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.ConsumedDocumentStorageInMB = longValue;
                    }
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.DatabaseAccountProvisionedDocumentStorageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.ProvisionedDocumentStorageInMB = longValue;
                    }
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.DatabaseAccountReservedDocumentStorageInMB, out headerValues) &&
                    (headerValues.Count() != 0))
                {
                    if (long.TryParse(headerValues.First(), out longValue))
                    {
                        databaseAccount.ReservedDocumentStorageInMB = longValue;
                    }
                }
            }

            return(databaseAccount);
        }