예제 #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));
                }
            }
        }
예제 #2
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));
        }
예제 #4
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);
            }
        }
예제 #5
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);
            }
        }
예제 #6
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);
        }
        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);
        }