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();
        }
Esempio n. 2
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);
        }
Esempio n. 3
0
        public async Task IteratorTest()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

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

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());

            HashSet <string> containerIds = new HashSet <string>();
            CosmosResultSetIterator <CosmosContainerSettings> resultSet = this.cosmosDatabase.Containers.GetContainerIterator();

            while (resultSet.HasMoreResults)
            {
                foreach (CosmosContainerSettings setting in await resultSet.FetchNextSetAsync())
                {
                    if (!containerIds.Contains(setting.Id))
                    {
                        containerIds.Add(setting.Id);
                    }
                }
            }

            Assert.IsTrue(containerIds.Count > 0, "The iterator did not find any containers.");
            Assert.IsTrue(containerIds.Contains(containerName), "The iterator did not find the created container");

            containerResponse = await containerResponse.Container.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Esempio n. 4
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);
        }
Esempio n. 5
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);
        }
        public async Task TestInitialize()
        {
            await base.TestInit();

            string containerName = Guid.NewGuid().ToString();
            CosmosContainerResponse cosmosContainerResponse = await this.database.Containers
                                                              .CreateContainerIfNotExistsAsync(containerName, "/user");

            this.container = cosmosContainerResponse;
        }
Esempio n. 7
0
        private static async Task <CosmosContainer> CreateContainer()
        {
            // Set throughput to the minimum value of 400 RU/s
            CosmosContainerResponse simpleContainer = await database.Containers.CreateContainerIfNotExistsAsync(
                id : containerId,
                partitionKeyPath : partitionKey,
                throughput : 400);

            Console.WriteLine($"\n1.1. Created container :{simpleContainer.Container.Id}");
            return(simpleContainer);
        }
Esempio 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 TestInitialize()
        {
            await base.ChangeFeedTestInit();

            string PartitionKey = "/pk";
            CosmosContainerResponse response = await this.database.Containers.CreateContainerAsync(
                new CosmosContainerSettings(id : Guid.NewGuid().ToString(), partitionKeyPath : PartitionKey),
                throughput : 10000,
                cancellationToken : this.cancellationToken);

            this.Container = response;
        }
        public async Task TestInitialize()
        {
            await base.TestInit();

            string PartitionKey = "/status";
            CosmosContainerResponse response = await this.database.Containers.CreateContainerAsync(
                new CosmosContainerSettings(id : Guid.NewGuid().ToString(), partitionKeyPath : PartitionKey),
                cancellationToken : this.cancellationToken);

            Assert.IsNotNull(response);
            this.container      = response;
            this.jsonSerializer = new CosmosDefaultJsonSerializer();
        }
Esempio n. 11
0
        public async Task NegativePartitionedCreateDelete()
        {
            string containerName = Guid.NewGuid().ToString();

            PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition();

            partitionKeyDefinition.Paths.Add("/users");
            partitionKeyDefinition.Paths.Add("/test");

            CosmosContainerSettings settings          = new CosmosContainerSettings(containerName, partitionKeyDefinition);
            CosmosContainerResponse containerResponse = await this.cosmosDatabase.Containers.CreateContainerAsync(settings);

            Assert.Fail("Multiple partition keys should have caused an exception.");
        }
Esempio n. 12
0
        public async Task PartitionedCreateDelete()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

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

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());

            containerResponse = await containerResponse.Container.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Esempio n. 13
0
        public async Task CreateHashV1Container()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            CosmosContainerSettings settings = new CosmosContainerSettings(containerName, partitionKeyPath);

            settings.PartitionKeyDefinitionVersion = Cosmos.PartitionKeyDefinitionVersion.V1;

            CosmosContainerResponse cosmosContainerResponse = await this.cosmosDatabase.Containers.CreateContainerAsync(settings);

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

            Assert.AreEqual(Cosmos.PartitionKeyDefinitionVersion.V1, cosmosContainerResponse.Resource.PartitionKeyDefinitionVersion);
        }
Esempio n. 14
0
        private static async Task CreateContainerWithTtlExpiration()
        {
            CosmosContainerSettings containerSettings = new CosmosContainerSettings(
                id: "TtlExpiryContainer",
                partitionKeyPath: partitionKey);

            containerSettings.DefaultTimeToLive = TimeSpan.FromDays(1); //expire in 1 day

            CosmosContainerResponse ttlEnabledContainerResponse = await database.Containers.CreateContainerIfNotExistsAsync(
                containerSettings : containerSettings);

            CosmosContainerSettings returnedSettings = ttlEnabledContainerResponse;

            Console.WriteLine($"\n1.3. Created Container \n{returnedSettings.Id} with TTL expiration of {returnedSettings.DefaultTimeToLive}");

            await ttlEnabledContainerResponse.Container.DeleteAsync();
        }
Esempio n. 15
0
        public async Task StreamIteratorTest()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

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

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());

            containerName     = Guid.NewGuid().ToString();
            containerResponse = await this.cosmosDatabase.Containers.CreateContainerAsync(containerName, partitionKeyPath);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());

            HashSet <string>            containerIds = new HashSet <string>();
            CosmosFeedResultSetIterator resultSet    = this.cosmosDatabase.Containers.GetContainerStreamIterator(
                maxItemCount: 1,
                requestOptions: new CosmosQueryRequestOptions());

            while (resultSet.HasMoreResults)
            {
                using (CosmosResponseMessage message = await resultSet.FetchNextSetAsync())
                {
                    Assert.AreEqual(HttpStatusCode.OK, message.StatusCode);
                    CosmosDefaultJsonSerializer defaultJsonSerializer = new CosmosDefaultJsonSerializer();
                    dynamic containers = defaultJsonSerializer.FromStream <dynamic>(message.Content).DocumentCollections;
                    foreach (dynamic container in containers)
                    {
                        string id = container.id.ToString();
                        containerIds.Add(id);
                    }
                }
            }

            Assert.IsTrue(containerIds.Count > 0, "The iterator did not find any containers.");
            Assert.IsTrue(containerIds.Contains(containerName), "The iterator did not find the created container");

            containerResponse = await containerResponse.Container.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Esempio n. 16
0
        public async Task ContainerContractTest()
        {
            CosmosContainerResponse response = await this.cosmosDatabase.Containers.CreateContainerAsync(new Guid().ToString(), "/id");

            Assert.IsNotNull(response);
            Assert.IsTrue(response.RequestCharge > 0);
            Assert.IsNotNull(response.Headers);
            Assert.IsNotNull(response.Headers.ActivityId);

            CosmosContainerSettings containerSettings = response.Resource;

            Assert.IsNotNull(containerSettings.Id);
            Assert.IsNotNull(containerSettings.ResourceId);
            Assert.IsNotNull(containerSettings.ETag);
            Assert.IsTrue(containerSettings.LastModified.HasValue);

            Assert.IsTrue(containerSettings.LastModified.Value > new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), containerSettings.LastModified.Value.ToString());
        }
Esempio n. 17
0
        public async Task TestInitialize()
        {
            await base.TestInit();

            CosmosContainerResponse response = await this.database.Containers.CreateContainerAsync(
                new CosmosContainerSettings(id : Guid.NewGuid().ToString(), partitionKeyPath : PartitionKey),
                throughput : 50000,
                cancellationToken : this.cancellationToken);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Container);
            Assert.IsNotNull(response.Resource);
            this.Container = (CosmosContainerCore)response;

            FeedResponse <PartitionKeyRange> pkRangesFeed = await this.cosmosClient.DocumentClient.ReadPartitionKeyRangeFeedAsync(this.Container.LinkUri);

            Assert.IsTrue(pkRangesFeed.Count > 1, "Refresh container throughput to have at-least > 1 pk-range");
        }
        private static async Task RoundTripWithLocal(Cosmos.IndexingPolicy indexingPolicy)
        {
            PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition {
                Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/id" }), Kind = PartitionKind.Hash
            };
            CosmosContainerSettings containerSetting = new CosmosContainerSettings()
            {
                Id             = Guid.NewGuid().ToString(),
                IndexingPolicy = indexingPolicy,
                PartitionKey   = partitionKeyDefinition
            };

            CosmosDatabase cosmosDatabase = await cosmosClient.Databases.CreateDatabaseIfNotExistsAsync(IndexingPolicyTests.database.Id);

            CosmosContainerResponse cosmosContainerResponse = await cosmosDatabase.Containers.CreateContainerAsync(containerSetting);

            Assert.IsTrue(IndexingPolicyTests.indexingPolicyEqualityComparer.Equals(indexingPolicy, containerSetting.IndexingPolicy));
        }
        public async Task ChangeFeedTestInit()
        {
            await base.TestInit();

            string PartitionKey = "/id";
            CosmosContainerResponse response = await this.database.Containers.CreateContainerAsync(
                new CosmosContainerSettings(id : "monitored", partitionKeyPath : PartitionKey),
                cancellationToken : this.cancellationToken);

            this.Container = response;


            response = await this.database.Containers.CreateContainerAsync(
                new CosmosContainerSettings(id : "leases", partitionKeyPath : PartitionKey),
                cancellationToken : this.cancellationToken);

            this.LeaseContainer = response;
        }
Esempio n. 20
0
        public async Task PartitionedCRUDTest()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

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

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());

            CosmosContainerSettings settings = new CosmosContainerSettings(containerName, partitionKeyPath)
            {
                IndexingPolicy = new Cosmos.IndexingPolicy()
                {
                    IndexingMode = Cosmos.IndexingMode.None,
                    Automatic    = false
                }
            };

            CosmosContainer cosmosContainer = containerResponse;

            containerResponse = await cosmosContainer.ReplaceAsync(settings);

            Assert.AreEqual(HttpStatusCode.OK, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
            Assert.AreEqual(Cosmos.IndexingMode.None, containerResponse.Resource.IndexingPolicy.IndexingMode);
            Assert.IsFalse(containerResponse.Resource.IndexingPolicy.Automatic);

            containerResponse = await cosmosContainer.ReadAsync();

            Assert.AreEqual(HttpStatusCode.OK, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(Cosmos.PartitionKeyDefinitionVersion.V2, containerResponse.Resource.PartitionKeyDefinitionVersion);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
            Assert.AreEqual(Cosmos.IndexingMode.None, containerResponse.Resource.IndexingPolicy.IndexingMode);
            Assert.IsFalse(containerResponse.Resource.IndexingPolicy.Automatic);

            containerResponse = await containerResponse.Container.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
        public async Task TestPreProcessingHandler()
        {
            CosmosRequestHandler preProcessHandler = new PreProcessingTestHandler();
            CosmosClient         client            = MockDocumentClient.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)
            {
                CosmosItemRequestOptions options = new CosmosItemRequestOptions();
                options.Properties = new Dictionary <string, object>();
                options.Properties.Add(PreProcessingTestHandler.StatusCodeName, code);

                CosmosItemResponse <object> response = await container.Items.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)
            {
                CosmosContainerRequestOptions options = new CosmosContainerRequestOptions();
                options.Properties = new Dictionary <string, object>();
                options.Properties.Add(PreProcessingTestHandler.StatusCodeName, code);

                CosmosContainerResponse response = await container.DeleteAsync(options);

                Console.WriteLine($"Got status code {response.StatusCode}");
                Assert.AreEqual(code, response.StatusCode);
            }
        }
Esempio n. 22
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 TestInitialize()
        {
            this.cancellationTokenSource = new CancellationTokenSource();
            this.cancellationToken       = this.cancellationTokenSource.Token;

            this.cosmosClient = TestCommon.CreateCosmosClient();
            this.database     = await this.cosmosClient.Databases.CreateDatabaseAsync(Guid.NewGuid().ToString(),
                                                                                      cancellationToken : this.cancellationToken);

            this.documentClient = TestCommon.CreateClient(true, defaultConsistencyLevel: Documents.ConsistencyLevel.Session);

            string PartitionKey = "/partitionKey";
            CosmosContainerResponse response = await this.database.Containers.CreateContainerAsync(
                new CosmosContainerSettings(id : Guid.NewGuid().ToString(), partitionKeyPath : PartitionKey),
                cancellationToken : this.cancellationToken);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Container);
            Assert.IsNotNull(response.Resource);
            this.Container      = response;
            this.jsonSerializer = new CosmosDefaultJsonSerializer();
        }
Esempio n. 24
0
        internal static async Task <DocumentServiceLeaseStoreManager> InitializeLeaseStoreManagerAsync(
            DocumentServiceLeaseStoreManager documentServiceLeaseStoreManager,
            CosmosContainer leaseContainer,
            string leaseContainerPrefix,
            string instanceName)
        {
            if (documentServiceLeaseStoreManager == null)
            {
                CosmosContainerResponse cosmosContainerResponse = await leaseContainer.ReadAsync().ConfigureAwait(false);

                CosmosContainerSettings containerSettings = cosmosContainerResponse.Resource;

                bool isPartitioned =
                    containerSettings.PartitionKey != null &&
                    containerSettings.PartitionKey.Paths != null &&
                    containerSettings.PartitionKey.Paths.Count > 0;
                if (isPartitioned &&
                    (containerSettings.PartitionKey.Paths.Count != 1 || containerSettings.PartitionKey.Paths[0] != "/id"))
                {
                    throw new ArgumentException("The lease collection, if partitioned, must have partition key equal to id.");
                }

                RequestOptionsFactory requestOptionsFactory = isPartitioned ?
                                                              (RequestOptionsFactory) new PartitionedByIdCollectionRequestOptionsFactory() :
                                                              (RequestOptionsFactory) new SinglePartitionRequestOptionsFactory();

                DocumentServiceLeaseStoreManagerBuilder leaseStoreManagerBuilder = new DocumentServiceLeaseStoreManagerBuilder()
                                                                                   .WithLeasePrefix(leaseContainerPrefix)
                                                                                   .WithLeaseContainer(leaseContainer)
                                                                                   .WithRequestOptionsFactory(requestOptionsFactory)
                                                                                   .WithHostName(instanceName);

                documentServiceLeaseStoreManager = await leaseStoreManagerBuilder.BuildAsync().ConfigureAwait(false);
            }

            return(documentServiceLeaseStoreManager);
        }
Esempio n. 25
0
 public TodoRepository(CosmosContainerResponse containerResponse, string partitionKey) : base(containerResponse, partitionKey)
 {
 }
Esempio n. 26
0
 public TodoRepository(CosmosContainerResponse containerResponse) : this(containerResponse, "/UserName")
 {
 }
Esempio n. 27
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();
                }
            }
        }
Esempio n. 28
0
        public static async Task Main(string[] args)
        {
            try
            {
                databaseId  = "deviceInformation" + Guid.NewGuid().ToString();
                containerId = "device-samples" + Guid.NewGuid().ToString();

                IConfigurationRoot configuration = new ConfigurationBuilder()
                                                   .AddJsonFile("appSettings.json")
                                                   .Build();

                string endpoint = configuration["EndPointUrl"];
                if (string.IsNullOrEmpty(endpoint))
                {
                    throw new ArgumentNullException("Please specify a valid endpoint in the appSettings.json");
                }

                string authKey = configuration["AuthorizationKey"];
                if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret key"))
                {
                    throw new ArgumentException("Please specify a valid AuthorizationKey in the appSettings.json");
                }

                using (CosmosClient client = new CosmosClient(endpoint, authKey))
                {
                    CosmosDatabase database = await client.Databases.CreateDatabaseIfNotExistsAsync(databaseId);

                    // Create the container using REST API without a partition key definition
                    await Program.CreateNonPartitionedContainerAsync(endpoint, authKey);

                    CosmosContainer container = database.Containers[containerId];

                    // Read back the same container and verify that partition key path is populated
                    // Partition key is returned when read from V3 SDK.
                    CosmosContainerResponse containerResposne = await container.ReadAsync();

                    if (containerResposne.Resource.PartitionKeyPath != null)
                    {
                        Console.WriteLine("Container Partition Key path {0}", containerResposne.Resource.PartitionKeyPath);
                    }
                    else
                    {
                        throw new Exception("Unexpected error : Partition Key is not populated in a migrated collection");
                    }

                    Console.WriteLine("--Demo Item operations with no partition key--");
                    await Program.ItemOperationsWithNonePartitionKeyValue(container);

                    Console.WriteLine("--Demo Item operations with valid partition key--");
                    await Program.ItemOperationsWithValidPartitionKeyValue(container);

                    Console.WriteLine("--Demo migration of items inserted with no partition key to items with a partition key--");
                    await Program.MigratedItemsFromNonePartitionKeyToValidPartitionKeyValue(container);

                    // Clean up the database -- for rerunning the sample
                    await database.DeleteAsync();
                }
            }
            catch (CosmosException cre)
            {
                Console.WriteLine(cre.ToString());
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
            }
            finally
            {
                Console.WriteLine("End of demo, press any key to exit.");
                Console.ReadKey();
            }
        }
Esempio n. 29
0
 public GenericRepository(CosmosContainerResponse containerResponse, string partitionKey)
 {
     this.ContainerResponse = containerResponse;
     this.PartitionKey      = partitionKey;
     this.SetupDefaultFunction();
 }
Esempio n. 30
0
        public async Task NoPartitionedCreateFail()
        {
            string containerName = Guid.NewGuid().ToString();

            try
            {
                new CosmosContainerSettings(id: containerName, partitionKeyPath: null);
                Assert.Fail("Create should throw null ref exception");
            }
            catch (ArgumentNullException ae)
            {
                Assert.IsNotNull(ae);
            }

            try
            {
                new CosmosContainerSettings(id: containerName, partitionKeyDefinition: null);
                Assert.Fail("Create should throw null ref exception");
            }
            catch (ArgumentNullException ae)
            {
                Assert.IsNotNull(ae);
            }

            CosmosContainerSettings settings = new CosmosContainerSettings()
            {
                Id = containerName
            };

            try
            {
                CosmosContainerResponse containerResponse = await this.cosmosDatabase.Containers.CreateContainerAsync(settings);

                Assert.Fail("Create should throw null ref exception");
            }
            catch (ArgumentNullException ae)
            {
                Assert.IsNotNull(ae);
            }

            try
            {
                CosmosContainerResponse containerResponse = await this.cosmosDatabase.Containers.CreateContainerIfNotExistsAsync(settings);

                Assert.Fail("Create should throw null ref exception");
            }
            catch (ArgumentNullException ae)
            {
                Assert.IsNotNull(ae);
            }

            try
            {
                CosmosContainerResponse containerResponse = await this.cosmosDatabase.Containers.CreateContainerAsync(id : containerName, partitionKeyPath : null);

                Assert.Fail("Create should throw null ref exception");
            }
            catch (ArgumentNullException ae)
            {
                Assert.IsNotNull(ae);
            }

            try
            {
                CosmosContainerResponse containerResponse = await this.cosmosDatabase.Containers.CreateContainerIfNotExistsAsync(id : containerName, partitionKeyPath : null);

                Assert.Fail("Create should throw null ref exception");
            }
            catch (ArgumentNullException ae)
            {
                Assert.IsNotNull(ae);
            }
        }