Article Overview

  1. Background

    1. Azure Cosmos DB

    2. Azure Cosmos DB Items

  2. Create Azure Cosmos DB account

  3. Create Data Resources and Items using .NET console app

    1. Create console application

    2. Configure application

    3. Starter code

    4. Complete code

      1. Create a cosmos DB client

      2. Create a database

      3. Create a container

      4. Define typed item

      5. Add item to a container

      6. Build application

  4. Run application and verify result

  5. Clean up resources

  6. Summary

This article describes a complete process of how to create a Azure Cosmos DB account and build .NET console application. In this example Microsoft Azure Cosmos DB SDK is used to create Database, Container, and Item. Authentication is configured and database operations are performed through programming. Results are verified in the Azure Portal. Following activities are performed one by one:

1. Background

A complete description and background about Azure Cosmos DB and Azure Cosmos DB Items is given in previous article How to Create Azure Cosmos DB Resources by using the Azure Portal?. Hence, same is not repeated here and one can refer it from it. Hierarchy of Azure Cosmos DB account entities is depicted in below figure:

Azure Cosmos DB account entities

2. Create Azure Cosmos DB account

Let’s first create Resource Group and Azure Cosmos DB account using Azure Cloud Shell (Azure CLI). One can also create it from Azure Portal, PowerShell, Azure CLI (Azure Cloud Shell), Bicep, Template, Azure Developer CLI, or Terraform. Resource Group and Azure Cosmos DB account using Azure Portal in article How to Create Azure Cosmos DB Resources by using the Azure Portal?

Use Azure Cloud Shell (Azure CLI)

It is a free Bash shell which can be run directly within the Azure portal. It is preinstalled and configured within an account.

az group create \ 
     --name <resource-group> \ 
     --location <location>
az group create \ 
     --name myResourceGroup \ 
     --location eastus2
az account list-locations
az account list-locations --query "[*].name"
az account list-locations --query "[*].name" --out tsv | sort
az cosmosdb create \
     --name <db-account-name> \
     --resource-group <resource-group>
az cosmosdb create \
     --name cosmosExercise1\
     --resource-group myResourceGroup
az cosmosdb show \
     --name cosmosExercise1\
     --resource-group myResourceGroup
     --query "documentEndpoint"
     --output tsv
az cosmosdb keys list \
     --name cosmosExercise1\
     --resource-group myResourceGroup
     --query "primaryMasterKey"
     --output tsv
az cosmosdb keys list \
     --name cosmosExercise1\
     --resource-group myResourceGroup

Now basic things are done and next task is to create a console application for further process.

3. Create Data Resources and Items using .NET console app

Let’s create data resources and items through .NET console application using . Open Cloud Shell and perform the following steps one by one:

3.1. Create console application

Set up the console application to create data resources and items.

mkdir cosmosdb1
cd cosmosdb1
dotnet new console

3.2. Configure application

First add packaged and after that create and update .env file. env file holds the secrets.

dotnet add package Microsoft.Azure.Cosmos --version 3.*
dotnet add package Newtonsoft.Json --version 13.*
dotnet add package dotenv.net
touch .env
code .env
DOCUMENT_ENDPOINT="YOUR_DOCUMENT_ENDPOINT"
ACCOUNT_KEY="YOUR_ACCOUNT_KEY"

3.3. Starter code

Add the following starter code into the application. Let’s replace template code in Program.cs file by using editor in Cloud Shell.

code Program.cs
using Microsoft.Azure.Cosmos;
using dotenv.net;

string databaseName = "db1"; // this named database will be created to use it
string containerName = "container1"; // this named container will be cerated to use it

// From .env file - load environment variables 
DotEnv.Load();
var envVars = DotEnv.Read();
string cosmosDbAccountUrl = envVars["DOCUMENT_ENDPOINT"];
string accountKey = envVars["ACCOUNT_KEY"];

if (string.IsNullOrEmpty(cosmosDbAccountUrl) || string.IsNullOrEmpty(accountKey))
{
    Console.WriteLine("Set DOCUMENT_ENDPOINT and ACCOUNT_KEY environment variables. Press any key to continue!");
    Console.ReadLine();
    return;
}

// CREATE COSMOS DB CLIENT

try
{
    // CREATE DATABASE

    // CREATE CONTAINER

    // DEFINE PRODUCT TYPE ITEM

    // ADD ITEM INTO CONTAINER
}
catch (CosmosException ex)
{
    // Cosmos DB-specific exception's handeling
    Console.WriteLine($"Cosmos DB Error: {ex.StatusCode} - {ex.Message}. Press any key to continue!");
    Console.ReadLine();
}
catch (Exception ex)
{
    // General exception's handeling
    Console.WriteLine($"Error: {ex.Message}. Press any key to continue!");
    Console.ReadLine();
}

// Class represents product in Cosmos DB container
public class Product
{
    public string? id { get; set; }
    public string? name { get; set; }
    public string? description { get; set; }
}

3.4. Complete code

Add following code one by one at mentioned commented section to complete the application. Let’s update the code fore commented lines for specific operations one by one with description to create client, database, container, and add items into container.

3.4.1. Create cosmos DB client through account URL and key

First create an instance of CosmosClient class to connect API for NoSQL of Azure Cosmos DB. This class is main starting point to perform all the operations against the database. It is a best practice to use the DefaultAzureCredential from Azure Identity library which require couple of additional configurations in Azure this is used in previous one article How to Create Azure Blob Storage Resources by using .NET Client Library? Locate // CREATE COSMOS DB CLIENT comment, then add following code directly beneath comment.

CosmosClient client = new(
    accountEndpoint: cosmosDbAccountUrl,
    authKeyOrResourceToken: accountKey
);

3.4.2. Create a database only if it doesn’t exists

CreateDatabaseIfNotExistsAsync command will create a database if it doesn’t exists. Locate // CREATE DATABASE comment, then add following code directly beneath comment.

Database database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
Console.WriteLine($"Database - Created or Retrieved : {database.Id}. Press any key to continue!");
Console.ReadLine();

3.4.3. Create container using specified partition key

CreateContainerIfNotExistsAsync command will create a container if it doesn’t exists. Locate // CREATE CONTAINER comment, then add following code directly beneath comment.

Container container = await database.CreateContainerIfNotExistsAsync(
    id: containerName,
    partitionKeyPath: "/id"
);
Console.WriteLine($"Container - Created or Retrieved : {container.Id}. Press any key to continue!");
Console.ReadLine();

3.4.4. Define typed item i.e. product to add into the container

This is simple Product class with three basic information. Locate // DEFINE PRODUCT TYPE ITEM comment, then add following code directly beneath comment.

Product newItem = new Product
{
    id = Guid.NewGuid().ToString(), // Generate an unique ID for the product
    name = "Desktop Computer",
    description = "HP All-in-One Desktop PC 54.5 cm"
};

3.4.5. Add item to a container

CreateItemAsync will mentioned item to given container. Locate // ADD ITEM INTO CONTAINER comment, then add following code directly beneath comment.

ItemResponse<Product> createResponse = await container.CreateItemAsync(
    item: newItem,
    partitionKey: new PartitionKey(newItem.id)
);

Console.WriteLine($"Created item with ID: {createResponse.Resource.id}. Press any key to continue!");
Console.ReadLine();

Now it’s time to save and close the file to build the application. Press ctrl + s to save file and then ctrl + q to exit the editor. Here, by with this article a complete code is attached in Program.cs file.

3.4.6. Build application

Run dotnet build command in Cloud Shell to test any error in project.

dotnet build

Now, console application is completed and tested for any build time error. Next task is to run the application from Cloud Shell and than use the Azure Portal to verify the results.

4. Run application and verify result

Database - Created or Retrieved : db1. Press any key to continue!
Container - Created or Retrieved : container1. Press any key to continue!
Created item with ID: 2B518442-4CDE-4C0E-BB58-48A3E1E5EB71. Press any key to continue!

5. Clean up resources

Once finished the exercise it’s recommended to delete cloud resources are being created to avoid the unnecessary resource usage and any future costs. Deleting a resource group will delete all resources contained within it. Perform following steps one by one in to Azure Portal to achieve this:

6. Summary

Here, a complete process flow is described to manage various tasks on an Azure Cosmos DB account by using .NET Client Library from Azure Cloud Shell (Azure CLI). A console application is created using Microsoft Azure Cosmos DB SDK to create Database, Container, and Item. Azure Portal is used to verify results. At the end resources are being cleaned up.