Exemple #1
0
        public async Task OneTimeSetUp()
        {
            var connectionStringEnvironmentVariableName = "CosmosDBPersistence_ConnectionString";
            var connectionString = GetEnvironmentVariable(connectionStringEnvironmentVariableName,
                                                          fallbackEmulatorConnectionString: "AccountEndpoint = https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");

            ContainerName = $"{DateTime.UtcNow.Ticks}_{Path.GetFileNameWithoutExtension(Path.GetTempFileName())}";

            var builder = new CosmosClientBuilder(connectionString);

            builder.AddCustomHandlers(new LoggingHandler(), new TransactionalBatchCounterHandler());

            CosmosDbClient = builder.Build();

            var installer = new Installer(new CosmosClientProvidedByConfiguration
            {
                Client = CosmosDbClient
            }, new InstallerSettings
            {
                ContainerName    = ContainerName,
                DatabaseName     = DatabaseName,
                Disabled         = false,
                PartitionKeyPath = PartitionPathKey
            });

            await installer.Install("");

            var database = CosmosDbClient.GetDatabase(DatabaseName);

            Container = database.GetContainer(ContainerName);
        }
Exemple #2
0
        public async Task ReadManyExceptionsTest(HttpStatusCode statusCode)
        {
            RequestHandler[] requestHandlers = new RequestHandler[1];
            requestHandlers[0] = new CustomHandler(statusCode);

            CosmosClientBuilder builder = TestCommon.GetDefaultConfiguration();

            builder.AddCustomHandlers(requestHandlers);
            CosmosClient client   = builder.Build();
            Database     database = await client.CreateDatabaseAsync(Guid.NewGuid().ToString());

            Container container = await database.CreateContainerAsync(Guid.NewGuid().ToString(), "/pk");

            for (int i = 0; i < 5; i++)
            {
                await container.CreateItemAsync(
                    ToDoActivity.CreateRandomToDoActivity("pk" + i, i.ToString()));
            }

            List <(string, PartitionKey)> itemList = new List <(string, PartitionKey)>();

            for (int i = 0; i < 5; i++)
            {
                itemList.Add(("IncorrectId" + i, new PartitionKey("pk" + i))); // wrong ids
            }

            using (ResponseMessage responseMessage = await container.ReadManyItemsStreamAsync(itemList))
            {
                Assert.AreEqual(responseMessage.StatusCode, statusCode);
            }

            try
            {
                await container.ReadManyItemsAsync <ToDoActivity>(itemList);

                Assert.Fail("Typed API should throw");
            }
            catch (CosmosException ex)
            {
                Assert.AreEqual(ex.StatusCode, statusCode);
            }

            await database.DeleteAsync();

            client.Dispose();
        }
        public async Task QueryActivityIdTests()
        {
            RequestHandler[] requestHandlers = new RequestHandler[1];
            requestHandlers[0] = new CustomHandler();

            CosmosClientBuilder builder = TestCommon.GetDefaultConfiguration();

            builder.AddCustomHandlers(requestHandlers);

            CosmosClient cosmosClient = builder.Build();
            Database     database     = await cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString());

            Container container = await database.CreateContainerAsync(Guid.NewGuid().ToString(),
                                                                      "/pk",
                                                                      throughput : 12000);

            // Create items
            for (int i = 0; i < 500; i++)
            {
                await container.CreateItemAsync <ToDoActivity>(ToDoActivity.CreateRandomToDoActivity());
            }

            QueryRequestOptions queryRequestOptions = new QueryRequestOptions
            {
                MaxItemCount = 50
            };

            FeedIterator <ToDoActivity> feedIterator = container.GetItemQueryIterator <ToDoActivity>(
                "select * from c",
                null,
                queryRequestOptions);

            while (feedIterator.HasMoreResults)
            {
                await feedIterator.ReadNextAsync();
            }

            await database.DeleteAsync();

            cosmosClient.Dispose();
        }
        // Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute
        // <Main>
        public static async Task Main(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .AddJsonFile("appSettings.json")
                                               .Build();

            string endpoint = configuration["EndPointUrl"];

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

            string authKey = configuration["AuthorizationKey"];

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

            // Connecting to Emulator. Change if you want a live account
            CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(endpoint, authKey);

            // Declare a JSON schema to use with the schema validation handler
            var myContainerSchema = JSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type': 'string'}
  },
  'required': ['name']
}");

            cosmosClientBuilder.AddCustomHandlers(
                new LoggingHandler(),
                new ConcurrencyHandler(),
                new ThrottlingHandler(),
                new SchemaValidationHandler((database: "mydb", container: "mycoll2", schema: myContainerSchema))
                );

            CosmosClient client = cosmosClientBuilder.Build();

            DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("mydb");

            Database database = databaseResponse.Database;

            ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll", "/id");

            Container container = containerResponse.Container;

            Item item = new Item()
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = "Test Item",
                Description = "Some random test item",
                Completed   = false
            };

            // Create
            await container.CreateItemAsync <Item>(item, new PartitionKey(item.Id));

            item.Completed = true;

            // Replace
            await container.ReplaceItemAsync <Item>(item, item.Id, new PartitionKey(item.Id));

            // Querying
            List <Item> results = new List <Item>();

            using (FeedIterator <Item> query = container.GetItemQueryIterator <Item>(new QueryDefinition("SELECT * FROM c"), requestOptions: new QueryRequestOptions()
            {
                MaxConcurrency = 1
            }))
            {
                while (query.HasMoreResults)
                {
                    FeedResponse <Item> response = await query.ReadNextAsync();

                    results.AddRange(response.ToList());
                }
            }

            // Read Item

            ItemResponse <Item> cosmosItemResponse = await container.ReadItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            ItemRequestOptions itemRequestOptions = new ItemRequestOptions()
            {
                IfMatchEtag = cosmosItemResponse.ETag
            };

            // Concurrency

            List <Task <ItemResponse <Item> > > tasks = new List <Task <ItemResponse <Item> > >
            {
                UpdateItemForConcurrency(container, itemRequestOptions, item),
                UpdateItemForConcurrency(container, itemRequestOptions, item)
            };

            try
            {
                await Task.WhenAll(tasks);
            }
            catch (CosmosException ex)
            {
                // Verify that our custom handler caught the scenario
                Debug.Assert(999.Equals(ex.SubStatusCode));
            }

            // Delete
            await container.DeleteItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            // Schema validation

            containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll2", "/id");

            container = containerResponse.Container;

            // Insert an item with invalid schema
            var writeSucceeded = true;

            try
            {
                await container.CreateItemAsync(new { id = "12345" });
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(!writeSucceeded);

            // Insert an item with valid schema
            try
            {
                await container.CreateItemAsync(new { id = "12345", name = "Youri" });

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(writeSucceeded);

            // Update an item with invalid schema
            try
            {
                await container.ReplaceItemAsync(new { id = "12345" }, "12345");

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(!writeSucceeded);

            // Update an item with valid schema
            try
            {
                await container.ReplaceItemAsync(new { id = "12345", name = "Vladimir" }, "12345");

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(writeSucceeded);
        }
        // Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute
        // <Main>
        public static async Task Main(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .AddJsonFile("appSettings.json")
                                               .Build();

            string endpoint = configuration["EndPointUrl"];

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

            string authKey = configuration["AuthorizationKey"];

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

            // Connecting to Emulator. Change if you want a live account
            CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(endpoint, authKey);

            cosmosClientBuilder.AddCustomHandlers(
                new LoggingHandler(),
                new ConcurrencyHandler(),
                new ThrottlingHandler()
                );

            CosmosClient client = cosmosClientBuilder.Build();

            DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("mydb");

            Database database = databaseResponse.Database;

            ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll", "/id");

            Container container = containerResponse.Container;

            Item item = new Item()
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = "Test Item",
                Description = "Some random test item",
                Completed   = false
            };

            // Create
            await container.CreateItemAsync <Item>(item, new PartitionKey(item.Id));

            item.Completed = true;

            // Replace
            await container.ReplaceItemAsync <Item>(item, item.Id, new PartitionKey(item.Id));

            // Querying
            FeedIterator <Item> query = container.GetItemQueryIterator <Item>(new QueryDefinition("SELECT * FROM c"), requestOptions: new QueryRequestOptions()
            {
                MaxConcurrency = 1
            });
            List <Item> results = new List <Item>();

            while (query.HasMoreResults)
            {
                FeedResponse <Item> response = await query.ReadNextAsync();

                results.AddRange(response.ToList());
            }

            // Read Item

            ItemResponse <Item> cosmosItemResponse = await container.ReadItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            ItemRequestOptions itemRequestOptions = new ItemRequestOptions()
            {
                IfMatchEtag = cosmosItemResponse.ETag
            };

            // Concurrency

            List <Task <ItemResponse <Item> > > tasks = new List <Task <ItemResponse <Item> > >
            {
                UpdateItemForConcurrency(container, itemRequestOptions, item),
                UpdateItemForConcurrency(container, itemRequestOptions, item)
            };

            try
            {
                await Task.WhenAll(tasks);
            }
            catch (CosmosException ex)
            {
                // Verify that our custom handler caught the scenario
                Debug.Assert(999.Equals(ex.SubStatusCode));
            }

            // Delete
            await container.DeleteItemAsync <Item>(item.Id, new PartitionKey(item.Id));
        }