示例#1
0
        public async Task AddNewItemToContainerAsync(Project project)
        {
            CosmosContainer container = await GetContainer();

            try
            {
                ItemResponse <Project> newProjecResponse = await container.CreateItemAsync <Project>(project, new PartitionKey(project.Name));

                //ItemResponse<Project> newProjecResponse = await container.ReadItemAsync<Project>(project.Id, new PartitionKey(project.Name));
            }
            catch (CosmosException ex) when(ex.Status == (int)HttpStatusCode.NotFound)
            {
                ItemResponse <Project> newProjecResponse = await container.CreateItemAsync <Project>(project, new PartitionKey(project.Name));
            }
        }
示例#2
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);
        }
示例#3
0
        public async Task ValidateCurrentWriteQuorumAndReplicaSetHeader()
        {
            CosmosClient   client = TestCommon.CreateCosmosClient(false);
            CosmosDatabase db     = null;

            try
            {
                db = await client.Databases.CreateDatabaseAsync(Guid.NewGuid().ToString());

                PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition {
                    Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/id" }), Kind = PartitionKind.Hash
                };
                CosmosContainerSettings containerSetting = new CosmosContainerSettings()
                {
                    Id           = Guid.NewGuid().ToString(),
                    PartitionKey = partitionKeyDefinition
                };
                CosmosContainer coll = await db.Containers.CreateContainerAsync(containerSetting);

                Document documentDefinition = new Document {
                    Id = Guid.NewGuid().ToString()
                };
                ItemResponse <Document> docResult = await coll.CreateItemAsync <Document>(documentDefinition.Id, documentDefinition);

                Assert.IsTrue(int.Parse(docResult.Headers[WFConstants.BackendHeaders.CurrentWriteQuorum], CultureInfo.InvariantCulture) > 0);
                Assert.IsTrue(int.Parse(docResult.Headers[WFConstants.BackendHeaders.CurrentReplicaSetSize], CultureInfo.InvariantCulture) > 0);
            }
            finally
            {
                await db.DeleteAsync();
            }
        }
示例#4
0
        public async Task <Guid> CreateAsync(T entity)
        {
            entity.Id = Guid.NewGuid();
            await _container.CreateItemAsync <T>(entity, new PartitionKey(entity.Id.ToString()));

            return(entity.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);
        }
        public async Task TimeToLiveTest()
        {
            string            containerName       = Guid.NewGuid().ToString();
            string            partitionKeyPath    = "/users";
            int               timeToLiveInSeconds = 10;
            ContainerResponse containerResponse   = await this.database.DefineContainer(containerName, partitionKeyPath)
                                                    .WithDefaultTimeToLive(timeToLiveInSeconds)
                                                    .CreateAsync();

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

            Assert.AreEqual(timeToLiveInSeconds, responseSettings.DefaultTimeToLive);

            ContainerResponse readResponse = await cosmosContainer.ReadAsync();

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

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

            JObject responseItem = createResponse;

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

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
示例#7
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);
        }
        public async Task ValidateQueryNotFoundResponse()
        {
            CosmosDatabase db = await CosmosNotFoundTests.client.CreateDatabaseAsync("NotFoundTest" + Guid.NewGuid().ToString());

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

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

            await container.DeleteAsync();

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

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

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

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

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

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

            await db.DeleteAsync();
        }
示例#9
0
        private static async Task <SalesOrder> CreateItemsAsync()
        {
            Console.WriteLine("\n1.1 - Creating items");

            // Create a SalesOrder object. This object has nested properties and various types including numbers, DateTimes and strings.
            // This can be saved as JSON as is without converting into rows/columns.
            SalesOrder salesOrder = GetSalesOrderSample("SalesOrder1");
            ItemResponse <SalesOrder> response = await container.CreateItemAsync(salesOrder, new PartitionKey(salesOrder.AccountNumber));

            SalesOrder salesOrder1 = response;

            Console.WriteLine($"\n1.1.1 - Item created {salesOrder1.Id}");

            // As your app evolves, let's say your object has a new schema. You can insert SalesOrderV2 objects without any
            // changes to the database tier.
            SalesOrder2 newSalesOrder            = GetSalesOrderV2Sample("SalesOrder2");
            ItemResponse <SalesOrder2> response2 = await container.CreateItemAsync(newSalesOrder, new PartitionKey(newSalesOrder.AccountNumber));

            SalesOrder2 salesOrder2 = response2;

            Console.WriteLine($"\n1.1.2 - Item created {salesOrder2.Id}");

            // For better performance create a SalesOrder object from a stream.
            SalesOrder salesOrderV3 = GetSalesOrderSample("SalesOrderV3");

            using (Stream stream = Program.ToStream <SalesOrder>(salesOrderV3))
            {
                using (CosmosResponseMessage responseMessage = await container.CreateItemStreamAsync(new PartitionKey(salesOrderV3.AccountNumber), stream))
                {
                    // Item stream operations do not throw exceptions for better performance
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        SalesOrder streamResponse = FromStream <SalesOrder>(responseMessage.Content);
                        Console.WriteLine($"\n1.1.2 - Item created {streamResponse.Id}");
                    }
                    else
                    {
                        Console.WriteLine($"Create item from stream failed. Status code: {responseMessage.StatusCode} Message: {responseMessage.ErrorMessage}");
                    }
                }
            }

            return(salesOrder);
        }
示例#10
0
        private async Task TestOrderyByQueryAsync()
        {
            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
                Converters          =
                {
                    new ObjectStringJsonConverter <SerializedObject>(_ => _.Name, _ => SerializedObject.Parse(_))
                }
            };

            CosmosClient    cosmosClient = TestCommon.CreateCosmosClient((cosmosClientBuilder) => cosmosClientBuilder.WithCustomJsonSerializer(new CustomJsonSerializer(jsonSerializerSettings)));
            CosmosContainer container    = cosmosClient.Databases[databaseName].Containers[partitionedCollectionName];

            // Create a few test documents
            int documentCount   = 3;
            var numberFieldName = "NumberField";

            for (int i = 0; i < documentCount; ++i)
            {
                var newDocument     = new MyObject(i);
                var createdDocument = await container.CreateItemAsync <MyObject>(newDocument.pk, newDocument);
            }

            CosmosSqlQueryDefinition cosmosSqlQueryDefinition1 = new CosmosSqlQueryDefinition("SELECT * FROM root");
            FeedIterator <MyObject>  setIterator1 = container.CreateItemQuery <MyObject>(cosmosSqlQueryDefinition1, maxConcurrency: -1, maxItemCount: -1);

            CosmosSqlQueryDefinition cosmosSqlQueryDefinition2 = new CosmosSqlQueryDefinition("SELECT * FROM root ORDER BY root[\"" + numberFieldName + "\"] DESC");
            FeedIterator <MyObject>  setIterator2 = container.CreateItemQuery <MyObject>(cosmosSqlQueryDefinition2, maxConcurrency: -1, maxItemCount: -1);

            List <MyObject> list1 = new List <MyObject>();
            List <MyObject> list2 = new List <MyObject>();

            while (setIterator1.HasMoreResults)
            {
                foreach (MyObject obj in await setIterator1.FetchNextSetAsync())
                {
                    list1.Add(obj);
                }
            }

            while (setIterator2.HasMoreResults)
            {
                foreach (MyObject obj in await setIterator2.FetchNextSetAsync())
                {
                    list2.Add(obj);
                }
            }

            Assert.AreEqual(documentCount, list1.Count);
            Assert.AreEqual(documentCount, list2.Count);
            for (int i = 0; i < documentCount; ++i)
            {
                Assert.AreEqual("Name: " + (documentCount - i - 1), list2[i].SerializedObject.Name);
            }
        }
示例#11
0
        public async Task <bool> AddStorageAsync(Storage storage)
        {
            var userId = GetUserId();

            var CreateStorageUserContainer = await UserContainer.CreateItemAsync <Storage>(storage, new PartitionKey(storage.UserId));

            var CreateStorageStorageContainer = await StorageContainer.CreateItemAsync <Storage>(storage, new PartitionKey(storage.StorageId));

            var CreateStorageLastVisitedAndModifiedContainer = await LastVisitedAndModifiedContainer.CreateItemAsync <Storage>(storage, new PartitionKey(storage.Type));

            return(true);
        }
示例#12
0
        /// <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);
                    }
                }
            }
        }
示例#13
0
        public async Task <PersonEntity> Add(PersonEntity PersonEntity)
        {
            ThrowIfDisposed();

            if (PersonEntity == null)
            {
                throw new ArgumentNullException(nameof(PersonEntity));
            }

            var response = await _cosmosContainer.CreateItemAsync(PersonEntity, new PartitionKey(PersonEntity.PartitionKey));

            return(response.Value);
        }
        public async Task <T> AddAsync(T newEntity)
        {
            try
            {
                CosmosContainer  container    = GetContainer();
                ItemResponse <T> itemResponse = await container.CreateItemAsync <T>(newEntity);

                return(itemResponse.Value);
            }catch (Exception ex)
            {
                Log.Error($"New entity with ID: {newEntity.Id} was not added successfully - error details: {ex.Message}");
                throw new Exception($"New entity with ID: {newEntity.Id} was not added successfully - error details: {ex.Message}");
            }
        }
        public static async Task <ItemResponse <T> > TryCreateItemAsync <T>(
            this CosmosContainer container,
            object partitionKey,
            T item)
        {
            var response = await container.CreateItemAsync <T>(partitionKey, item).ConfigureAwait(false);

            if (response.StatusCode == HttpStatusCode.Conflict)
            {
                // Ignore-- document already exists.
                return(null);
            }

            return(response);
        }
        public async Task TimeToLivePropertyPath()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/user";
            int    timeToLivetimeToLiveInSeconds = 10;

            ContainerResponse containerResponse = null;

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

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

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

            CosmosContainer cosmosContainer = containerResponse;

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

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

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

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

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
示例#17
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 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);
        }
        public async Task TimeToLiveTest()
        {
            string containerName            = Guid.NewGuid().ToString();
            string partitionKeyPath         = "/users";
            int    timeToLiveInSeconds      = 10;
            CosmosContainerSettings setting = new CosmosContainerSettings()
            {
                Id           = containerName,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string> {
                        partitionKeyPath
                    }, Kind = PartitionKind.Hash
                },
                DefaultTimeToLive = timeToLiveInSeconds,
            };

            ContainerResponse containerResponse = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(setting);

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

            Assert.AreEqual(timeToLiveInSeconds, responseSettings.DefaultTimeToLive);

            ContainerResponse readResponse = await cosmosContainer.ReadAsync();

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

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

            JObject responseItem = createResponse;

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

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
        public async Task <T> AddAsync(T newEntity)
        {
            try
            {
                CosmosContainer  container      = GetContainer();
                ItemResponse <T> createResponse = await container.CreateItemAsync(newEntity);

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

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

                return(null);
            }
        }
示例#21
0
        public async Task <T> AddAsync(T newEntity)
        {
            try
            {
                CosmosContainer  container      = GetContainer();
                ItemResponse <T> createResponse = await container.CreateItemAsync(newEntity);

                return(createResponse.Value);
            }
            catch (CosmosException ex)
            {
                Log.Error($"New entity with ID: {newEntity.Id} was not added successfully - error details: {ex.Message}");

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

                return(null);
            }
        }
        public async Task InsertCompetition(Competition competition)
        {
            if (competition == null)
            {
                throw new ArgumentNullException(nameof(competition));
            }

            try
            {
                var itemResponse = await _container
                                   .CreateItemAsync(competition, new PartitionKey(competition.Location.State));

                _logger.LogInformation($"Competition with id '{itemResponse.Value.Id}' and " +
                                       $"title '{itemResponse.Value.Title}' added successful");

                var isHaveHeaderRequestCharge = itemResponse
                                                .GetRawResponse()
                                                .Headers
                                                .TryGetValue("x-ms-request-charge", out var requestUnits);

                if (isHaveHeaderRequestCharge)
                {
                    _logger.LogInformation($"Charged request units: {requestUnits}");
                }
            }
            catch (CosmosException e) when(e.Response.Status == (int)HttpStatusCode.Conflict)
            {
                _logger.LogWarning($"Item with id '{competition.Id}' already exists!");

                var requestUnitHeader = GetRequestUnitHeader(e.Response.Headers);

                if (requestUnitHeader != null)
                {
                    _logger.LogWarning($"Charged request units: {requestUnitHeader}");
                }
            }
        }
示例#23
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);
        }
示例#24
0
        private async Task ValidateCollectionIndexProgressHeaders(CosmosClient client)
        {
            CosmosDatabase db = await client.Databases.CreateDatabaseAsync(Guid.NewGuid().ToString());

            try
            {
                PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition {
                    Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/id" }), Kind = PartitionKind.Hash
                };
                var lazyCollection = new CosmosContainerSettings()
                {
                    Id = Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition
                };
                lazyCollection.IndexingPolicy.IndexingMode = Cosmos.IndexingMode.Lazy;
                CosmosContainer lazyContainer = await db.Containers.CreateContainerAsync(lazyCollection);

                var consistentCollection = new CosmosContainerSettings()
                {
                    Id = Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition
                };
                consistentCollection.IndexingPolicy.IndexingMode = Cosmos.IndexingMode.Consistent;
                CosmosContainer consistentContainer = await db.Containers.CreateContainerAsync(consistentCollection);

                var noneIndexCollection = new CosmosContainerSettings()
                {
                    Id = Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition
                };
                noneIndexCollection.IndexingPolicy.Automatic    = false;
                noneIndexCollection.IndexingPolicy.IndexingMode = Cosmos.IndexingMode.None;
                CosmosContainer noneIndexContainer = await db.Containers.CreateContainerAsync(noneIndexCollection);

                var doc = new Document()
                {
                    Id = Guid.NewGuid().ToString()
                };
                await lazyContainer.CreateItemAsync <Document>(doc.Id, doc);

                await consistentContainer.CreateItemAsync <Document>(doc.Id, doc);

                await noneIndexContainer.CreateItemAsync <Document>(doc.Id, doc);


                // Lazy-indexing collection.
                {
                    ContainerResponse collectionResponse = await lazyContainer.ReadAsync(requestOptions : new ContainerRequestOptions {
                        PopulateQuotaInfo = true
                    });

                    Assert.IsTrue(int.Parse(collectionResponse.Headers[HttpConstants.HttpHeaders.CollectionLazyIndexingProgress], CultureInfo.InvariantCulture) >= 0,
                                  "Expect lazy indexer progress when reading lazy collection.");
                    Assert.AreEqual(100, int.Parse(collectionResponse.Headers[HttpConstants.HttpHeaders.CollectionIndexTransformationProgress], CultureInfo.InvariantCulture),
                                    "Expect reindexer progress when reading lazy collection.");
                }

                // Consistent-indexing collection.
                {
                    ContainerResponse collectionResponse = await consistentContainer.ReadAsync(requestOptions : new ContainerRequestOptions {
                        PopulateQuotaInfo = true
                    });

                    Assert.IsFalse(collectionResponse.Headers.AllKeys().Contains(HttpConstants.HttpHeaders.CollectionLazyIndexingProgress),
                                   "No lazy indexer progress when reading consistent collection.");
                    Assert.AreEqual(100, int.Parse(collectionResponse.Headers[HttpConstants.HttpHeaders.CollectionIndexTransformationProgress], CultureInfo.InvariantCulture),
                                    "Expect reindexer progress when reading consistent collection.");
                }

                // None-indexing collection.
                {
                    ContainerResponse collectionResponse = await noneIndexContainer.ReadAsync(requestOptions : new ContainerRequestOptions {
                        PopulateQuotaInfo = true
                    });

                    Assert.IsFalse(collectionResponse.Headers.AllKeys().Contains(HttpConstants.HttpHeaders.CollectionLazyIndexingProgress),
                                   "No lazy indexer progress when reading none-index collection.");
                    Assert.AreEqual(100, int.Parse(collectionResponse.Headers[HttpConstants.HttpHeaders.CollectionIndexTransformationProgress], CultureInfo.InvariantCulture),
                                    "Expect reindexer progress when reading none-index collection.");
                }
            }
            finally
            {
                await db.DeleteAsync();
            }
        }
示例#25
0
 public async Task AddTestDataAsync(TestData item)
 {
     await _container.CreateItemAsync(item, new PartitionKey(item.Id));
 }
示例#26
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.");
            }
        }
示例#27
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 AddAsync(TEntity entity, PartitionKey partitionKey)
        {
            var itemResponse = await _container.CreateItemAsync <TEntity>(entity, partitionKey);

            entity.Id = itemResponse.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);
        }