Ejemplo n.º 1
0
        public async Task <IActionResult> Create(Products products)
        {
            var          url      = "";
            var          db       = "Ecommerce";
            var          key      = "";
            CosmosClient client   = new CosmosClient(url, key);
            Database     database = await client.CreateDatabaseIfNotExistsAsync(db);

            Container containers = await database.CreateContainerIfNotExistsAsync("Product", "/ProductId");

            var response = await containers.CreateItemAsync <Products>(products);

            return(View());
        }
Ejemplo n.º 2
0
        private static async Task CreateItem()
        {
            var cosmosUrl    = "https://adrian-cosmos-db.documents.azure.com:443/";
            var cosmoskey    = "KHFyiaZ9N9NlxfsqF1mrXGWddce23pUQL9Ms9w1rJKPNVDtzpOpfGrFXyi3r2UwV0cLqaevxuQxHTS9dmdyd8w==";
            var databaseName = "DemoDB";

            CosmosClient client   = new CosmosClient(cosmosUrl, cosmoskey);
            Database     database = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            Container container = await database.CreateContainerIfNotExistsAsync("MyContainerName", "/partitionKeyPath", 400);

            dynamic testItem = new { id = Guid.NewGuid().ToString(), PartitionKey = "MyTestPkValue", details = "its working" };
            var     response = await container.CreateItemAsync(testItem);
        }
Ejemplo n.º 3
0
        private static async Task <Container> GetContainer()
        {
            string endpointUrl = Environment.GetEnvironmentVariable("EndpointUrl"); //ConfigurationManager.AppSettings["EndpointUrl"];
            string primaryKey  = Environment.GetEnvironmentVariable("PrimaryKey");  //ConfigurationManager.AppSettings["PrimaryKey"];
            string databaseId  = Environment.GetEnvironmentVariable("DatabaseId");  //ConfigurationManager.AppSettings["DatabaseId"];
            string containerId = Environment.GetEnvironmentVariable("ContainerId"); //ConfigurationManager.AppSettings["ContainerId"];

            _cosmosClient = new CosmosClient(endpointUrl, primaryKey);
            Database database = await _cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);

            Container container = await database.CreateContainerIfNotExistsAsync(containerId, partitionKeyPath);

            return(container);
        }
Ejemplo n.º 4
0
        private static async Task <CosmosDbService> InitializeCosmosClientInstanceAsync(IConfigurationSection configurationSection)
        {
            string           databaseName    = configurationSection.GetSection("DatabaseName").Value;
            string           containerName   = configurationSection.GetSection("ContainerName").Value;
            string           account         = configurationSection.GetSection("Account").Value;
            string           key             = configurationSection.GetSection("Key").Value;
            CosmosClient     client          = new CosmosClient(account, key);
            CosmosDbService  cosmosDbService = new CosmosDbService(client, databaseName, containerName);
            DatabaseResponse database        = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            await database.Database.CreateContainerIfNotExistsAsync(containerName, "/type");

            return(cosmosDbService);
        }
Ejemplo n.º 5
0
        // </Main>

        private static async Task InitializeAsync(CosmosClient client)
        {
            Program.database = await client.CreateDatabaseIfNotExistsAsync(Program.databaseId);

            // Delete the existing container to prevent create item conflicts.
            using (await Program.database.GetContainer(Program.containerId).DeleteContainerStreamAsync())
            { }

            Console.WriteLine("The demo will create a 1000 RU/s container, press any key to continue.");
            Console.ReadKey();

            // Create a container with a throughput of 1000 RU/s.
            await Program.database.DefineContainer(Program.containerId, "/GameId").CreateAsync(1000);
        }
Ejemplo n.º 6
0
        public static async Task <CosmosDbService <CitizenAccount> > InitializeCitizenAccountCosmosClientAsync(IConfigurationSection configurationSection, CosmosClient cosmosClient)
        {
            string databaseName  = configurationSection.GetSection("DatabaseName").Value;
            string containerName = configurationSection.GetSection("CitizenAccountContainerName").Value;

            CosmosDbService <CitizenAccount> cosmosDbService = new CosmosDbService <CitizenAccount>(cosmosClient, databaseName, containerName);
            DatabaseResponse database = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseName);

            await database.Database.CreateContainerIfNotExistsAsync(containerName, "/publicAddress");

            //InitializeCitizenAccountData(cosmosDbService);

            return(cosmosDbService);
        }
Ejemplo n.º 7
0
        private async Task <Database> CreateDatabase(CosmosClient client)
        {
            try
            {
                var dbResponse = await client.CreateDatabaseIfNotExistsAsync(Descriptor.DatabaseId);

                return(dbResponse.Database);
            }
            catch (Exception e)
            {
                Logger?.WriteError(e, System.Reflection.MethodBase.GetCurrentMethod().Name);
                throw;
            }
        }
Ejemplo n.º 8
0
        private async Task <Database> EnsureDatabaseAndCollectionsCreated(IConfiguration configuration)
        {
            var dbName     = configuration.GetValue <string>("CosmosDb:Database");
            var dbResponse = await _cosmosClient.CreateDatabaseIfNotExistsAsync(dbName);

            var db = dbResponse.Database;
            await db.CreateContainerIfNotExistsAsync(new ContainerProperties(DishRepository.CONTAINER, $"/{nameof(Dish.PartitionKey).ToCamelCase()}"));

            await db.CreateContainerIfNotExistsAsync(new ContainerProperties(DinnerRepository.CONTAINER, $"/{nameof(Dinner.PartitionKey).ToCamelCase()}"));

            await db.CreateContainerIfNotExistsAsync(new ContainerProperties(FamilyRepository.CONTAINER, $"/{nameof(Family.PartitionKey).ToCamelCase()}"));

            return(db);
        }
        private async Task <CosmosDatabase> ConnectToDatabase(string databaseId, int databaseThroughput)
        {
            if (string.IsNullOrWhiteSpace(databaseId))
            {
                throw new ApplicationException($"{nameof(databaseId)} can't be null or empty");
            }

            var databaseResponse = await _client
                                   .CreateDatabaseIfNotExistsAsync(databaseId, databaseThroughput);

            _logger.LogInformation($"Connected to container with id {databaseId}");

            return(databaseResponse.Database);
        }
Ejemplo n.º 10
0
        public async Task CreateIfNotExists()
        {
            RequestChargeHandlerHelper requestChargeHandler = new RequestChargeHandlerHelper();
            RequestHandlerHelper       requestHandlerHelper = new RequestHandlerHelper();

            CosmosClient client = TestCommon.CreateCosmosClient(x => x.AddCustomHandlers(requestChargeHandler, requestHandlerHelper));

            // Create a new database
            requestChargeHandler.TotalRequestCharges = 0;
            DatabaseResponse createResponse = await client.CreateDatabaseIfNotExistsAsync(Guid.NewGuid().ToString());

            Assert.AreEqual(requestChargeHandler.TotalRequestCharges, createResponse.RequestCharge);
            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            requestChargeHandler.TotalRequestCharges = 0;
            DatabaseResponse createExistingResponse = await client.CreateDatabaseIfNotExistsAsync(createResponse.Resource.Id);

            Assert.AreEqual(HttpStatusCode.OK, createExistingResponse.StatusCode);
            Assert.AreEqual(requestChargeHandler.TotalRequestCharges, createExistingResponse.RequestCharge);
            Assert.IsNotNull(createExistingResponse.Diagnostics);
            string diagnostics = createExistingResponse.Diagnostics.ToString();

            Assert.IsFalse(string.IsNullOrEmpty(diagnostics));
            Assert.IsTrue(diagnostics.Contains("StartUtc"));

            bool conflictReturned = false;

            requestHandlerHelper.CallBackOnResponse = (request, response) =>
            {
                if (request.OperationType == Documents.OperationType.Create &&
                    request.ResourceType == Documents.ResourceType.Database)
                {
                    conflictReturned = true;
                    // Simulate a race condition which results in a 409
                    return(CosmosExceptionFactory.Create(
                               statusCode: HttpStatusCode.Conflict,
                               subStatusCode: default,
Ejemplo n.º 11
0
        // </Main>

        /// <summary>
        /// Run basic database meta data operations as a console application.
        /// </summary>
        /// <returns></returns>
        // <RunDatabaseDemo>
        private static async Task RunDatabaseDemo(CosmosClient client)
        {
            // An object containing relevant information about the response
            DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync(databaseId, 10000);

            // A client side reference object that allows additional operations like ReadAsync
            Database database = databaseResponse;

            // The response from Azure Cosmos
            DatabaseProperties properties = databaseResponse;

            Console.WriteLine($"\n1. Create a database resource with id: {properties.Id} and last modified time stamp: {properties.LastModified}");
            Console.WriteLine($"\n2. Create a database resource request charge: {databaseResponse.RequestCharge} and Activity Id: {databaseResponse.ActivityId}");

            // Read the database from Azure Cosmos
            DatabaseResponse readResponse = await database.ReadAsync();

            Console.WriteLine($"\n3. Read a database: {readResponse.Resource.Id}");

            await readResponse.Database.CreateContainerAsync("testContainer", "/pk");

            // Get the current throughput for the database
            int?throughputResponse = await database.ReadThroughputAsync();

            if (throughputResponse.HasValue)
            {
                Console.WriteLine($"\n4. Read a database throughput: {throughputResponse}");

                // Update the current throughput for the database
                await database.ReplaceThroughputAsync(11000);
            }

            Console.WriteLine("\n5. Reading all databases resources for an account");
            using (FeedIterator <DatabaseProperties> iterator = client.GetDatabaseQueryIterator <DatabaseProperties>())
            {
                while (iterator.HasMoreResults)
                {
                    foreach (DatabaseProperties db in await iterator.ReadNextAsync())
                    {
                        Console.WriteLine(db.Id);
                    }
                }
            }

            // Delete the database from Azure Cosmos.
            await database.DeleteAsync();

            Console.WriteLine($"\n6. Database {database.Id} deleted.");
        }
        public static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine("Begin Cosmosdb SQL Api Quickstart...\n");

                // Create a new instance of the Cosmos Client
                cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);

                // Create a new database
                database = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);

                Console.WriteLine("Created Database: {0}\n", database.Id);

                // Create a new container with partition key
                container = await database.CreateContainerIfNotExistsAsync(containerId, "/LastName");

                Console.WriteLine("Created Container: {0}\n", container.Id);

                //Insert
                await AddItemsToContainerAsync();

                //Query
                await QueryItemsAsync();

                //Update
                await ReplaceFamilyItemAsync();

                //Delete
                await DeleteFamilyItemAsync();

                //Delete Database
                await DeleteDatabaseAndCleanupAsync();
            }
            catch (CosmosException de)
            {
                Exception baseException = de.GetBaseException();
                Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
            }
            finally
            {
                Console.WriteLine("End of demo, press any key to exit.");
                Console.ReadKey();
            }
        }
Ejemplo n.º 13
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            CosmosClient cosmosClient = new CosmosClient(EndpointUrl, AuthorizationKey, new CosmosClientOptions()
            {
                AllowBulkExecution = true
            });
            Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(Program.DatabaseName);

            await database.DefineContainer(Program.ContainerName, "/pk")
            .WithIndexingPolicy()
            .WithIndexingMode(IndexingMode.Consistent)
            .WithIncludedPaths()
            .Attach()
            .WithExcludedPaths()
            .Path("/*")
            .Attach()
            .Attach().CreateAsync(50000);

            Dictionary <PartitionKey, Stream> itemsToInsert = new Dictionary <PartitionKey, Stream>(ItemsToInsert);

            foreach (Item item in GetItemsToInsert())
            {
                MemoryStream stream = new MemoryStream();
                await JsonSerializer.SerializeAsync(stream, item);

                itemsToInsert.Add(new PartitionKey(item.pk), stream);
            }
            Container   container = database.GetContainer(ContainerName);
            List <Task> tasks     = new List <Task>(ItemsToInsert);

            foreach (KeyValuePair <PartitionKey, Stream> item in itemsToInsert)
            {
                tasks.Add(container.CreateItemStreamAsync(item.Value, item.Key).ContinueWith(
                              task =>
                {
                    using ResponseMessage response = task.Result;
                    if (!response.IsSuccessStatusCode)
                    {
                        Console.WriteLine($"Received {response.StatusCode} ({response.ErrorMessage}) status codefor operation {response.RequestMessage.RequestUri}.");
                    }
                }));
            }
            // Wait until all are done
            await Task.WhenAll(tasks);

            Console.WriteLine("Bye World!");
            Console.ReadLine();
        }
Ejemplo n.º 14
0
        private static async Task generateData()
        {
            //Reading configuration
            string connectionString = Environment.GetEnvironmentVariable("connectionString");
            string dbName           = Environment.GetEnvironmentVariable("database");
            string cnName           = Environment.GetEnvironmentVariable("container");

            long.TryParse(Environment.GetEnvironmentVariable("numberOfDocumentsToGenerate"), out long noOfDocs);

            long.TryParse(Environment.GetEnvironmentVariable("perDocRUs"), out long perDocRUs);
            int.TryParse(Environment.GetEnvironmentVariable("maxRUs"), out int maxRUs);

            //long totalRURequired = Math.Abs(noOfDocs * perDocRUs);
            long numberOfDocsPerBatch = Math.Abs(Math.Abs(Convert.ToInt64(maxRUs * 0.90)) / perDocRUs);
            long batchSize            = Math.Abs(noOfDocs / numberOfDocsPerBatch);

            CosmosClientBuilder cosmosClientBuilder =
                new CosmosClientBuilder(connectionString)
                .WithConnectionModeDirect()

                .WithBulkExecution(true);

            cosmosClient = cosmosClientBuilder.Build();

            Database db = await cosmosClient.CreateDatabaseIfNotExistsAsync(dbName);

            Container cn = await db.CreateContainerIfNotExistsAsync(cnName, "/id", maxRUs);

            List <List <Task> > tasks = new List <List <Task> >();

            for (int j = 0; j < batchSize; j++)
            {
                tasks.Add(CreateCustomer(numberOfDocsPerBatch, cn, j));
            }

            Stopwatch sw = new Stopwatch();

            for (int j = 0; j < tasks.Count; j++)
            {
                sw.Restart();
                await Task.WhenAll(tasks[j]);

                sw.Stop();
                Console.WriteLine("It took = " + sw.ElapsedMilliseconds / 1000 + "ms to insert " + tasks[j].Count + " records ");

                Thread.Sleep(sw.Elapsed);
                sw.Reset();
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Gewährleistet, dass die Azure Cosmos Datenbank und Container vorhanden sind,
        /// dann initialisiert ein Client für den Datenbankdienst.
        /// </summary>
        /// <param name="databaseName">Der Name der Datenbank.</param>
        /// <param name="connectionString">The Verbindungszeichenfolge für die Datenbank.</param>
        /// <param name="idGenerator">Implementierung für die Beschafung einer einzigartigen ID.</param>
        /// <returns>Eine erstellte Instanz von <see cref="CosmosDbService{ItemType}"/></returns>
        public static async Task <CosmosDbService <ItemType> > InitializeCosmosClientInstanceAsync(
            string databaseName,
            string connectionString,
            Utils.UidGenerator <ItemType> idGenerator)
        {
            var client  = new CosmosClient(connectionString);
            var service = new CosmosDbService <ItemType>(client, databaseName, idGenerator);
            DatabaseResponse response = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            await response.Database.CreateContainerIfNotExistsAsync(
                DataModels.CosmosDbPartitionedItem <ItemType> .ContainerName,
                DataModels.CosmosDbPartitionedItem <ItemType> .PartitionKeyPath);

            return(service);
        }
Ejemplo n.º 16
0
        private async Task <Container> GetContainer()
        {
            var databaseResponse = await _client.CreateDatabaseIfNotExistsAsync(DatabaseId);

            databaseResponse.EnsureSuccess();

            var database            = databaseResponse.Database;
            var containerProperties = new ContainerProperties(ContainerId, partitionKeyPath: "/id");

            var containerResponse = await database.CreateContainerIfNotExistsAsync(
                containerProperties,
                throughput : 1000);

            return(containerResponse.Container);
        }
Ejemplo n.º 17
0
        private async Task InitAsync()
        {
            if (CosmosClient == null || Database == null || Containers == null || Containers.Count == 0)
            {
                CosmosClient = new CosmosClient(Endpoint, PrimaryKey);
                Database     = await CosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseId);

                foreach (KeyValuePair <string, string> entry in ContainerData)
                {
                    Container c = await Database.CreateContainerIfNotExistsAsync(new ContainerProperties(entry.Key, entry.Value));

                    Containers.Add(entry.Key, c);
                }
            }
        }
Ejemplo n.º 18
0
        public async Task <bool> CreateDatabase()
        {
            string           message    = "Create Database";
            DatabaseResponse dbResponse = await _cosmosClient.CreateDatabaseIfNotExistsAsync(_databaseId, 400);

            if (dbResponse.StatusCode == System.Net.HttpStatusCode.Created)
            {
                Printer.PrintLine(message: message);
                WriteLine($"Database: '{_databaseId}', Created Successfully");
                _database = _cosmosClient.GetDatabase(_databaseId);
                Printer.PrintLine(noOfTimes: (100 + message.Length));
                return(true);
            }
            return(false);
        }
Ejemplo n.º 19
0
        public static async Task CreateDatabaseIfNotExistsAsync(CosmosClient client, ICosmosContainerOptions options)
        {
            DatabaseResponse databaseCreationResponse;

            if (options.ProvisionOnDatabaseLevel)
            {
                databaseCreationResponse = await client.CreateDatabaseIfNotExistsAsync(options.DatabaseId, options.RequestUnits);
            }
            else
            {
                databaseCreationResponse = await client.CreateDatabaseIfNotExistsAsync(options.DatabaseId);
            }

            if (databaseCreationResponse.StatusCode == System.Net.HttpStatusCode.Accepted ||
                databaseCreationResponse.StatusCode == System.Net.HttpStatusCode.OK ||
                databaseCreationResponse.StatusCode == System.Net.HttpStatusCode.Created)
            {
                await CreateContainerIfNotExistsAsync(client, options);
            }
            else
            {
                throw new NotSupportedException($"Database '{options.DatabaseId}' cannot be created. Wrong Url or Key? ({databaseCreationResponse.StatusCode})");
            }
        }
Ejemplo n.º 20
0
        private async Task Initialize()
        {
            var response = await CosmosClient.CreateDatabaseIfNotExistsAsync(
                Configuration[COSMOS_DATABASE]
                );

            if ((response.StatusCode == HttpStatusCode.Created) ||
                (response.StatusCode == HttpStatusCode.OK))
            {
                await response.Database.CreateContainerIfNotExistsAsync(
                    Configuration[COSMOS_CONTAINER],
                    "/PartitionKey"
                    );
            }
        }
Ejemplo n.º 21
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _provider.GetRequiredService <IConfiguration>();
            using var scoped = _provider.CreateScope();
            var configuration = scoped.ServiceProvider.GetRequiredService <CosmosConfiguration>();
            var cosmosClient  = new CosmosClient(configuration.AccountEndpoint, configuration.AccountKey);
            var db            = await cosmosClient.CreateDatabaseIfNotExistsAsync(configuration.DatabaseId,
                                                                                  cancellationToken : cancellationToken);

            await db.Database.CreateContainerIfNotExistsAsync(configuration.ContainerId, configuration.PartitionKey,
                                                              cancellationToken : cancellationToken);

            ContainerProperties containerProperties = new(configuration.LeasesId, "/id");
            await db.Database.CreateContainerIfNotExistsAsync(containerProperties, cancellationToken : cancellationToken);
        }
        /// <summary>
        /// Gets or creates the database as an asynchronous operation.
        /// </summary>
        /// <param name="client">The Cosmos client to use to get the database.</param>
        /// <param name="cancellationToken">The cancellation token to use.</param>
        /// <returns>
        /// A <see cref="Task{Database}"/> representing the asynchronous operation to get the database.
        /// </returns>
        private async Task <Database> GetOrCreateDatabaseAsync(CosmosClient client, CancellationToken cancellationToken)
        {
            var response = await client.CreateDatabaseIfNotExistsAsync(
                _databaseName,
                cancellationToken : cancellationToken);

            bool created = response.StatusCode == HttpStatusCode.Created;

            if (created)
            {
                _logger.LogInformation("Created database {DatabaseName}.", _databaseName);
            }

            return(response.Database);
        }
Ejemplo n.º 23
0
        private static async Task <CosmosDBService> InitializeCosmosClientInstanceAsync(CosmosDb settings)
        {
            databaseName  = settings.DatabaseName;
            containerName = settings.ContainerName;
            account       = settings.Account;
            key           = settings.Key;

            CosmosClient     client          = new CosmosClient(account, key);
            CosmosDBService  cosmosDBService = new CosmosDBService(client, databaseName, containerName);
            DatabaseResponse database        = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            await database.Database.CreateContainerIfNotExistsAsync(containerName, "/__partitionKey");

            return(cosmosDBService);
        }
        public DataController()
        {
            string endpointUrl      = ConfigurationManager.AppSettings["dbConnectionUrl"];
            string authorizationKey = ConfigurationManager.AppSettings["dbConnectionKey"];

            databaseId = ConfigurationManager.AppSettings["databaseId"];

            CosmosClientOptions options = new CosmosClientOptions();

            options.ConnectionMode = ConnectionMode.Gateway;

            client = new CosmosClient(endpointUrl, authorizationKey, options);

            database = client.CreateDatabaseIfNotExistsAsync(databaseId).Result;
        }
Ejemplo n.º 25
0
        private async Task CreateDatabaseIfNotExistsAsync()
        {
            try
            {
                Database cosmosDatabase = await client.CreateDatabaseIfNotExistsAsync(DatabaseId);

                container = await GetOrCreateContainerAsync(cosmosDatabase, CollectionId);

                //await CreateItems(container);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 26
0
        private static async Task <CosmosService> InitCosmosClientAsync(IConfigurationSection configurationSection)
        {
            string databaseName  = configurationSection.GetSection("DatabaseName").Value;
            string containerName = configurationSection.GetSection("ContainerName").Value;
            string account       = configurationSection.GetSection("Account").Value;
            string key           = Environment.GetEnvironmentVariable("CosmosKey");

            CosmosClient     client        = new CosmosClient(account, key);
            CosmosService    cosmosService = new CosmosService(client, databaseName, containerName);
            DatabaseResponse database      = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");

            return(cosmosService);
        }
Ejemplo n.º 27
0
        private static async Task InitCosmosDb()
        {
            string       databaseId             = "EdgeElevator";
            string       containerId            = "State";
            string       cosmosConnectionString = "";
            CosmosClient client = new CosmosClient(cosmosConnectionString, new CosmosClientOptions()
            {
                ConnectionMode = ConnectionMode.Direct
            });
            var database = await client.CreateDatabaseIfNotExistsAsync(databaseId);

            ContainerResponse container = await database.Database.CreateContainerIfNotExistsAsync(new ContainerProperties(containerId, "/id") { PartitionKeyDefinitionVersion = PartitionKeyDefinitionVersion.V2 });

            _container = container.Container;
        }
Ejemplo n.º 28
0
        private static async Task <PersonRegistrationService> InitCosmosAsync(IConfigurationSection configurationSection)
        {
            string           databaseName  = configurationSection.GetSection("DatabaseName").Value;
            string           containerName = configurationSection.GetSection("ContainerName").Value;
            string           account       = configurationSection.GetSection("Account").Value;
            string           key           = configurationSection.GetSection("Key").Value;
            CosmosClient     client        = new CosmosClient(account, key);
            DatabaseResponse database      = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            var container = await client.GetDatabase(databaseName).CreateContainerIfNotExistsAsync(nameof(PersonRegistration), "/id");

            PersonRegistrationService cosmosService = new PersonRegistrationService(client, databaseName, containerName);

            return(cosmosService);
        }
        public async Task TestInitialize()
        {
            CosmosClientOptions clientOptions = new CosmosClientOptions();

            clientOptions.AllowBulkExecution = true;
            CosmosClient client = TestCommon.CreateCosmosClient(clientOptions);

            DatabaseResponse response = await client.CreateDatabaseIfNotExistsAsync(Guid.NewGuid().ToString());

            this.database = response.Database;

            ContainerResponse containerResponse = await this.database.CreateContainerAsync(Guid.NewGuid().ToString(), "/Status", 10000);

            this.container = containerResponse;
        }
Ejemplo n.º 30
0
        private async Task <Container> CreateDatabaseAndCollection(CancellationToken cancellationToken)
        {
            CosmosClientOptions options = new()
            {
                ConnectionMode = ConnectionMode.Gateway,
            };

            CosmosClient client = new CosmosClient(_cosmosSettings.EndpointUri, _cosmosSettings.PrimaryKey, options);

            Database db = await client.CreateDatabaseIfNotExistsAsync(_databaseId, cancellationToken : cancellationToken);

            Container container = await db.CreateContainerIfNotExistsAsync(_collectionId, _partitionKey, cancellationToken : cancellationToken);

            return(container);
        }