Facing issue to create Cosmos Db using .NET core SDK

105 Views Asked by At

The code successfully created the container, which is now available for use. However, when attempting to create a database, it enters an infinite loop.

var name = "cosmosdb_emulator";
        var exposedPort = 8083; // Port exposed by the container
        var ContainerCosmosServicePort = 8081; // Port used by the Cosmos service within the container

        try
        {
            var containerService = new Builder()
                .UseContainer()
                .WithName(name)
                .UseImage($"mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator")
                .ReuseIfExists()
                .ExposePort(exposedPort, ContainerCosmosServicePort)
               // .WaitForMessageInLog("Cosmos service is successfully listening")
                .Build();                    
           
                containerService.Start();
                Console.WriteLine($"Container {name} started successfully.");

            var _cosmosdbConnectionString = "AccountEndpoint=https://localhost:8083/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";

            CosmosClientOptions options = new()
            {
                HttpClientFactory = () => new HttpClient(new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                })
            };
            // Initialize Cosmos DB client
            CosmosClient client = new CosmosClient(_cosmosdbConnectionString, clientOptions: options);

            // Check if the database exists; if not, create it
            DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("abc");
1

There are 1 best solutions below

1
Vivek Vaibhav Shandilya On

This worked for me.

For reference check this document.

For Docker container creation follow this document.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Docker.DotNet;
using Docker.DotNet.Models;
using Microsoft.Azure.Cosmos;

namespace CosmosDBConsoleApp
{
    public class Program
    {
        public static async Task Main()
        {

            try
            {
                DockerClient client = new DockerClientConfiguration()
                 .CreateClient();

                await client.Images.CreateImageAsync(
                new ImagesCreateParameters
                {
                    FromImage = "mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator",
                    Tag = "latest"

                },
                null,
                new Progress<JSONMessage>()) ;

                Console.WriteLine("Image is pulled");

                var container = await client.Containers.CreateContainerAsync(new CreateContainerParameters()
                {
                    Image = "mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator",
                    HostConfig = new HostConfig
                    {
                        PortBindings = new Dictionary<string, IList<PortBinding>>
                            {
                                { "8081", new List<PortBinding> { new PortBinding { HostPort = "8081" } } }
                            },
                            DNS = new[] { "0.0.0.0:8081" }

                   }

                });

                Console.WriteLine("Container created sucessfully");
                await client.Containers.StartContainerAsync(container.ID,
                   new ContainerStartParameters());

                Console.WriteLine("Container started successfully");

                var _cosmosdbConnectionString = "AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
                    CosmosClientOptions options = new()
                    {
                        HttpClientFactory = () => new HttpClient(new HttpClientHandler()
                        {
                            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                        })
                    };

                    // Initialize Cosmos DB client
                    CosmosClient cosmosclient = new CosmosClient(_cosmosdbConnectionString, clientOptions: options);
                                

                    Console.WriteLine("Cosmos client created");

                Database database = await cosmosclient.CreateDatabaseIfNotExistsAsync(
                    id: "cosmosemulatordb",
                    throughput: 400
                );
                Console.WriteLine("Cosmos Database created sucessfully");
                Container dbcontainer = await database.CreateContainerIfNotExistsAsync(
                    id: "emulatorcontainer",
                    partitionKeyPath: "/id"
                );

                Console.WriteLine("Cosmos Container created sucessfully");

                var item = new
                {
                    id = "68719518371",
                    name = "Kiama classic surfboard"
                };

                await dbcontainer.UpsertItemAsync(item);

                Console.WriteLine("item created sucessfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }

        }
    }
}

OUTPUT:

{
    "id": "68719518371",
    "name": "Kiama classic surfboard"
}