Beispiel #1
0
        public async Task TestCustomJsonSerializer()
        {
            int toStreamCount   = 0;
            int fromStreamCount = 0;

            Mock <CosmosJsonSerializer> mockJsonSerializer = new Mock <CosmosJsonSerializer>();

            //The item object will be serialized with the custom json serializer.
            ToDoActivity testItem = CreateRandomToDoActivity();

            mockJsonSerializer.Setup(x => x.ToStream <ToDoActivity>(It.IsAny <ToDoActivity>())).Callback(() => toStreamCount++).Returns(this.jsonSerializer.ToStream <ToDoActivity>(testItem));
            mockJsonSerializer.Setup(x => x.FromStream <ToDoActivity>(It.IsAny <Stream>())).Callback <Stream>(x => { x.Dispose(); fromStreamCount++; }).Returns(testItem);

            //Create a new cosmos client with the mocked cosmos json serializer
            CosmosClient mockClient = TestCommon.CreateCosmosClient(
                (cosmosClientBuilder) => cosmosClientBuilder.WithCustomJsonSerializer(mockJsonSerializer.Object));
            CosmosContainer mockContainer = mockClient.GetContainer(this.database.Id, this.container.Id);

            //Validate that the custom json serializer is used for creating the item
            ItemResponse <ToDoActivity> response = await mockContainer.CreateItemAsync <ToDoActivity>(item : testItem);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

            Assert.AreEqual(1, toStreamCount);
            Assert.AreEqual(1, fromStreamCount);

            await mockContainer.DeleteItemAsync <ToDoActivity>(new Cosmos.PartitionKey(testItem.status), testItem.id);
        }
        /// <summary>
        /// The function demonstrates the Item CRUD operation using the NonePartitionKeyValue
        /// NonePartitionKeyValue represents the information that the current item doesn't have a value for partitition key
        /// All items inserted pre-migration are grouped into this logical partition and can be accessed by providing this value
        /// for the partitionKey parameter
        /// New item CRUD could be performed using this NonePartitionKeyValue to target the same logical partition
        /// </summary>
        private static async Task ItemOperationsWithNonePartitionKeyValue(CosmosContainer container)
        {
            string itemid = Guid.NewGuid().ToString();
            DeviceInformationItem itemWithoutPK = GetDeviceWithNoPartitionKey(itemid);

            // Insert a new item with NonePartitionKeyValue
            ItemResponse <DeviceInformationItem> createResponse = await container.CreateItemAsync <DeviceInformationItem>(
                partitionKey : PartitionKey.NonePartitionKeyValue,
                item : itemWithoutPK);

            Console.WriteLine("Creating Item {0} Status Code {1}", itemid, createResponse.StatusCode);

            // Read an existing item with NonePartitionKeyValue
            ItemResponse <DeviceInformationItem> readResponse = await container.ReadItemAsync <DeviceInformationItem>(
                partitionKey : PartitionKey.NonePartitionKeyValue,
                id : itemid);

            Console.WriteLine("Reading Item {0} Status Code {1}", itemid, readResponse.StatusCode);

            // Replace the content of existing item with NonePartitionKeyValue
            itemWithoutPK.DeviceId = Guid.NewGuid().ToString();
            ItemResponse <DeviceInformationItem> replaceResponse = await container.ReplaceItemAsync <DeviceInformationItem>(
                partitionKey : PartitionKey.NonePartitionKeyValue,
                id : itemWithoutPK.Id,
                item : itemWithoutPK);

            Console.WriteLine("Replacing Item {0} Status Code {1}", itemid, replaceResponse.StatusCode);

            // Delete an item with NonePartitionKeyValue.
            ItemResponse <DeviceInformationItem> deleteResponse = await container.DeleteItemAsync <DeviceInformationItem>(
                partitionKey : PartitionKey.NonePartitionKeyValue,
                id : itemid);

            Console.WriteLine("Deleting Item {0} Status Code {1}", itemid, deleteResponse.StatusCode);
        }
Beispiel #3
0
        /// <summary>
        /// Runs a simple script which just does a server side query
        /// </summary>
        private static async Task RunSimpleScript(CosmosContainer container)
        {
            // 1. Create stored procedure for script.
            string scriptFileName = @"js\SimpleScript.js";
            string scriptId       = Path.GetFileNameWithoutExtension(scriptFileName);

            await TryDeleteStoredProcedure(container, scriptId);

            CosmosScripts           cosmosScripts = container.GetScripts();
            StoredProcedureResponse sproc         = await cosmosScripts.CreateStoredProcedureAsync(new CosmosStoredProcedureSettings(scriptId, File.ReadAllText(scriptFileName)));

            // 2. Create a document.
            SampleDocument doc = new SampleDocument
            {
                Id           = Guid.NewGuid().ToString(),
                LastName     = "Estel",
                Headquarters = "Russia",
                Locations    = new Location[] { new Location {
                                                    Country = "Russia", City = "Novosibirsk"
                                                } },
                Income = 50000
            };

            ItemResponse <SampleDocument> created = await container.CreateItemAsync(doc, new PartitionKey(doc.LastName));

            // 3. Run the script. Pass "Hello, " as parameter.
            // The script will take the 1st document and echo: Hello, <document as json>.
            StoredProcedureExecuteResponse <string> response = await container.GetScripts().ExecuteStoredProcedureAsync <string, string>(new PartitionKey(doc.LastName), scriptId, "Hello");

            Console.WriteLine("Result from script: {0}\r\n", response.Resource);

            await container.DeleteItemAsync <SampleDocument>(new PartitionKey(doc.LastName), doc.Id);
        }
Beispiel #4
0
 public static async Task DeleteItemsByIdsAsync <T>(CosmosContainer container, List <string> ids, string partitionKeyValue)
 {
     // Delete item
     foreach (var id in ids)
     {
         await container.DeleteItemAsync <T>(id, new PartitionKey(partitionKeyValue));
     }
     ;
 }
Beispiel #5
0
        public async Task <Image> DeleteImageAsync(string id)
        {
            var partitionKey = new PartitionKey(id);
            var response     = await CosmosContainer.DeleteItemAsync <Image>(id, partitionKey);

            return(response.Value);

            //TODO : Bubble up errors through the stack
        }
Beispiel #6
0
        private static async Task DeleteItemAsync()
        {
            Console.WriteLine("\n1.7 - Deleting a item");
            ItemResponse <SalesOrder> response = await container.DeleteItemAsync <SalesOrder>(
                partitionKey : new PartitionKey("Account1"),
                id : "SalesOrder3");

            Console.WriteLine("Request charge of delete operation: {0}", response.RequestCharge);
            Console.WriteLine("StatusCode of operation: {0}", response.StatusCode);
        }
 public async Task DeleteAsync(string entityId, string partionKey)
 {
     try
     {
         CosmosContainer container = GetContainer();
         await container.DeleteItemAsync <T>(entityId, new PartitionKey(partionKey));
     }catch (Exception ex)
     {
         Log.Error($"Entity with ID: {entityId} was not removed successfully - error details: {ex.Message}");
     }
 }
        // </ReplaceFamilyItemAsync>

        // <DeleteFamilyItemAsync>
        /// <summary>
        /// Delete an item in the container
        /// </summary>
        private static async Task DeleteFamilyItemAsync(CosmosClient cosmosClient)
        {
            CosmosContainer container = cosmosClient.GetContainer(Program.DatabaseId, Program.ContainerId);

            string partitionKeyValue = "Wakefield";
            string familyId          = "Wakefield.7";

            // Delete an item. Note we must provide the partition key value and id of the item to delete
            ItemResponse <Family> wakefieldFamilyResponse = await container.DeleteItemAsync <Family>(familyId, new PartitionKey(partitionKeyValue));

            Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, familyId);
        }
        public static async Task <T> TryDeleteItemAsync <T>(
            this CosmosContainer container,
            object partitionKey,
            string itemId,
            ItemRequestOptions cosmosItemRequestOptions = null)
        {
            var response = await container.DeleteItemAsync <T>(partitionKey, itemId, cosmosItemRequestOptions).ConfigureAwait(false);

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(default(T));
            }

            return(response.Resource);
        }
        public async Task DeleteAsync(string entityId)
        {
            try
            {
                CosmosContainer container = GetContainer();

                await container.DeleteItemAsync <T>(entityId, new PartitionKey(entityId));
            }
            catch (CosmosException ex)
            {
                _logger.LogError(ex.Message);

                if (ex.Status != (int)HttpStatusCode.NotFound)
                {
                    throw;
                }
            }
        }
Beispiel #11
0
        public async Task DeleteAsync(string entityId)
        {
            try
            {
                CosmosContainer container = GetContainer();

                await container.DeleteItemAsync <T>(entityId, new PartitionKey(entityId));
            }
            catch (CosmosException ex)
            {
                Log.Error($"Entity with ID: {entityId} was not removed successfully - error details: {ex.Message}");

                if (ex.Status != (int)HttpStatusCode.NotFound)
                {
                    throw;
                }
            }
        }
Beispiel #12
0
        private async void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            var clickedId = dataGridView1.Rows[e.Row.Index].Cells[0].Value.ToString();

            try
            {
                CosmosContainer        container     = cosmosClient.GetContainer(_settings.DatabaseId, _settings.ContainerId);
                Session                session       = new Session();
                ItemResponse <Session> sessionCosmos = await container.DeleteItemAsync <Session>(clickedId, new PartitionKey(session.partition));

                _allSessions.Remove(_allSessions.Where(c => c.id.Equals(clickedId)).FirstOrDefault());
            }
            catch (Exception)
            {
                this.Cursor = System.Windows.Forms.Cursors.Default;
            }


            Thread.Sleep(100);
            this.Cursor = System.Windows.Forms.Cursors.Default;
        }
        /// <summary>
        /// The function demonstrates CRUD operations on the migrated collection supplying a value for the partition key
        /// <summary>
        private static async Task ItemOperationsWithValidPartitionKeyValue(CosmosContainer container)
        {
            string itemid       = Guid.NewGuid().ToString();
            string partitionKey = "a";
            DeviceInformationItem itemWithPK = GetDeviceWithPartitionKey(itemid, partitionKey);

            // Insert a new item
            ItemResponse <DeviceInformationItem> createResponse = await container.CreateItemAsync <DeviceInformationItem>(
                partitionKey : new PartitionKey(partitionKey),
                item : itemWithPK);

            Console.WriteLine("Creating Item {0} with Partition Key Status Code {1}", itemid, createResponse.StatusCode);

            // Read the item back
            ItemResponse <DeviceInformationItem> readResponse = await container.ReadItemAsync <DeviceInformationItem>(
                partitionKey : new PartitionKey(partitionKey),
                id : itemid);

            Console.WriteLine("Reading Item {0} with Partition Key Status Code {1}", itemid, readResponse.StatusCode);

            // Replace the content of the item
            itemWithPK.DeviceId = Guid.NewGuid().ToString();
            ItemResponse <DeviceInformationItem> replaceResponse = await container.ReplaceItemAsync <DeviceInformationItem>(
                partitionKey : new PartitionKey(partitionKey),
                id : itemWithPK.Id,
                item : itemWithPK);

            Console.WriteLine("Replacing Item {0} with Partition Key Status Code {1}", itemid, replaceResponse.StatusCode);

            // Delete the item.
            ItemResponse <DeviceInformationItem> deleteResponse = await container.DeleteItemAsync <DeviceInformationItem>(
                partitionKey : new PartitionKey(partitionKey),
                id : itemid);

            Console.WriteLine("Deleting Item {0} with Partition Key Status Code {1}", itemid, deleteResponse.StatusCode);
        }
Beispiel #14
0
 public async Task <ItemResponse <Recipe> > DeleteRecipeAsync(Recipe recipe)
 {
     _logger.LogInformation("Deleting item: " + recipe.id);
     return(await _cosmosContainer.DeleteItemAsync <Recipe>(recipe.id, new PartitionKey(recipe.type)));
 }
Beispiel #15
0
 public async Task DeleteTestDataAsync(string id)
 {
     await _container.DeleteItemAsync <TestData>(id, new PartitionKey(id));
 }
        private async Task VerifyItemNullPartitionKeyExpectations(
            dynamic testItem,
            ItemRequestOptions requestOptions = null)
        {
            TestHandler testHandler = new TestHandler((request, cancellationToken) =>
            {
                Assert.IsNotNull(request.Headers.PartitionKey);
                Assert.AreEqual(Documents.Routing.PartitionKeyInternal.Undefined.ToString(), request.Headers.PartitionKey.ToString());

                return(Task.FromResult(new CosmosResponseMessage(HttpStatusCode.OK)));
            });

            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(
                (cosmosClientBuilder) => cosmosClientBuilder.AddCustomHandlers(testHandler));

            CosmosContainer container = client.GetDatabase("testdb")
                                        .GetContainer("testcontainer");

            await container.CreateItemAsync <dynamic>(
                item : testItem,
                requestOptions : requestOptions);

            await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() =>
            {
                await container.ReadItemAsync <dynamic>(
                    partitionKey: null,
                    id: testItem.id,
                    requestOptions: requestOptions);
            }, "ReadItemAsync should throw ArgumentNullException without the correct request option set.");

            await container.UpsertItemAsync <dynamic>(
                item : testItem,
                requestOptions : requestOptions);

            await container.ReplaceItemAsync <dynamic>(
                id : testItem.id,
                item : testItem,
                requestOptions : requestOptions);

            await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() =>
            {
                await container.DeleteItemAsync <dynamic>(
                    partitionKey: null,
                    id: testItem.id,
                    requestOptions: requestOptions);
            }, "DeleteItemAsync should throw ArgumentNullException without the correct request option set.");

            CosmosJsonSerializerCore jsonSerializer = new CosmosJsonSerializerCore();

            using (Stream itemStream = jsonSerializer.ToStream <dynamic>(testItem))
            {
                await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() =>
                {
                    await container.CreateItemStreamAsync(
                        partitionKey: null,
                        streamPayload: itemStream,
                        requestOptions: requestOptions);
                }, "CreateItemAsync should throw ArgumentNullException without the correct request option set.");

                await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() =>
                {
                    await container.ReadItemStreamAsync(
                        partitionKey: null,
                        id: testItem.id,
                        requestOptions: requestOptions);
                }, "ReadItemAsync should throw ArgumentNullException without the correct request option set.");

                await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() =>
                {
                    await container.UpsertItemStreamAsync(
                        partitionKey: null,
                        streamPayload: itemStream,
                        requestOptions: requestOptions);
                }, "UpsertItemAsync should throw ArgumentNullException without the correct request option set.");

                await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() =>
                {
                    await container.ReplaceItemStreamAsync(
                        partitionKey: null,
                        id: testItem.id,
                        streamPayload: itemStream,
                        requestOptions: requestOptions);
                }, "ReplaceItemAsync should throw ArgumentNullException without the correct request option set.");

                await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() =>
                {
                    await container.DeleteItemStreamAsync(
                        partitionKey: null,
                        id: testItem.id,
                        requestOptions: requestOptions);
                }, "DeleteItemAsync should throw ArgumentNullException without the correct request option set.");
            }
        }
Beispiel #17
0
        private async Task VerifyItemOperations(
            object partitionKey,
            string partitionKeySerialized,
            dynamic testItem,
            ItemRequestOptions requestOptions = null)
        {
            CosmosResponseMessage response = null;
            HttpStatusCode httpStatusCode = HttpStatusCode.OK;
            int testHandlerHitCount = 0;
            TestHandler testHandler = new TestHandler((request, cancellationToken) =>
            {
                Assert.IsTrue(request.RequestUri.OriginalString.StartsWith(@"/dbs/testdb/colls/testcontainer"));
                Assert.AreEqual(requestOptions, request.RequestOptions);
                Assert.AreEqual(ResourceType.Document, request.ResourceType);
                Assert.IsNotNull(request.Headers.PartitionKey);
                Assert.AreEqual(partitionKeySerialized, request.Headers.PartitionKey);
                testHandlerHitCount++;
                response = new CosmosResponseMessage(httpStatusCode, request, errorMessage: null);
                response.Content = request.Content;
                return Task.FromResult(response);
            });

            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(
                (builder) => builder.AddCustomHandlers(testHandler));

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

            ItemResponse<dynamic> itemResponse = await container.CreateItemAsync<dynamic>(
                partitionKey: partitionKey,
                item: testItem,
                requestOptions: requestOptions);
            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.ReadItemAsync<dynamic>(
                partitionKey: partitionKey,
                id: testItem.id,
                requestOptions: requestOptions);
            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.UpsertItemAsync<dynamic>(
                partitionKey: partitionKey,
                item: testItem,
                requestOptions: requestOptions);
            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.ReplaceItemAsync<dynamic>(
                partitionKey: partitionKey,
                id: testItem.id,
                item: testItem,
                requestOptions: requestOptions);
            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.DeleteItemAsync<dynamic>(
                partitionKey: partitionKey,
                id: testItem.id,
                requestOptions: requestOptions);
            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            Assert.AreEqual(5, testHandlerHitCount, "An operation did not make it to the handler");

            CosmosJsonSerializerCore jsonSerializer = new CosmosJsonSerializerCore();
            using (Stream itemStream = jsonSerializer.ToStream<dynamic>(testItem))
            {
                using (CosmosResponseMessage streamResponse = await container.CreateItemAsStreamAsync(
                    partitionKey: partitionKey,
                    streamPayload: itemStream))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = jsonSerializer.ToStream<dynamic>(testItem))
            {
                using (CosmosResponseMessage streamResponse = await container.ReadItemAsStreamAsync(
                    partitionKey: partitionKey,
                    id: testItem.id,
                    requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = jsonSerializer.ToStream<dynamic>(testItem))
            {
                using (CosmosResponseMessage streamResponse = await container.UpsertItemAsStreamAsync(
                    partitionKey: partitionKey,
                    streamPayload: itemStream,
                    requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = jsonSerializer.ToStream<dynamic>(testItem))
            {
                using (CosmosResponseMessage streamResponse = await container.ReplaceItemAsStreamAsync(
                    partitionKey: partitionKey,
                    id: testItem.id,
                    streamPayload: itemStream,
                    requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = jsonSerializer.ToStream<dynamic>(testItem))
            {
                using (CosmosResponseMessage streamResponse = await container.DeleteItemAsStreamAsync(
                    partitionKey: partitionKey,
                    id: testItem.id,
                    requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            Assert.AreEqual(10, testHandlerHitCount, "A stream operation did not make it to the handler");
        }
Beispiel #18
0
        private async Task VerifyItemNullExceptions(
            dynamic testItem,
            ItemRequestOptions requestOptions = null)
        {
            TestHandler testHandler = new TestHandler((request, cancellationToken) =>
            {
                Assert.Fail("Null partition key should be blocked without the correct request option");
                return null;
            });

            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(
                (cosmosClientBuilder) => cosmosClientBuilder.AddCustomHandlers(testHandler));

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

            await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
            {
                await container.CreateItemAsync<dynamic>(
                    partitionKey: null,
                    item: testItem,
                    requestOptions: requestOptions);
            }, "CreateItemAsync should throw ArgumentNullException without the correct request option set.");

            await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
            {
                await container.ReadItemAsync<dynamic>(
                    partitionKey: null,
                    id: testItem.id,
                    requestOptions: requestOptions);
            }, "ReadItemAsync should throw ArgumentNullException without the correct request option set.");

            await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
            {
                await container.UpsertItemAsync<dynamic>(
                    partitionKey: null,
                    item: testItem,
                    requestOptions: requestOptions);
            }, "UpsertItemAsync should throw ArgumentNullException without the correct request option set.");

            await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
            {
                await container.ReplaceItemAsync<dynamic>(
                    partitionKey: null,
                    id: testItem.id,
                    item: testItem,
                    requestOptions: requestOptions);
            }, "ReplaceItemAsync should throw ArgumentNullException without the correct request option set.");

            await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
            {
                await container.DeleteItemAsync<dynamic>(
                    partitionKey: null,
                    id: testItem.id,
                    requestOptions: requestOptions);
            }, "DeleteItemAsync should throw ArgumentNullException without the correct request option set.");

            CosmosJsonSerializerCore jsonSerializer = new CosmosJsonSerializerCore();
            using (Stream itemStream = jsonSerializer.ToStream<dynamic>(testItem))
            {
                await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
                {
                    await container.CreateItemAsStreamAsync(
                        partitionKey: null,
                        streamPayload: itemStream,
                        requestOptions: requestOptions);
                }, "CreateItemAsync should throw ArgumentNullException without the correct request option set.");

                await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
                {
                    await container.ReadItemAsStreamAsync(
                        partitionKey: null,
                        id: testItem.id,
                        requestOptions: requestOptions);
                }, "ReadItemAsync should throw ArgumentNullException without the correct request option set.");

                await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
                {
                    await container.UpsertItemAsStreamAsync(
                        partitionKey: null,
                        streamPayload: itemStream,
                        requestOptions: requestOptions);
                }, "UpsertItemAsync should throw ArgumentNullException without the correct request option set.");

                await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
                {
                    await container.ReplaceItemAsStreamAsync(
                        partitionKey: null,
                        id: testItem.id,
                        streamPayload: itemStream,
                        requestOptions: requestOptions);
                }, "ReplaceItemAsync should throw ArgumentNullException without the correct request option set.");

                await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
                {
                    await container.DeleteItemAsStreamAsync(
                        partitionKey: null,
                        id: testItem.id,
                        requestOptions: requestOptions);
                }, "DeleteItemAsync should throw ArgumentNullException without the correct request option set.");
            }
        }
Beispiel #19
0
 public static async Task DeleteItemByIdAsync <T>(CosmosContainer container, string id, string partitionKeyValue)
 {
     // Delete item
     await container.DeleteItemAsync <T>(id, new PartitionKey(partitionKeyValue));
 }
 public async Task DeleteAsync(string id, PartitionKey partitionKey)
 {
     await _container.DeleteItemAsync <TEntity>(id, partitionKey);
 }
Beispiel #21
0
 public async Task DeleteAsync(Guid id)
 {
     await _container.DeleteItemAsync <T>(id.ToString(), new PartitionKey(id.ToString()));
 }
 public async Task DeleteAsync(string id, string partitionKey)
 {
     await _container.DeleteItemAsync <TEntity>(id, new PartitionKey(partitionKey));
 }
        /// <summary>
        ///  The function demonstrates migrating documents that were inserted without a value for partition key, and those inserted
        ///  pre-migration to other logical partitions, those with a value for partition key.
        /// </summary>
        private static async Task MigratedItemsFromNonePartitionKeyToValidPartitionKeyValue(CosmosContainer container)
        {
            // Pre-create a few items in the container to demo the migration
            const int ItemsToCreate = 4;

            // Insert a few items with no Partition Key
            for (int i = 0; i < ItemsToCreate; i++)
            {
                string itemid = Guid.NewGuid().ToString();
                DeviceInformationItem itemWithoutPK = GetDeviceWithNoPartitionKey(itemid);
                ItemResponse <DeviceInformationItem> createResponse = await container.CreateItemAsync <DeviceInformationItem>(
                    partitionKey : PartitionKey.NonePartitionKeyValue,
                    item : itemWithoutPK);
            }

            // Query items on the container that have no partition key value by supplying NonePartitionKeyValue
            // The operation is made in batches to not lose work in case of partial execution
            int resultsFetched = 0;
            CosmosSqlQueryDefinition             sql         = new CosmosSqlQueryDefinition("select * from r");
            FeedIterator <DeviceInformationItem> setIterator = container.CreateItemQuery <DeviceInformationItem>(sql, partitionKey: PartitionKey.NonePartitionKeyValue, maxItemCount: 2);

            while (setIterator.HasMoreResults)
            {
                FeedResponse <DeviceInformationItem> queryResponse = await setIterator.FetchNextSetAsync();

                resultsFetched += queryResponse.Count();

                // For the items returned with NonePartitionKeyValue
                IEnumerator <DeviceInformationItem> iter = queryResponse.GetEnumerator();
                while (iter.MoveNext())
                {
                    DeviceInformationItem item = iter.Current;
                    if (item.DeviceId != null)
                    {
                        // Using existing deviceID for partition key
                        item.PartitionKey = item.DeviceId;
                        Console.WriteLine("Migrating item {0} to Partition {1}", item.Id, item.DeviceId);
                        // Re-Insert into container with a partition key
                        // This could result in exception if the same item was inserted in a previous run of the program on existing container
                        // and the program stopped before the delete.
                        ItemResponse <DeviceInformationItem> createResponseWithPk = await container.CreateItemAsync <DeviceInformationItem>(
                            partitionKey : new PartitionKey(item.PartitionKey),
                            item : item);

                        // Deleting item from fixed container with CosmosContainerSettings.NonePartitionKeyValue.
                        ItemResponse <DeviceInformationItem> deleteResponseWithoutPk = await container.DeleteItemAsync <DeviceInformationItem>(
                            partitionKey : PartitionKey.NonePartitionKeyValue,
                            id : item.Id);
                    }
                }
            }
        }