Ejemplo n.º 1
0
        public async Task ImplicitConversion()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            CosmosContainerResponse containerResponse       = await this.cosmosDatabase.Containers[containerName].ReadAsync();
            CosmosContainer         cosmosContainer         = containerResponse;
            CosmosContainerSettings cosmosContainerSettings = containerResponse;

            Assert.AreEqual(HttpStatusCode.NotFound, containerResponse.StatusCode);
            Assert.IsNotNull(cosmosContainer);
            Assert.IsNull(cosmosContainerSettings);

            containerResponse = await this.cosmosDatabase.Containers.CreateContainerIfNotExistsAsync(containerName, partitionKeyPath);

            cosmosContainer         = containerResponse;
            cosmosContainerSettings = containerResponse;
            Assert.IsNotNull(cosmosContainer);
            Assert.IsNotNull(cosmosContainerSettings);

            containerResponse = await cosmosContainer.DeleteAsync();

            cosmosContainer         = containerResponse;
            cosmosContainerSettings = containerResponse;
            Assert.IsNotNull(cosmosContainer);
            Assert.IsNull(cosmosContainerSettings);
        }
        public async Task TimeToLiveTest()
        {
            string            containerName       = Guid.NewGuid().ToString();
            string            partitionKeyPath    = "/users";
            int               timeToLiveInSeconds = 10;
            ContainerResponse containerResponse   = await this.database.DefineContainer(containerName, partitionKeyPath)
                                                    .WithDefaultTimeToLive(timeToLiveInSeconds)
                                                    .CreateAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            CosmosContainer         cosmosContainer  = containerResponse;
            CosmosContainerSettings responseSettings = containerResponse;

            Assert.AreEqual(timeToLiveInSeconds, responseSettings.DefaultTimeToLive);

            ContainerResponse readResponse = await cosmosContainer.ReadAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(timeToLiveInSeconds, readResponse.Resource.DefaultTimeToLive);

            JObject itemTest = JObject.FromObject(new { id = Guid.NewGuid().ToString(), users = "testUser42" });
            ItemResponse <JObject> createResponse = await cosmosContainer.CreateItemAsync <JObject>(item : itemTest);

            JObject responseItem = createResponse;

            Assert.IsNull(responseItem["ttl"]);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
        public async Task SharedThroughputTests()
        {
            string databaseId = Guid.NewGuid().ToString();
            int    throughput = 10000;
            CosmosDatabaseResponse createResponse = await this.CreateDatabaseHelper(databaseId, databaseExists : false, throughput : throughput);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            CosmosDatabase cosmosDatabase = createResponse;
            int?           readThroughput = await cosmosDatabase.ReadProvisionedThroughputAsync();

            Assert.AreEqual(throughput, readThroughput);

            string containerId   = Guid.NewGuid().ToString();
            string partitionPath = "/users";
            CosmosContainerResponse containerResponse = await cosmosDatabase.Containers.CreateContainerAsync(containerId, partitionPath);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);

            CosmosContainer container = containerResponse;

            readThroughput = await container.ReadProvisionedThroughputAsync();

            Assert.IsNull(readThroughput);

            await container.DeleteAsync();

            await cosmosDatabase.DeleteAsync();
        }
Ejemplo n.º 4
0
        public async Task ReplaceThroughputTest()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            CosmosContainerResponse containerResponse = await this.cosmosDatabase.Containers.CreateContainerIfNotExistsAsync(containerName, partitionKeyPath);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            CosmosContainer cosmosContainer = this.cosmosDatabase.Containers[containerName];

            int?readThroughput = await cosmosContainer.ReadProvisionedThroughputAsync();

            Assert.IsNotNull(readThroughput);

            await cosmosContainer.ReplaceProvisionedThroughputAsync(readThroughput.Value + 1000);

            int?replaceThroughput = await cosmosContainer.ReadProvisionedThroughputAsync();

            Assert.IsNotNull(replaceThroughput);
            Assert.AreEqual(readThroughput.Value + 1000, replaceThroughput);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
        public async Task ValidateQueryNotFoundResponse()
        {
            CosmosDatabase db = await CosmosNotFoundTests.client.CreateDatabaseAsync("NotFoundTest" + Guid.NewGuid().ToString());

            CosmosContainer container = await db.CreateContainerAsync("NotFoundTest" + Guid.NewGuid().ToString(), "/pk", 500);

            dynamic randomItem = new { id = "test", pk = "testpk" };
            await container.CreateItemAsync(randomItem);

            await container.DeleteAsync();

            var crossPartitionQueryIterator = container.CreateItemQueryStream("select * from t where true", maxConcurrency: 2);
            var queryResponse = await crossPartitionQueryIterator.FetchNextSetAsync();

            Assert.IsNotNull(queryResponse);
            Assert.AreEqual(HttpStatusCode.Gone, queryResponse.StatusCode);

            var queryIterator = container.CreateItemQueryStream("select * from t where true", maxConcurrency: 1, partitionKey: new Cosmos.PartitionKey("testpk"));

            this.VerifyQueryNotFoundResponse(await queryIterator.FetchNextSetAsync());

            var crossPartitionQueryIterator2 = container.CreateItemQueryStream("select * from t where true", maxConcurrency: 2);

            this.VerifyQueryNotFoundResponse(await crossPartitionQueryIterator2.FetchNextSetAsync());

            await db.DeleteAsync();
        }
Ejemplo n.º 6
0
        public async Task DeleteNonExistingContainer()
        {
            string          containerName   = Guid.NewGuid().ToString();
            CosmosContainer cosmosContainer = this.cosmosDatabase.Containers[containerName];

            CosmosContainerResponse containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NotFound, containerResponse.StatusCode);
        }
Ejemplo n.º 7
0
        public async Task CleanAll()
        {
            CosmosDatabase database = await client.Databases.CreateDatabaseIfNotExistsAsync(DatabaseName);

            CosmosContainer container = await database.Containers.CreateContainerIfNotExistsAsync(ContainerName, PartitionKeyPath);

            await container.DeleteAsync();

            await database.DeleteAsync();
        }
Ejemplo n.º 8
0
        public async Task ThroughputNonExistingTest()
        {
            string          containerName   = Guid.NewGuid().ToString();
            CosmosContainer cosmosContainer = this.cosmosDatabase.Containers[containerName];

            await cosmosContainer.ReadProvisionedThroughputAsync();

            CosmosContainerResponse containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NotFound, containerResponse.StatusCode);
        }
        public async Task TimeToLivePropertyPath()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/user";
            int    timeToLivetimeToLiveInSeconds = 10;

            ContainerResponse containerResponse = null;

            try
            {
                containerResponse = await this.database.DefineContainer(containerName, partitionKeyPath)
                                    .WithTimeToLivePropertyPath("/creationDate")
                                    .CreateAsync();

                Assert.Fail("CreateColleciton with TtlPropertyPath and with no DefaultTimeToLive should have failed.");
            }
            catch (CosmosException exeption)
            {
                // expected because DefaultTimeToLive was not specified
                Assert.AreEqual(HttpStatusCode.BadRequest, exeption.StatusCode);
            }

            // Verify the container content.
            containerResponse = await this.database.DefineContainer(containerName, partitionKeyPath)
                                .WithTimeToLivePropertyPath("/creationDate")
                                .WithDefaultTimeToLive(timeToLivetimeToLiveInSeconds)
                                .CreateAsync();

            CosmosContainer cosmosContainer = containerResponse;

            Assert.AreEqual(timeToLivetimeToLiveInSeconds, containerResponse.Resource.DefaultTimeToLive);
            Assert.AreEqual("/creationDate", containerResponse.Resource.TimeToLivePropertyPath);

            //Creating an item and reading before expiration
            var payload = new { id = "testId", user = "******", creationDate = ToEpoch(DateTime.UtcNow) };
            ItemResponse <dynamic> createItemResponse = await cosmosContainer.CreateItemAsync <dynamic>(payload);

            Assert.IsNotNull(createItemResponse.Resource);
            Assert.AreEqual(createItemResponse.StatusCode, HttpStatusCode.Created);
            ItemResponse <dynamic> readItemResponse = await cosmosContainer.ReadItemAsync <dynamic>(new Cosmos.PartitionKey(payload.user), payload.id);

            Assert.IsNotNull(readItemResponse.Resource);
            Assert.AreEqual(readItemResponse.StatusCode, HttpStatusCode.OK);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Ejemplo n.º 10
0
        private static async Task CreateContainerWithCustomIndexingPolicy()
        {
            // Create a container with custom index policy (lazy indexing)
            // We cover index policies in detail in IndexManagement sample project
            CosmosContainerSettings containerSettings = new CosmosContainerSettings(
                id: "SampleContainerWithCustomIndexPolicy",
                partitionKeyPath: partitionKey);

            containerSettings.IndexingPolicy.IndexingMode = IndexingMode.Lazy;

            CosmosContainer containerWithLazyIndexing = await database.CreateContainerIfNotExistsAsync(
                containerSettings,
                requestUnitsPerSecond : 400);

            Console.WriteLine($"1.2. Created Container {containerWithLazyIndexing.Id}, with custom index policy \n");

            await containerWithLazyIndexing.DeleteAsync();
        }
Ejemplo n.º 11
0
        public async Task TestPreProcessingHandler()
        {
            CosmosRequestHandler preProcessHandler = new PreProcessingTestHandler();
            CosmosClient         client            = MockCosmosUtil.CreateMockCosmosClient((builder) => builder.AddCustomHandlers(preProcessHandler));

            Assert.IsTrue(typeof(RequestInvokerHandler).Equals(client.RequestHandler.GetType()));
            Assert.IsTrue(typeof(PreProcessingTestHandler).Equals(client.RequestHandler.InnerHandler.GetType()));

            CosmosContainer container = client.Databases["testdb"]
                                        .Containers["testcontainer"];

            HttpStatusCode[] testHttpStatusCodes = new HttpStatusCode[]
            {
                HttpStatusCode.OK,
                HttpStatusCode.NotFound
            };

            // User operations
            foreach (HttpStatusCode code in testHttpStatusCodes)
            {
                ItemRequestOptions options = new ItemRequestOptions();
                options.Properties = new Dictionary <string, object>();
                options.Properties.Add(PreProcessingTestHandler.StatusCodeName, code);

                ItemResponse <object> response = await container.ReadItemAsync <object>("pk1", "id1", options);

                Console.WriteLine($"Got status code {response.StatusCode}");
                Assert.AreEqual(code, response.StatusCode);
            }

            // Meta-data operations
            foreach (HttpStatusCode code in testHttpStatusCodes)
            {
                ContainerRequestOptions options = new ContainerRequestOptions();
                options.Properties = new Dictionary <string, object>();
                options.Properties.Add(PreProcessingTestHandler.StatusCodeName, code);

                ContainerResponse response = await container.DeleteAsync(options);

                Console.WriteLine($"Got status code {response.StatusCode}");
                Assert.AreEqual(code, response.StatusCode);
            }
        }
Ejemplo n.º 12
0
        public async Task TimeToLiveTest()
        {
            string   containerName          = Guid.NewGuid().ToString();
            string   partitionKeyPath       = "/users";
            TimeSpan timeToLive             = TimeSpan.FromSeconds(1);
            CosmosContainerSettings setting = new CosmosContainerSettings()
            {
                Id           = containerName,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string> {
                        partitionKeyPath
                    }, Kind = PartitionKind.Hash
                },
                DefaultTimeToLive = timeToLive
            };

            CosmosContainerResponse containerResponse = await this.cosmosDatabase.Containers.CreateContainerIfNotExistsAsync(setting);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            CosmosContainer         cosmosContainer  = containerResponse;
            CosmosContainerSettings responseSettings = containerResponse;

            Assert.AreEqual(timeToLive.TotalSeconds, responseSettings.DefaultTimeToLive.Value.TotalSeconds);

            CosmosContainerResponse readResponse = await cosmosContainer.ReadAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(timeToLive.TotalSeconds, readResponse.Resource.DefaultTimeToLive.Value.TotalSeconds);

            JObject itemTest = JObject.FromObject(new { id = Guid.NewGuid().ToString(), users = "testUser42" });
            CosmosItemResponse <JObject> createResponse = await cosmosContainer.Items.CreateItemAsync <JObject>(partitionKey : itemTest["users"].ToString(), item : itemTest);

            JObject responseItem = createResponse;

            Assert.IsNull(responseItem["ttl"]);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
        public async Task ThroughputTest()
        {
            int    expectedThroughput = 2400;
            string containerName      = Guid.NewGuid().ToString();
            string partitionKeyPath   = "/users";

            ContainerResponse containerResponse
                = await this.database.DefineContainer(containerName, partitionKeyPath)
                  .CreateAsync(expectedThroughput);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            CosmosContainer cosmosContainer = this.database.GetContainer(containerName);

            int?readThroughput = await cosmosContainer.ReadProvisionedThroughputAsync();

            Assert.IsNotNull(readThroughput);
            Assert.AreEqual(expectedThroughput, readThroughput);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
        public async Task TimeToLivePropertyPath()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/user";
            int    timeToLivetimeToLiveInSeconds = 10;
            CosmosContainerSettings setting      = new CosmosContainerSettings()
            {
                Id           = containerName,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string> {
                        partitionKeyPath
                    }, Kind = PartitionKind.Hash
                },
                TimeToLivePropertyPath = "/creationDate",
            };

            ContainerResponse containerResponse = null;

            try
            {
                containerResponse = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(setting);

                Assert.Fail("CreateColleciton with TtlPropertyPath and with no DefaultTimeToLive should have failed.");
            }
            catch (CosmosException exeption)
            {
                // expected because DefaultTimeToLive was not specified
                Assert.AreEqual(HttpStatusCode.BadRequest, exeption.StatusCode);
            }

            // Verify the container content.
            setting.DefaultTimeToLive = timeToLivetimeToLiveInSeconds;
            containerResponse         = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(setting);

            CosmosContainer cosmosContainer = containerResponse;

            Assert.AreEqual(timeToLivetimeToLiveInSeconds, containerResponse.Resource.DefaultTimeToLive);
            Assert.AreEqual("/creationDate", containerResponse.Resource.TimeToLivePropertyPath);

            //verify removing the ttl property path
            setting.TimeToLivePropertyPath = null;
            containerResponse = await cosmosContainer.ReplaceAsync(setting);

            cosmosContainer = containerResponse;
            Assert.AreEqual(timeToLivetimeToLiveInSeconds, containerResponse.Resource.DefaultTimeToLive);
            Assert.IsNull(containerResponse.Resource.TimeToLivePropertyPath);

            //adding back the ttl property path
            setting.TimeToLivePropertyPath = "/creationDate";
            containerResponse = await cosmosContainer.ReplaceAsync(setting);

            cosmosContainer = containerResponse;
            Assert.AreEqual(containerResponse.Resource.TimeToLivePropertyPath, "/creationDate");

            //Creating an item and reading before expiration
            var payload = new { id = "testId", user = "******", creationDate = ToEpoch(DateTime.UtcNow) };
            ItemResponse <dynamic> createItemResponse = await cosmosContainer.CreateItemAsync <dynamic>(payload);

            Assert.IsNotNull(createItemResponse.Resource);
            Assert.AreEqual(createItemResponse.StatusCode, HttpStatusCode.Created);
            ItemResponse <dynamic> readItemResponse = await cosmosContainer.ReadItemAsync <dynamic>(new Cosmos.PartitionKey(payload.user), payload.id);

            Assert.IsNotNull(readItemResponse.Resource);
            Assert.AreEqual(readItemResponse.StatusCode, HttpStatusCode.OK);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Ejemplo n.º 15
0
        [Ignore] //Temporary ignore till we fix emulator issue
        public async Task ReadNonPartitionItemAsync()
        {
            try
            {
                await this.CreateNonPartitionContainerItem();

                await this.CreateUndefinedPartitionItem();

                fixedContainer = this.database.Containers[nonPartitionContainerId];

                CosmosContainerResponse containerResponse = await fixedContainer.ReadAsync();

                Assert.IsTrue(containerResponse.Resource.PartitionKey.Paths.Count > 0);
                Assert.AreEqual(PartitionKey.SystemKeyPath, containerResponse.Resource.PartitionKey.Paths[0]);

                //Reading item from fixed container with CosmosContainerSettings.NonePartitionKeyValue.
                CosmosItemResponse <ToDoActivity> response = await fixedContainer.Items.ReadItemAsync <ToDoActivity>(
                    partitionKey : CosmosContainerSettings.NonePartitionKeyValue,
                    id : nonPartitionItemId);

                Assert.IsNotNull(response.Resource);
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.AreEqual(nonPartitionItemId, response.Resource.id);

                //Adding item to fixed container with CosmosContainerSettings.NonePartitionKeyValue.
                ToDoActivity itemWithoutPK = CreateRandomToDoActivity();
                CosmosItemResponse <ToDoActivity> createResponseWithoutPk = await fixedContainer.Items.CreateItemAsync <ToDoActivity>(
                    partitionKey : CosmosContainerSettings.NonePartitionKeyValue,
                    item : itemWithoutPK);

                Assert.IsNotNull(createResponseWithoutPk.Resource);
                Assert.AreEqual(HttpStatusCode.Created, createResponseWithoutPk.StatusCode);
                Assert.AreEqual(itemWithoutPK.id, createResponseWithoutPk.Resource.id);

                //Updating item on fixed container with CosmosContainerSettings.NonePartitionKeyValue.
                itemWithoutPK.status = "updatedStatus";
                CosmosItemResponse <ToDoActivity> updateResponseWithoutPk = await fixedContainer.Items.ReplaceItemAsync <ToDoActivity>(
                    partitionKey : CosmosContainerSettings.NonePartitionKeyValue,
                    id : itemWithoutPK.id,
                    item : itemWithoutPK);

                Assert.IsNotNull(updateResponseWithoutPk.Resource);
                Assert.AreEqual(HttpStatusCode.OK, updateResponseWithoutPk.StatusCode);
                Assert.AreEqual(itemWithoutPK.id, updateResponseWithoutPk.Resource.id);

                //Adding item to fixed container with non-none PK.
                ToDoActivityAfterMigration itemWithPK = CreateRandomToDoActivityAfterMigration("TestPk");
                CosmosItemResponse <ToDoActivityAfterMigration> createResponseWithPk = await fixedContainer.Items.CreateItemAsync <ToDoActivityAfterMigration>(
                    partitionKey : itemWithPK.status,
                    item : itemWithPK);

                Assert.IsNotNull(createResponseWithPk.Resource);
                Assert.AreEqual(HttpStatusCode.Created, createResponseWithPk.StatusCode);
                Assert.AreEqual(itemWithPK.id, createResponseWithPk.Resource.id);

                //Quering items on fixed container with cross partition enabled.
                CosmosSqlQueryDefinition          sql         = new CosmosSqlQueryDefinition("select * from r");
                CosmosResultSetIterator <dynamic> setIterator = fixedContainer.Items
                                                                .CreateItemQuery <dynamic>(sql, maxConcurrency: 1, maxItemCount: 10, requestOptions: new CosmosQueryRequestOptions {
                    EnableCrossPartitionQuery = true
                });
                while (setIterator.HasMoreResults)
                {
                    CosmosQueryResponse <dynamic> queryResponse = await setIterator.FetchNextSetAsync();

                    Assert.AreEqual(3, queryResponse.Count());
                }

                //Reading all items on fixed container.
                setIterator = fixedContainer.Items
                              .GetItemIterator <dynamic>(maxItemCount: 10);
                while (setIterator.HasMoreResults)
                {
                    CosmosQueryResponse <dynamic> queryResponse = await setIterator.FetchNextSetAsync();

                    Assert.AreEqual(3, queryResponse.Count());
                }

                //Quering items on fixed container with CosmosContainerSettings.NonePartitionKeyValue.
                setIterator = fixedContainer.Items
                              .CreateItemQuery <dynamic>(sql, partitionKey: CosmosContainerSettings.NonePartitionKeyValue, maxItemCount: 10);
                while (setIterator.HasMoreResults)
                {
                    CosmosQueryResponse <dynamic> queryResponse = await setIterator.FetchNextSetAsync();

                    Assert.AreEqual(2, queryResponse.Count());
                }

                //Quering items on fixed container with non-none PK.
                setIterator = fixedContainer.Items
                              .CreateItemQuery <dynamic>(sql, partitionKey: itemWithPK.status, maxItemCount: 10);
                while (setIterator.HasMoreResults)
                {
                    CosmosQueryResponse <dynamic> queryResponse = await setIterator.FetchNextSetAsync();

                    Assert.AreEqual(1, queryResponse.Count());
                }

                //Deleting item from fixed container with CosmosContainerSettings.NonePartitionKeyValue.
                CosmosItemResponse <ToDoActivity> deleteResponseWithoutPk = await fixedContainer.Items.DeleteItemAsync <ToDoActivity>(
                    partitionKey : CosmosContainerSettings.NonePartitionKeyValue,
                    id : itemWithoutPK.id);

                Assert.IsNull(deleteResponseWithoutPk.Resource);
                Assert.AreEqual(HttpStatusCode.NoContent, deleteResponseWithoutPk.StatusCode);

                //Deleting item from fixed container with non-none PK.
                CosmosItemResponse <ToDoActivityAfterMigration> deleteResponseWithPk = await fixedContainer.Items.DeleteItemAsync <ToDoActivityAfterMigration>(
                    partitionKey : itemWithPK.status,
                    id : itemWithPK.id);

                Assert.IsNull(deleteResponseWithPk.Resource);
                Assert.AreEqual(HttpStatusCode.NoContent, deleteResponseWithPk.StatusCode);

                //Reading item from partitioned container with CosmosContainerSettings.NonePartitionKeyValue.
                CosmosItemResponse <ToDoActivity> undefinedItemResponse = await Container.Items.ReadItemAsync <ToDoActivity>(
                    partitionKey : CosmosContainerSettings.NonePartitionKeyValue,
                    id : undefinedPartitionItemId);

                Assert.IsNotNull(undefinedItemResponse.Resource);
                Assert.AreEqual(HttpStatusCode.OK, undefinedItemResponse.StatusCode);
                Assert.AreEqual(undefinedPartitionItemId, undefinedItemResponse.Resource.id);
            }
            finally
            {
                if (fixedContainer != null)
                {
                    await fixedContainer.DeleteAsync();
                }
            }
        }
Ejemplo n.º 16
0
        public async Task ItemEpkQuerySingleKeyRangeValidation()
        {
            IList <ToDoActivity> deleteList = new List <ToDoActivity>();
            CosmosContainer      container  = null;

            try
            {
                // Create a container large enough to have at least 2 partitions
                CosmosContainerResponse containerResponse = await this.database.Containers.CreateContainerAsync(
                    id : Guid.NewGuid().ToString(),
                    partitionKeyPath : "/pk",
                    throughput : 15000);

                container = containerResponse;

                // Get all the partition key ranges to verify there is more than one partition
                IRoutingMapProvider routingMapProvider = await this.cosmosClient.DocumentClient.GetPartitionKeyRangeCacheAsync();

                IReadOnlyList <PartitionKeyRange> ranges = await routingMapProvider.TryGetOverlappingRangesAsync(
                    containerResponse.Resource.ResourceId,
                    new Documents.Routing.Range <string>("00", "FF", isMaxInclusive: true, isMinInclusive: true));

                // If this fails the RUs of the container needs to be increased to ensure at least 2 partitions.
                Assert.IsTrue(ranges.Count > 1, " RUs of the container needs to be increased to ensure at least 2 partitions.");

                FeedOptions options = new FeedOptions()
                {
                    Properties = new Dictionary <string, object>()
                    {
                        { "x-ms-effective-partition-key-string", "AA" }
                    }
                };

                // Create a bad expression. It will not be called. Expression is not allowed to be null.
                IQueryable <int> queryable  = new List <int>().AsQueryable();
                Expression       expression = queryable.Expression;

                DocumentQueryExecutionContextBase.InitParams inputParams = new DocumentQueryExecutionContextBase.InitParams(
                    new DocumentQueryClient(this.cosmosClient.DocumentClient),
                    ResourceType.Document,
                    typeof(object),
                    expression,
                    options,
                    ((CosmosContainerCore)container).LinkUri.OriginalString,
                    false,
                    Guid.NewGuid());

                DefaultDocumentQueryExecutionContext defaultDocumentQueryExecutionContext = new DefaultDocumentQueryExecutionContext(inputParams, true);

                // There should only be one range since the EPK option is set.
                List <PartitionKeyRange> partitionKeyRanges = await DocumentQueryExecutionContextFactory.GetTargetPartitionKeyRanges(
                    queryExecutionContext : defaultDocumentQueryExecutionContext,
                    partitionedQueryExecutionInfo : null,
                    collection : containerResponse,
                    feedOptions : options);

                Assert.IsTrue(partitionKeyRanges.Count == 1, "Only 1 partition key range should be selected since the EPK option is set.");
            }
            finally
            {
                if (container != null)
                {
                    await container.DeleteAsync();
                }
            }
        }