예제 #1
0
        private static async Task ReadItemAsync()
        {
            Console.WriteLine("\n1.2 - Reading Item by Id");

            // Note that Reads require a partition key to be specified.
            ItemResponse <SalesOrder> response = await container.ReadItemAsync <SalesOrder>(
                partitionKey : new PartitionKey("Account1"),
                id : "SalesOrder1");

            // You can measure the throughput consumed by any operation by inspecting the RequestCharge property
            Console.WriteLine("Item read by Id {0}", response.Resource);
            Console.WriteLine("Request Units Charge for reading a Item by Id {0}", response.RequestCharge);

            SalesOrder readOrder = (SalesOrder)response;

            // Read the same item but as a stream.
            using (CosmosResponseMessage responseMessage = await container.ReadItemStreamAsync(
                       partitionKey: new PartitionKey("Account1"),
                       id: "SalesOrder1"))
            {
                // Item stream operations do not throw exceptions for better performance
                if (responseMessage.IsSuccessStatusCode)
                {
                    SalesOrder streamResponse = FromStream <SalesOrder>(responseMessage.Content);
                    Console.WriteLine($"\n1.2.2 - Item created {streamResponse.Id}");
                }
                else
                {
                    Console.WriteLine($"Read item from stream failed. Status code: {responseMessage.StatusCode} Message: {responseMessage.ErrorMessage}");
                }
            }
        }
예제 #2
0
파일: Form1.cs 프로젝트: zateckar/ApiTester
        /// <summary>
        /// Insert or update Note to the database
        /// </summary>
        private async void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                string clickedId = dataGridView1.Rows[e.RowIndex].Cells["Id"].Value.ToString();

                //Sqlite
                //var query = db.Table<Session>().Where(s => s.sqliteId.Equals(clickedId));
                //var session_pom = await query.FirstAsync();

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

                    session = sessionCosmos.Value;

                    session.Note = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

                    // await db.UpdateAsync(session);

                    sessionCosmos = await container.ReplaceItemAsync <Session>(session, session.id, new PartitionKey(session.partition));
                }
                catch (Exception)
                {
                    // throw;
                }
            }
        }
예제 #3
0
        public async Task <T> UpdateAsync(T entity)
        {
            try
            {
                CosmosContainer container = GetContainer();

                ItemResponse <BaseEntity> entityResult = await container
                                                         .ReadItemAsync <BaseEntity>(entity.Id.ToString(), new PartitionKey(entity.Id.ToString()));

                if (entityResult != null)
                {
                    await container
                    .ReplaceItemAsync(entity, entity.Id.ToString(), new PartitionKey(entity.Id.ToString()));
                }
                return(entity);
            }
            catch (CosmosException ex)
            {
                Log.Error($"Entity with ID: {entity.Id} was not updated successfully - error details: {ex.Message}");

                if (ex.Status != (int)HttpStatusCode.NotFound)
                {
                    throw;
                }

                return(null);
            }
        }
예제 #4
0
        /// <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);
        }
        public async Task <T> UpdateAsync(T entity)
        {
            try
            {
                CosmosContainer container = GetContainer();

                ItemResponse <BaseEntity> entityResult = await container
                                                         .ReadItemAsync <BaseEntity>(entity.Id.ToString(), new PartitionKey(entity.Id.ToString()));

                if (entityResult != null)
                {
                    await container
                    .ReplaceItemAsync(entity, entity.Id.ToString(), new PartitionKey(entity.Id.ToString()));
                }
                return(entity);
            }
            catch (CosmosException ex)
            {
                _logger.LogError(ex.Message);

                if (ex.Status != (int)HttpStatusCode.NotFound)
                {
                    throw;
                }

                return(null);
            }
        }
예제 #6
0
        public async Task <PersonEntity> GetById(string id)
        {
            ThrowIfDisposed();

            var response = await _cosmosContainer.ReadItemAsync <PersonEntity>(id, new PartitionKey(id));

            return(response.Value);
        }
        public async Task UpdateDatetimeAndNumberOfCompetitionsByTitleAndState(
            string title,
            string state,
            DateTime newDatetime,
            int newNumberOfCompetitors)
        {
            if (string.IsNullOrWhiteSpace(title))
            {
                throw new ArgumentException($"{nameof(title)} is null or empty");
            }
            if (string.IsNullOrWhiteSpace(state))
            {
                throw new ArgumentException($"{nameof(state)} is null or empty");
            }
            if (newDatetime == null)
            {
                throw new ArgumentNullException(nameof(newDatetime));
            }

            var requestedItemResponse = await _container
                                        .ReadItemAsync <Competition>(title, new PartitionKey(state));

            if (requestedItemResponse.Value == null)
            {
                throw new ApplicationException($"Item with title '{title}' and state '{state}' not found...");
            }

            _logger.LogInformation($"Item with title '{title}' and state '{state}' found");

            var requestUnits = GetRequestUnitHeader(requestedItemResponse.GetRawResponse().Headers);

            if (requestUnits != null)
            {
                _logger.LogInformation($"Charged request units: {requestUnits}");
            }

            var originalItem = requestedItemResponse.Value;

            originalItem.DateTime            = newDatetime;
            originalItem.NumberOfCompetitors = newNumberOfCompetitors;

            var replaceItemResponse = await _container
                                      .ReplaceItemAsync(originalItem, title, new PartitionKey(state));

            if (requestedItemResponse.Value == null)
            {
                throw new ApplicationException($"Item with title '{title}' and state '{state}' not found...");
            }

            _logger.LogInformation($"Item with title '{title}' and state '{state}' replaced");

            requestUnits = GetRequestUnitHeader(replaceItemResponse.GetRawResponse().Headers);
            if (requestUnits != null)
            {
                _logger.LogInformation($"Charged request units: {requestUnits}");
            }
        }
        public async Task <TEntity> GetByIdAsync(string id, PartitionKey partitionKey)
        {
            var itemResponse = await _container.ReadItemAsync <TEntity>(id, partitionKey);

            if (itemResponse != null && itemResponse.Value != null)
            {
                return(itemResponse.Value);
            }

            return(null);
        }
예제 #9
0
        static async Task <SaleData> GetSaleDataAsync(CosmosContainer container, string docId, string location)
        {
            try
            {
                ItemResponse <SaleData> result = await container.ReadItemAsync <SaleData>(docId, new PartitionKey(location));

                return(result.Value);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
예제 #10
0
        public async Task <T> GetAsync(Guid id)
        {
            try
            {
                ItemResponse <T> response = await _container.ReadItemAsync <T>(id.ToString(), new PartitionKey(id.ToString()));

                return(response);
            }
            catch (CosmosException ex) when(ex.Status == 404)
            {
                return(default(T));
            }
        }
예제 #11
0
        static async Task <SaleData> InsertSaleDataAsync(CosmosContainer container, SaleData saleData)
        {
            try
            {
                ItemResponse <SaleData> result = await container.ReadItemAsync <SaleData>(saleData.Id, new PartitionKey(saleData.Location));

                Console.WriteLine("Item already exists for document with id " + result.Value.Id);
                return(null);
            } catch (CosmosException ex) when(ex.Status == (int)HttpStatusCode.NotFound)
            {
                ItemResponse <SaleData> result = await container.CreateItemAsync <SaleData>(saleData, new PartitionKey(saleData.Location));

                Console.WriteLine("New document inserted with id " + result.Value.Id);
                return(result.Value);
            }
        }
        public static async Task <T> TryGetItemAsync <T>(
            this CosmosContainer container,
            object partitionKey,
            string itemId)
        {
            var response = await container.ReadItemAsync <T>(
                partitionKey,
                itemId)
                           .ConfigureAwait(false);

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

            return(response);
        }
        public async Task TransportInterceptorContractTest()
        {
            CosmosClient cosmosClient = TestCommon.CreateCosmosClient(
                builder =>
            {
                builder.WithTransportClientHandlerFactory(transportClient => new TransportClientWrapper(transportClient, TransportWrapperTests.Interceptor));
            });

            CosmosDatabase database = await cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString());

            CosmosContainer container = await database.CreateContainerAsync(Guid.NewGuid().ToString(), "/id");

            string      id1      = Guid.NewGuid().ToString();
            TestPayload payload1 = await container.CreateItemAsync <TestPayload>(new TestPayload { id = id1 });

            payload1 = await container.ReadItemAsync <TestPayload>(new Cosmos.PartitionKey(id1), id1);
        }
        // </QueryItemsAsync>

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

            ItemResponse <Family> wakefieldFamilyResponse = await container.ReadItemAsync <Family>("Wakefield.7", new PartitionKey("Wakefield"));

            Family itemBody = wakefieldFamilyResponse;

            // update registration status from false to true
            itemBody.IsRegistered = true;
            // update grade of child
            itemBody.Children[0].Grade = 6;

            // replace the item with the updated content
            wakefieldFamilyResponse = await container.ReplaceItemAsync <Family>(itemBody, itemBody.Id, new PartitionKey(itemBody.LastName));

            Console.WriteLine("Updated Family [{0},{1}].\n \tBody is now: {2}\n", itemBody.LastName, itemBody.Id, wakefieldFamilyResponse.Value);
        }
예제 #15
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);
            }
        }
예제 #16
0
        public async Task <T> GetAsync(string entityId, string partionKey)
        {
            try
            {
                CosmosContainer container = GetContainer();

                ItemResponse <T> entityResult = await container.ReadItemAsync <T>(entityId, new PartitionKey(partionKey));

                return(entityResult.Value);
            }
            catch (CosmosException ex)
            {
                Log.Error($"Entity with ID: {entityId} was not retrieved successfully - error details: {ex.Message}");

                if (ex.ErrorCode != "404")
                {
                    throw;
                }
                return(null);
            }
        }
        public async Task <T> GetAsync(string entityId)
        {
            try
            {
                CosmosContainer container = GetContainer();

                ItemResponse <T> entityResult = await container.ReadItemAsync <T>(entityId, new PartitionKey(entityId));

                return(entityResult.Value);
            }
            catch (CosmosException ex)
            {
                _logger.LogError(ex.Message);

                if (ex.Status != (int)HttpStatusCode.NotFound)
                {
                    throw;
                }

                return(null);
            }
        }
예제 #18
0
        public async Task <RecipesClientResponse> GetRecipeAsync(string id)
        {
            RecipesClientResponse recipesClientResponse = new RecipesClientResponse();

            _logger.LogInformation("Reading items {0}", id);

            try
            {
                ItemResponse <Recipe> itemResponse = await _cosmosContainer.ReadItemAsync <Recipe>(id, new PartitionKey("recipe"));

                recipesClientResponse.recipe  = itemResponse.Value;
                recipesClientResponse.status  = HttpStatusCode.OK;
                recipesClientResponse.message = "Item found " + itemResponse.Value.id;
            }
            catch (CosmosException exception)
            {
                recipesClientResponse.status  = (HttpStatusCode)exception.Status;
                recipesClientResponse.message = exception.Message;
                _logger.LogInformation("Status: {0} - Message: {1}", exception.Status, exception.Message);
            }

            return(recipesClientResponse);
        }
예제 #19
0
        /// <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);
        }
        public async Task <TEntity> GetByIdAsync(string id, string partitionKey)
        {
            var itemResponse = await _cosmosContainer.ReadItemAsync <TEntity>(id, new PartitionKey(partitionKey));

            return(itemResponse?.Value);
        }
        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.");
            }
        }
예제 #22
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.");
            }
        }
예제 #23
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");
        }
        // </CreateContainerAsync>

        // <AddItemsToContainerAsync>
        /// <summary>
        /// Add Family items to the container
        /// </summary>
        private static async Task AddItemsToContainerAsync(CosmosClient cosmosClient)
        {
            // Create a family object for the Andersen family
            Family andersenFamily = new Family
            {
                Id       = "Andersen.1",
                LastName = "Andersen",
                Parents  = new Parent[]
                {
                    new Parent {
                        FirstName = "Thomas"
                    },
                    new Parent {
                        FirstName = "Mary Kay"
                    }
                },
                Children = new Child[]
                {
                    new Child
                    {
                        FirstName = "Henriette Thaulow",
                        Gender    = "female",
                        Grade     = 5,
                        Pets      = new Pet[]
                        {
                            new Pet {
                                GivenName = "Fluffy"
                            }
                        }
                    }
                },
                Address = new Address {
                    State = "WA", County = "King", City = "Seattle"
                },
                IsRegistered = false
            };

            CosmosContainer container = cosmosClient.GetContainer(Program.DatabaseId, Program.ContainerId);

            try
            {
                // Read the item to see if it exists.
                ItemResponse <Family> andersenFamilyResponse = await container.ReadItemAsync <Family>(andersenFamily.Id, new PartitionKey(andersenFamily.LastName));

                Console.WriteLine("Item in database with id: {0} already exists\n", andersenFamilyResponse.Value.Id);
            }
            catch (CosmosException ex) when(ex.Status == (int)HttpStatusCode.NotFound)
            {
                // Create an item in the container representing the Andersen family. Note we provide the value of the partition key for this item, which is "Andersen"
                ItemResponse <Family> andersenFamilyResponse = await container.CreateItemAsync <Family>(andersenFamily, new PartitionKey(andersenFamily.LastName));

                // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse.
                Console.WriteLine("Created item in database with id: {0}\n", andersenFamilyResponse.Value.Id);
            }

            // Create a family object for the Wakefield family
            Family wakefieldFamily = new Family
            {
                Id       = "Wakefield.7",
                LastName = "Wakefield",
                Parents  = new Parent[]
                {
                    new Parent {
                        FamilyName = "Wakefield", FirstName = "Robin"
                    },
                    new Parent {
                        FamilyName = "Miller", FirstName = "Ben"
                    }
                },
                Children = new Child[]
                {
                    new Child
                    {
                        FamilyName = "Merriam",
                        FirstName  = "Jesse",
                        Gender     = "female",
                        Grade      = 8,
                        Pets       = new Pet[]
                        {
                            new Pet {
                                GivenName = "Goofy"
                            },
                            new Pet {
                                GivenName = "Shadow"
                            }
                        }
                    },
                    new Child
                    {
                        FamilyName = "Miller",
                        FirstName  = "Lisa",
                        Gender     = "female",
                        Grade      = 1
                    }
                },
                Address = new Address {
                    State = "NY", County = "Manhattan", City = "NY"
                },
                IsRegistered = true
            };

            // Create an item in the container representing the Wakefield family. Note we provide the value of the partition key for this item, which is "Wakefield"
            ItemResponse <Family> wakefieldFamilyResponse = await container.UpsertItemAsync <Family>(wakefieldFamily, new PartitionKey(wakefieldFamily.LastName));

            // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request.
            Console.WriteLine("Created item in database with id: {0}\n", wakefieldFamilyResponse.Value.Id);
        }
        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);
        }
예제 #26
0
        public async Task  TestJsonSerializerSettings(bool useGateway)
        {
            CosmosClient cosmosClient = TestCommon.CreateCosmosClient((cosmosClientBuilder) => {
                if (useGateway)
                {
                    cosmosClientBuilder.WithCustomJsonSerializer(new CustomJsonSerializer(CustomSerializationTests.GetSerializerWithCustomConverterAndBinder())).WithConnectionModeGateway();
                }
                else
                {
                    cosmosClientBuilder.WithCustomJsonSerializer(new CustomJsonSerializer(CustomSerializationTests.GetSerializerWithCustomConverterAndBinder())).WithConnectionModeDirect();
                }
            });
            CosmosContainer container = cosmosClient.Databases[databaseName].Containers[partitionedCollectionName];

            var rnd   = new Random();
            var bytes = new byte[100];

            rnd.NextBytes(bytes);
            var testDocument = new TestDocument(new KerberosTicketHashKey(bytes));

            //create and read
            ItemResponse <TestDocument> createResponse = await container.CreateItemAsync <TestDocument>(testDocument.Name, testDocument);

            ItemResponse <TestDocument> readResponse = await container.ReadItemAsync <TestDocument>(testDocument.Name, testDocument.Id);

            AssertEqual(testDocument, readResponse.Resource);
            AssertEqual(testDocument, createResponse.Resource);

            // upsert
            ItemResponse <TestDocument> upsertResponse = await container.UpsertItemAsync <TestDocument>(testDocument.Name, testDocument);

            readResponse = await container.ReadItemAsync <TestDocument>(testDocument.Name, testDocument.Id);

            AssertEqual(testDocument, readResponse.Resource);
            AssertEqual(testDocument, upsertResponse.Resource);

            // replace
            ItemResponse <TestDocument> replacedResponse = await container.ReplaceItemAsync <TestDocument>(testDocument.Name, testDocument.Id, testDocument);

            readResponse = await container.ReadItemAsync <TestDocument>(testDocument.Name, testDocument.Id);

            AssertEqual(testDocument, readResponse.Resource);
            AssertEqual(testDocument, replacedResponse.Resource);

            CosmosSqlQueryDefinition    sql          = new CosmosSqlQueryDefinition("select * from r");
            FeedIterator <TestDocument> feedIterator =
                container.CreateItemQuery <TestDocument>(sqlQueryDefinition: sql, partitionKey: testDocument.Name, maxItemCount: 1);
            FeedResponse <TestDocument> queryResponse = await feedIterator.FetchNextSetAsync();

            AssertEqual(testDocument, queryResponse.First());

            //Will add LINQ test once it is available with new V3 OM
            // // LINQ Lambda
            // var query1 = client.CreateDocumentQuery<TestDocument>(partitionedCollectionUri, options)
            //            .Where(_ => _.Id.CompareTo(String.Empty) > 0)
            //            .Select(_ => _.Id);
            // string query1Str = query1.ToString();
            // var result = query1.ToList();
            // Assert.AreEqual(1, result.Count);
            // Assert.AreEqual(testDocument.Id, result[0]);

            // // LINQ Query
            // var query2 =
            //     from f in client.CreateDocumentQuery<TestDocument>(partitionedCollectionUri, options)
            //     where f.Id.CompareTo(String.Empty) > 0
            //     select f.Id;
            // string query2Str = query2.ToString();
            // var result2 = query2.ToList();
            // Assert.AreEqual(1, result2.Count);
            // Assert.AreEqual(testDocument.Id, result2[0]);
        }