Working with Cosmos DB

Azure Cosmos is a globally distributed, multi-model database service. I’ve worked with it recently as the backend database for several Azure web apps and am impressed with its responsiveness.

To connect to the document database, I used the Cosmos SDK which is a client library that enables client applications to connect to Azure Cosmos via the SQL API. It can be found here or be included in your Visual Studio project using NuGet.

In my projects, I included the library in a console application for bulk document modification and a Web API application for client data access. Overall, I’d say it was fairly easy to work with.

Here are a few example code snippets to get you started:

Console Application

using System;
using Microsoft.Azure.Cosmos;

namespace CosmosDBConsoleAppExample
{
    class Program
    {
        private static readonly string EndpointUri = "<Endpoint URL>";
        private static readonly string PrimaryKey = "<Primary Key>";
        private static readonly string DatabaseName = "<Database Name>";
        private static readonly string ContainerName = "<Container Name>";

        static async Task Main(string[] args)
        {
            CosmosClient client = new CosmosClient(EndpointUri, PrimaryKey);
            var database = client.GetDatabase(DatabaseName);
            var container = database.GetContainer(ContainerName);

            Console.WriteLine("Connected to Cosmos DB");

            Console.WriteLine("\nReading items from the database...\n");
            var query = "SELECT * FROM c";
            var iterator = container.GetItemQueryIterator<dynamic>(query);
            while (iterator.HasMoreResults)
            {
                var response = await iterator.ReadNextAsync();
                foreach (var item in response)
                {
                    Console.WriteLine("\t" + item);
                }
            }

            Console.WriteLine("\nPress any key to continue...");
            Console.ReadKey();
        }
    }
}

In the code example above, you will need to replace the placeholder values for EndpointUri, PrimaryKey, DatabaseName and ContainerName with your actual values. Once you do that, the application will connect to Cosmos DB and write out the documents in your container to the console.

Web API

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;

namespace CosmosDBWebAPIExample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private static readonly string EndpointUri = "<Endpoint URL>";
        private static readonly string PrimaryKey = "<Primary Key>";
        private static readonly string DatabaseName = "<Database Name>";
        private static readonly string ContainerName = "<Container Name>";

        private CosmosClient cosmosClient;
        private Container container;

        public ValuesController()
        {
            this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
            this.container = cosmosClient.GetContainer(DatabaseName, ContainerName);
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<dynamic>>> Get()
        {
            var query = "SELECT * FROM c";
            var iterator = container.GetItemQueryIterator<dynamic>(query);
            List<dynamic> results = new List<dynamic>();
            while (iterator.HasMoreResults)
            {
                var response = await iterator.ReadNextAsync();
                results.AddRange(response.ToList());
            }
            return results;
        }
    }
}

As before, you will need to replace the placeholder values for EndpointUri, PrimaryKey, DatabaseName and ContainerName with your actual values. Once you do that, you can query the endpoint from your front-end web application or from Postman. The endpoint will connect to Cosmos DB and returns all the documents in your container.

Leave a comment