public async Task TestGatewayModelSession()
        {
            ContainerProperties containerProperties = await this.Container.GetCachedContainerPropertiesAsync(
                false,
                Trace.GetRootTrace("Test"),
                CancellationToken.None);

            ISessionContainer sessionContainer = this.cosmosClient.DocumentClient.sessionContainer;
            string            docLink          = "dbs/" + this.database.Id + "/colls/" + containerProperties.Id + "/docs/3";

            Documents.Collections.INameValueCollection headers = new Documents.Collections.RequestNameValueCollection();
            headers.Set(HttpConstants.HttpHeaders.PartitionKey, "[\"Status3\"]");

            DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, ResourceType.Document, docLink, AuthorizationTokenType.PrimaryMasterKey, headers);
            string globalSessionToken      = sessionContainer.ResolveGlobalSessionToken(request);

            Assert.IsTrue(globalSessionToken.Split(',').Length > 1);

            await GatewayStoreModel.ApplySessionTokenAsync(request,
                                                           Cosmos.ConsistencyLevel.Session,
                                                           sessionContainer,
                                                           await this.cosmosClient.DocumentClient.GetPartitionKeyRangeCacheAsync(NoOpTrace.Singleton),
                                                           await this.cosmosClient.DocumentClient.GetCollectionCacheAsync(NoOpTrace.Singleton),
                                                           this.cosmosClient.DocumentClient.GlobalEndpointManager);

            string sessionToken = request.Headers[HttpConstants.HttpHeaders.SessionToken];

            Assert.IsTrue(!string.IsNullOrEmpty(sessionToken) && sessionToken.Split(',').Length == 1);
        }
        public async Task GatewaySameSessionTokenTest()
        {
            string createSessionToken = null;
            HttpHandlerMetaDataValidator httpClientHandler = new HttpHandlerMetaDataValidator
            {
                RequestCallBack = (request, response) =>
                {
                    if (response.StatusCode != HttpStatusCode.Created)
                    {
                        return;
                    }

                    response.Headers.TryGetValues("x-ms-session-token", out IEnumerable <string> sessionTokens);
                    foreach (string singleToken in sessionTokens)
                    {
                        createSessionToken = singleToken;
                        break;
                    }
                }
            };

            using (CosmosClient client = TestCommon.CreateCosmosClient(builder => builder
                                                                       .WithConnectionModeGateway()
                                                                       .WithConsistencyLevel(Cosmos.ConsistencyLevel.Session)
                                                                       .WithHttpClientFactory(() => new HttpClient(httpClientHandler))))
            {
                Container container = client.GetContainer(this.database.Id, this.Container.Id);

                ToDoActivity item = ToDoActivity.CreateRandomToDoActivity("Status1001", "1001");
                ItemResponse <ToDoActivity> itemResponse = await container.CreateItemAsync(item);

                // Read back the created Item and check if the session token is identical.
                string docLink = "dbs/" + this.database.Id + "/colls/" + this.Container.Id + "/docs/1001";
                Documents.Collections.INameValueCollection headers = new Documents.Collections.RequestNameValueCollection();
                headers.Set(HttpConstants.HttpHeaders.PartitionKey, "[\"Status1001\"]");

                DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, ResourceType.Document, docLink, AuthorizationTokenType.PrimaryMasterKey, headers);
                await GatewayStoreModel.ApplySessionTokenAsync(request,
                                                               Cosmos.ConsistencyLevel.Session,
                                                               client.DocumentClient.sessionContainer,
                                                               await client.DocumentClient.GetPartitionKeyRangeCacheAsync(NoOpTrace.Singleton),
                                                               await client.DocumentClient.GetCollectionCacheAsync(NoOpTrace.Singleton),
                                                               client.DocumentClient.GlobalEndpointManager);

                string readSessionToken = request.Headers[HttpConstants.HttpHeaders.SessionToken];
                Assert.AreEqual(readSessionToken, createSessionToken);
            }
        }
Esempio n. 3
0
        public static async Task <ICollection <T> > ListAllAsync <T>(this HttpClient client,
                                                                     Uri collectionUri,
                                                                     INameValueCollection headers = null) where T : Resource, new()
        {
            Collection <T> responseCollection   = new Collection <T>();
            string         responseContinuation = null;

            if (headers == null)
            {
                headers = new Documents.Collections.RequestNameValueCollection();
            }

            do
            {
                if (responseContinuation != null)
                {
                    headers[HttpConstants.HttpHeaders.Continuation] = responseContinuation;
                }

                HttpResponseMessage responseMessage;
                foreach (string header in headers.AllKeys())
                {
                    client.DefaultRequestHeaders.Add(header, headers[header]);
                }

                responseMessage = await client.GetAsync(collectionUri, HttpCompletionOption.ResponseHeadersRead);

                FeedResource <T> feedResource = await responseMessage.ToResourceAsync <FeedResource <T> >();

                foreach (T resource in feedResource)
                {
                    responseCollection.Add(resource);
                }

                if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.Continuation,
                                                         out IEnumerable <string> continuationToken))
                {
                    responseContinuation = continuationToken.SingleOrDefault();
                }
                else
                {
                    responseContinuation = null;
                }
            } while (!string.IsNullOrEmpty(responseContinuation));

            return(responseCollection);
        }
        internal static void ValidateQuery <T>(DocumentClient client, string collectionLink, string queryProperty, string queryPropertyValue, int expectedCount, INameValueCollection headers = null)
            where T : Resource, new()
        {
            INameValueCollection inputHeaders = headers;

            headers = new Documents.Collections.RequestNameValueCollection();
            if (inputHeaders != null)
            {
                headers.Add(inputHeaders); // dont mess with the input headers
            }

            int       maxTries         = 5;
            const int minIndexInterval = 5000; // 5 seconds

            while (maxTries-- > 0)
            {
                DocumentFeedResponse <dynamic> resourceFeed = null;
                IDocumentQuery <dynamic>       queryService = null;
                string queryString = @"select * from root r where r." + queryProperty + @"=""" + queryPropertyValue + @"""";
                if (typeof(T) == typeof(Database))
                {
                    queryService = client.CreateDatabaseQuery(queryString).AsDocumentQuery();
                }
                else if (typeof(T) == typeof(DocumentCollection))
                {
                    queryService = client.CreateDocumentCollectionQuery(collectionLink, queryString).AsDocumentQuery();
                }
                else if (typeof(T) == typeof(Document))
                {
                    queryService = client.CreateDocumentQuery(collectionLink, queryString).AsDocumentQuery();
                }
                else
                {
                    Assert.Fail("Unexpected type");
                }

                while (queryService.HasMoreResults)
                {
                    resourceFeed = queryService.ExecuteNextAsync().Result;

                    if (resourceFeed.Count > 0)
                    {
                        Assert.IsNotNull(resourceFeed, "Query result is null");
                        Assert.AreNotEqual(0, resourceFeed.Count, "Query result is invalid");

                        foreach (T resource in resourceFeed)
                        {
                            if (queryProperty.Equals("name", StringComparison.CurrentCultureIgnoreCase))
                            {
                                Assert.AreEqual(resource.Id, queryPropertyValue, "Result contain invalid result");
                            }
                        }
                        return;
                    }
                }

                Task.Delay(minIndexInterval);
            }

            Assert.Fail("Query did not return result after max tries");
        }