Monday 19 September 2022

Working with in Azure Cosmos DB using Core .Net

Introduction:

Welcome to Azure Cosmos DB

Today's applications are required to be highly responsive and always online. To achieve low latency and high availability, instances of these applications need to be deployed in datacenters that are close to their users. Applications need to respond in real time to large changes in usage at peak hours, store ever increasing volumes of data, and make this data available to users in milliseconds.

Azure Cosmos DB is a fully managed NoSQL database for modern app development. Single-digit millisecond response times, and automatic and instant scalability, guarantee speed at any scale. Business continuity is assured with SLA-backed availability and enterprise-grade security. App development is faster and more productive thanks to turnkey multi region data distribution anywhere in the world, open source APIs and SDKs for popular languages.

 As a fully managed service, Azure Cosmos DB takes database administration off your hands with automatic management, updates and patching. It also handles capacity management with cost-effective serverless and automatic scaling options that respond to application needs to match capacity with demand.


In this articles will discuss:

1. How to Create database Azure Cosmos DB in Azure portal

2. How to Create Container or table Azure Cosmos DB

3. How to Insert records in Container

4. Working the different types of queries.


We are assuming you have an Account in Azure portal.


Step 1. First you have to create a Cosmos Db account in Azure portal. For this you in https://portal.azure.com. You also use your free subscription here.

Step 2. Search Azure Cosmos DB in search box in select “Azure Cosmos DB” in this blade click on Create button as shown in below screen or image.

 


Step 3. Select Core (SQL) – Recommended as shown in below screen



Step 3: Provide required details and click on Review and Create button


Now wait for 2-3 minutes. After then go to CosmosDB detail page as shown in below:



Now click on Data Explorer in left side panel then one popup will open, then click on full screen button as shown in below scree:



Next page will open and auto login in work in Cosmos DB.

New coding part:

Go to Visual Studio 2022 and create one Console application and give name "cosmosDB".

We need to install one NuGet package: Microsoft.Azure.Cosmos


Now, Go to Program.cs and write following codes:

How to Create Database in Azure Cosmos DB?

cosmosDBEndUrl  and cosmosDbKey  will get from Azure portal. Go to Cosmos DB and click on Key link





using Microsoft.Azure.Cosmos;

string cosmosDBEndUrl = "https://testdbtesttb.documents.azure.com:443/";
string cosmosDbKey = "keykeykeykey";

await CreateDatabase("appdb"); // calling here CreateDatabase method

async Task CreateDatabase(string dataBaseName)
{
    try
    {
        CosmosClient cosmosClient;
        cosmosClient = new CosmosClient(cosmosDBEndUrl, cosmosDbKey);
        await cosmosClient.CreateDatabaseAsync(dataBaseName);
        Console.WriteLine("Database Created.");
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


How to Create Container in Azure Cosmos DB?

using Microsoft.Azure.Cosmos;

string cosmosDBEndUrl = "https://testdbtesttb.documents.azure.com:443/";
string cosmosDbKey = "keykeykeykey";

await CreateContainer("appdb", "Orders", "/category");

async Task CreateContainer(string dataBaseName, string containerName, string partitionKey)

{

    try

    {

        CosmosClient cosmosClient;

        cosmosClient = new CosmosClient(cosmosDBEndUrl, cosmosDbKey);

        Database database = cosmosClient.GetDatabase(dataBaseName);

        await database.CreateContainerAsync(containerName, partitionKey);

        Console.WriteLine("Container Created.");

    }

    catch (Exception ex)

    {

        throw ex;

    }

}


Now to Azure portal and View the details:



How to Insert records in Container?


using Microsoft.Azure.Cosmos;

string cosmosDBEndUrl = "https://testdbtesttb.documents.azure.com:443/";

string cosmosDbKey = "keykeykeykey"; 

string databaseName = "appdb";

string containerName = "Orders"; 

// calling Method in Main method

await AddItem("O1", "Laptops", 100);

await AddItem("O2", "Desktops", 200);

await AddItem("O3", "Mobiles", 150);

await AddItem("O4", "Laptop", 120); 

async Task CreateContainer(string dataBaseName, string containerName, string partitionKey)

{

    try

    {

        CosmosClient cosmosClient;

        cosmosClient = new CosmosClient(cosmosDBEndUrl, cosmosDbKey);

        Database database = cosmosClient.GetDatabase(dataBaseName);

        await database.CreateContainerAsync(containerName, partitionKey);

        Console.WriteLine("Container Created.");

    }

    catch (Exception ex)

    {

        throw ex;

    }

}

 


How to Get records from Container?


 

using Microsoft.Azure.Cosmos;

string cosmosDBEndUrl = "https://testdbtesttb.documents.azure.com:443/";

string cosmosDbKey = "keykeykeykey"; 

string databaseName = "appdb";

string containerName = "Orders"; 

// calling in Main method

await GetItem(); 

async Task GetItem()

{

    CosmosClient cosmosClient;

    cosmosClient = new CosmosClient(cosmosDBEndUrl, cosmosDbKey);

    Database database = cosmosClient.GetDatabase(databaseName);

    Container container = database.GetContainer(containerName);

    string sqlQuery = "select o.orderId,o.category,o.quantity from Orders o";

    QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);

    FeedIterator<Order> feedIterator = container.GetItemQueryIterator<Order>(queryDefinition);

    while (feedIterator.HasMoreResults)

    {

        FeedResponse<Order> orders=await feedIterator.ReadNextAsync();

        foreach(Order item in orders)

        {

            Console.WriteLine("The orderId {0}, category is {1} and quantity {2}",item.orderId,item.category,item.quantity);

        }

    }

} 

 


How to update or replacing item in Container?

await ReplaceItem();// Calling the method in Main method

async Task ReplaceItem() // Updating item

{

    Console.WriteLine("Enter order Id:");

    string orderIdInput = Console.ReadLine();

 

    Console.WriteLine("Enter quantiry:");

    int quantity =Convert.ToInt32(Console.ReadLine());

 

  

    CosmosClient cosmosClient;

    cosmosClient = new CosmosClient(cosmosDBEndUrl, cosmosDbKey);

    Database database = cosmosClient.GetDatabase(databaseName);

    Container container = database.GetContainer(containerName);  

    string sqlQuery = $"select o.id,o.category from Orders o where o.orderId='{orderIdInput}'";

    string id = "";

    string category = "";

    QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);

    FeedIterator<Order> feedIterator = container.GetItemQueryIterator<Order>(queryDefinition);

    while (feedIterator.HasMoreResults)

    {

        FeedResponse<Order> orders = await feedIterator.ReadNextAsync();

        foreach (Order item in orders)

        {

            id = item.id;

            category = item.category;

        }

    };

 

    ItemResponse<Order> response = await container.ReadItemAsync<Order>(id, new PartitionKey(category));

    var items = response.Resource;

    items.quantity = quantity;

    await container.ReplaceItemAsync<Order>(items, id, new PartitionKey(category));

 

    Console.Write("Item updated successfully.");

}  


1 comment:

  1. Thank you so much for letting me express my feeling about your post. Private tutor St. AugustineYou write this blog post so well.

    ReplyDelete