Azure Cosmos DB to solve application challenges | Serverless360
← Return To Home

Getting Started with Azure Cosmos DB Using .NET SDK

Tags:  
Serverless360

Introduction

Any application built today is expected to be highly responsive, highly available, and required to adapt to enormous changes in real-time at peak business hours, store ever-increasing volumes of data, and make that stored data available for users a fraction of seconds. To achieve such low latency and high availability, you need to deploy these applications’ Instances in data centers that are close to their users. This blog will see how Azure Cosmos DB addresses the above challenges and how to use the .net SDK for Azure Cosmos.

What is Azure Cosmos DB?

Azure Cosmos DB is a Microsoft’s globally distributed, multi-model database service. It enables scaling the throughput elastically and independently. Also, it offers storage across any number of Azure regions worldwide. Cosmos DB provides comprehensive service level agreements for throughput, latency, availability, and consistency guarantees.

Azure Cosmos Databases, Containers, and Items

Databases

The Cosmos database is like a namespace, the unit of management for a set of Cosmos Containers. Every Cosmos account can consist of one to more Cosmos Databases.

Containers

A Cosmos container is the unit of scalability for provisioned throughput and storage. It can be scaled elastically, horizontally partitioned, and then replicated across multiple Azure regions. The items added to the Container and the throughput provisioned distributes automatically across the partitions based on the partition key. 

Items

You can represent a Cosmos item as a document in a collection, row in a table, node, or edge in a graph. The below table shows the Cosmos Item against each Cosmos Entity.

Cosmos Entity

Cosmos Item

SQL

Item

Cassandra

Row

Mongo 

Document

Gremlin

Node or Edge

Table

Item

Let us have a short glimpse of the core capabilities of the Azure Cosmos DB.

High Throughput

With single-digit millisecond reads and writes worldwide and with the capability to elastically scale from thousands to hundreds of millions of requests per second, Cosmos DB offers unparalleled throughput. 

Low Latency

Cosmos DB ensures less than ten milliseconds latency for reads and writes at the 99th percentile worldwide. This capability enables the applications to be highly responsible.

Global Distribution

To achieve low latency and high availability, you can deploy instances of the applications in multiple data centers. Globally distributed applications require a globally distributed database. Cosmos DB seamlessly replicates the data to all the Azure regions associated with the Cosmos account while maintaining the application’s high availability.

Multi-Consistency Model

Distributed applications make a fair trade-off between data consistency, availability, and latency. Cosmos DB’s multi-master replication model offers five consistency models: strong, bounded staleness, session, consistent prefix, and eventual for an intuitive programming model with low latency and high availability for a globally distributed application. The consistency levels are region-agnostic and are guaranteed for all operations regardless of the region.

Available APIs

Cosmos DB supports five flavors of APIs for the developer’s convenience.

  • Core (SQL)
  • Cassandra
  • Mongo DB (Document)
  • Gremlin (Graph)
  • Table

Now let us create a project that uses an Azure Cosmos DB SQL API client library for .NET to manage resources.

Prerequisite

Create an Azure Cosmos DB account of type SQL API in your Azure Subscription. Ensure that the right API is chosen in the first place as it is more difficult to change once you create the account.

The Azure Cosmos DB creates resources in the following hierarchy

  • Azure Cosmos account
  • Databases
  • Containers
  • Items

Once you create the account, open the Keys pane to copy the Uri and Primary Key.

Create a .NET App and Install the Azure Cosmos DB package

Create a new .NET application in your preferred IDE. Once you create the application, install the Azure Cosmos DB package. Here, we are using the Visual Studio Package Manager to do that by running ‘Install-Package Microsoft.Azure. Cosmos’ command in the power shell.

Code Sample

Create a new class file named Product.cs in the application. It has a few properties corresponding to the product.

public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public Customer[] Customers { get; set; }
        public string Version { get; set; }
    }

    public class Customer
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

Add the following global variables in the Program.cs class. The variables will include the endpoint (Uri), authorization key (Primary Key), the Database’s name, and the Container’s name. You can retrieve these values from environment variables at the runtime.

private const string Endpoint = Environment.GetEnvironmentVariable("EndpointUri");
private const string AuthorizationKey = 
Environment.GetEnvironmentVariable("PrimaryKey");
private const string DatabaseName = Environment.GetEnvironmentVariable("DatabaseName");
private const string ContainerName =
 Environment.GetEnvironmentVariable("Container Name");

Create a Cosmos Client

The CosmosClient library enables client applications to connect to Azure Cosmos through SQL API, and this client object helps to configure and execute requests against the service.

CosmosClient cosmosClient = new CosmosClient(Endpoint, AuthorizationKey);

Create a database

The CreateDatabaseIfNotExistsAsync method creates a database if it doesn’t exist or gets the Database if it already exists.

CosmosDatabase database = await 
cosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseName);

Delete a database

The DeleteAsync method deletes the specified Database from the Azure Cosmos account.

CosmosDatabase database = cosmosClient.GetDatabase(DatabaseName);
DatabaseResponse databaseResourceResponse = await database.DeleteAsync();

Create a container

The CreateContainerIfNotExistsAsync method creates the Container with a specified name if it doesn’t exist. I am specifying the product name as partition key here. Status code from the response helps to identify whether the Container was newly created (201) or an existing container was returned (200).

CosmosContainer container = await cosmosClient.GetDatabase(DatabaseName).CreateContainerIfNotExistsAsync(ContainerName, "/PartitionKey_ProductName");

Delete a container

The DeleteContainerAsync method deletes a Container from the Azure Cosmos DB account.

CosmosDatabase database = cosmosClient.GetDatabase(DatabaseName);
Container container = database.GetContainer(ContainerName);
var response = await container.DeleteContainerAsync();

Create an item

The createItemAsync method creates an item within the Container. UpsertItemAsync method creates an item within the Container if it doesn’t already exist or replaces the item if it already exists.

 Product product = new product
    {
        Id = "Kovai_Co_1",
        Name = "Serverless360",
        Customers = new Customer[]
        {
            new Customer { Id = "Serverless360_Customer_1", Name = "Contoso" },
            new Customer { Id = " Serverless360_Customer_2", Name = "Microsoft" }
        },        
        Version = "4.5"
    };

CosmosContainer container = cosmosClient.GetContainer(DatabaseName, ContainerName);

var response = await container.CreateItemAsync( product, new PartitionKey(product.Name));

var response = await container.UpsertItemAsync(product, new PartitionKey(product.Name));

Replace an item

The ReplaceItemAsync method updates an item within the Container.

CosmosContainer container = cosmosClient.GetContainer(DatabaseName, ContainerName);
var response = await container.ReadItemAsync(" Kovai_Co_1", new PartitionKey("Serverless360"));

 var item = response;    
 item.Version = "5.0"; // updated the version from 4.5 to 5.0

 var replaceResponse = await container.ReplaceItemAsync(item, item.Id, new PartitionKey(item.Name));

Delete an item

The DeleteItemAsync method deletes an item within the Container.

 CosmosContainer container = cosmosClient.GetContainer(DatabaseName, ContainerName);
    
 //Id of the item and partition key must be provided to delete an item.
 var response = await container.DeleteItemAsync("Kovai_Co_1",new PartitionKey("Serverless360"));

Query the items

Use the following code to execute the query using the SQL.

var sqlQuery = "select * from c";
 QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);
 List products = new List();

 CosmosContainer container = cosmosClient.GetContainer(DatabaseName, ContainerName);

await foreach (Product product in container.GetItemQueryIterator(queryDefinition))
{
    products.Add(product);
}

Conclusion

In this blog, we saw how Azure Cosmos DB solves the challenges that the modern applications tend to face and the code samples to work with the SQL API of Azure Cosmos DB.