Building CRUD Web API for Cosmos DB using C# ASP.NET Core

In this article, we will be building a CRUD (create, read, update, and delete) Web API using C# and ASP.NET Core to interact with Cosmos DB. This article will take you through the process of setting up a Cosmos DB database, creating a Web API project, and implementing CRUD operations using C#.

 
Azure Cosmos DB CRUD Flow By Vithal Wadje


Step 1: Set up Prerequisites

Set up the following one of the required pre-requisites to perform the CRUD operation in the Azure Cosmos DB

    • Azure Subscription OR
    • Azure Cosmos DB Emulator 

Azure Subscription 

To create the Azure cloud Cosmos DB account, you need an active Azure subscription. When you create the Cosmos DB account on the cloud, the Azure Cosmos DB Serverless account provides the first 1000 RU and 25 GB of storage for free per subscription.

Refer to the following link to learn the basics and how to create the Azure Cosmos DB account.

Azure Cosmos DB Emulator (offline)

As explained, the first approach requires an active Azure subscription as well as an active internet connection, which is not feasible for everyone who just wants to explore or learn about the Azure Cosmos DB.

To overcome the preceding issue, we can use the Azure Cosmos DB capabilities and features using the Azure Cosmos DB Emulator without an active Azure subscription or an active internet connection.

The Azure Cosmos DB Emulator currently does not have support for all the NoSQL APIs, but it will support the most commonly used NoSQL APIs, such as the SQL API and Mongo DB API, and in the future it may also support all the Cosmos DB APIs.

The following is the link to download the Azure Cosmos DB Emulator.

After clicking on the link, the official Microsoft documentation website gets opened, from which you can find and install the latest version of the Azure Cosmos DB Emulator.

Step 2: Create Azure Cosmos DB 

In this article, we are going to use the Azure Cosmos DB emulator instead of a Cloud Azure Cosmos DB account. If you are new to Azure Cosmos DB, please read the articles below to learn how to create an Azure Cosmos DB account. 
We are using the Azure Cosmos DB emulator in this article. search for the Azure Cosmos DB emulator from the search bar of the window once you download and install the emulator, which looks like the following:



The preceding image shows the Azure CosmosDB Account of the emulator, which will provide the same features as the Cloud Azure CosmosDB Account for development. Now click on the explorer and create the database and container. The explorer will then look like this:



We are storing the employee basic data in the Azure CosmosDB, and we are planning to use Department as a partition key and ID as the unique id for our employee records.

Note:
  • The ID and Department properties should be part of your backend input while inserting or updating the records; otherwise, you will get the exceptions.
I hope you have completed the required setup as explained in this article, including the creation of the Azure Cosmos account and database.

Step 3: Create ASP.NET Core web api Project

  1. Start then  All Programs and select "Microsoft Visual Studio".
  2. Once the Visual Studio Opens, Then click on Continue Without Code.
  3. Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web Api Project Template.
  4. Then define the project name, location of the project, then click on the next button.
  5. On the next screen, provide the additional details: framework, authentication type, and check the Enable Open API Support checkbox as shown below.


The preceding steps will create the ASP.NET Core Web API application and solution explorer. It will look like what is shown in the following image.



Step 4: Add Microsoft.Azure.Cosmos Nuget Package Reference

The Microsoft.Azure.Cosmos is the the latest nuget package to interact with the Azure cosmos DB. The Microsoft.Azure.Cosmos supports the basic to custom and complex database operations, follow the following steps to add the Nuget package.

  1. Right click on the Solution Explorer, find Manage NuGet Package Manager and click on it
  2. After as shown into the image and type in search box Microsoft.Azure.Cosmos
  3. Select Microsoft.Azure.Cosmos as shown into the image, 
  4. Choose version of Microsoft.Azure.Cosmos library and click on install button


I hope you have followed the same steps and installed the Microsoft.Azure.Cosmos nuget package.The next step is to delete the default controller and model class so we can start from scratch.


Step 5:Create the Model Class

  • First, delete the default model class, which is created outside the folder structure, so we can start from scratch. 
  • Next, create the folder named Model by right clicking on the solution explorer.
  • Create the model class Employee Model by right clicking on the Model folder, as shown in the following image


Now open the EmployeeModel.cs class file and add the following code.

EmployeeModel.cs

namespace EmployeeManagement.Model
{
    public class EmployeeModel
    {
        public string? id { get; set; }
        public string? Name { get; set; }
        public string? Country { get; set; }
        public string? City { get; set; }       
        public string? Department { get; set; }
        public string? Designation { get; set; }
        public DateTime? JoiningDate { get; set; }

    }
}

Step 6: Add the Controller

Create the Empty API Controller class EmployeeController by right clicking on the Controller folder as shown in the following image.



After adding the model class and API controller class, the solution explorer will look like the following:




Now open the EmployeeController.cs file and add the add the following configuration.
  • Define the following route at controller level, so that we can add the multiple Get, Post, Put, or Delete and avoid the name ambiguity exception.
    [ApiController]
    [Route("[api/[controller]/[action]]")]
    public class EmployeeController : ControllerBase
    {
    }

  • Declare the following variable and set the Azure Cosmos DB configuration by copying the details from step 2.
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController : ControllerBase
    {
       
        // Cosmos DB details, In real use cases, these details should be configured in secure configuraion file.
        private readonly string CosmosDBAccountUri = "https://localhost:8081/";
        private readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        private readonly string CosmosDbName = "EmployeeManagementDB";
        private readonly string CosmosDbContainerName = "Employees";
}

Step 7: Create Method to Add Employee

Add the following code into the EmployeeController.cs class to Add the employees into the CosmosDB. This method takes input values using  the EmployeeModel class. 

        [HttpPost]
        public async Task<IActionResult> AddEmployee(EmployeeModel employee)
        {
            try
            {
                var container = ContainerClient();
                var response = await container.CreateItemAsync(employee, new PartitionKey(employee.Department));

                return Ok(response);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
               
        }


As explained in step 2, we are passing the ID and Department as a partition key as part of the employee input payload while adding the employee details. These parameters must be part of the input parameter payload.

Step 8:  Create Method to Get Employees

Add the following code into the EmployeeController.cs class to get all the employees from the Cosmos database.

        [HttpGet]
        public async Task<IActionResult> GetEmployeeDetails()
        {
            try
            {
                var container = ContainerClient();
                var sqlQuery = "SELECT * FROM c";
                QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);
                FeedIterator<EmployeeModel> queryResultSetIterator = container.GetItemQueryIterator<EmployeeModel>(queryDefinition);


                List<EmployeeModel> employees = new List<EmployeeModel>();

                while (queryResultSetIterator.HasMoreResults)
                {
                    FeedResponse<EmployeeModel> currentResultSet = await queryResultSetIterator.ReadNextAsync();
                    foreach (EmployeeModel employee in currentResultSet)
                    {
                        employees.Add(employee);
                    }
                }

                return Ok(employees);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
           
        }


This example is not good practise since we are fetching all the employees without paging or a partition key filter, but we are doing this to learn how it works without making it complicated. In the next article, I will show how to get a list of records with the paging.

Step 9: Create Method to Get Employee by ID

Create the GetEmployeeDetailsById method in the EmployeeController.cs and add the following code to get the employee by employeeId and partition key from the Cosmos database.


        [HttpGet]
        public async Task<IActionResult> GetEmployeeDetailsById(string employeeId,string partitionKey)
        {

            try
            {
                var container = ContainerClient();
                ItemResponse<EmployeeModel> response = await container.ReadItemAsync<EmployeeModel>(employeeId, new PartitionKey(partitionKey));
                return Ok(response.Resource);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

        }

Step 10: Create Method to Update Employee

Create the UpdateEmployee method in the EmployeeController.cs and add the following code to update  the employee by employeeId and partition key.

The CosmosDB does not support the partial update feature; rather, it actually replaces the existing item by getting the document to be updated and sending the same details to the database after fields to change or update.

       [HttpPut]
        public async Task<IActionResult> UpdateEmployee(EmployeeModel emp,string partitionKey)
        {

            try
            {

                var container = ContainerClient();
                ItemResponse<EmployeeModel> res = await container.ReadItemAsync<EmployeeModel>(emp.id, new PartitionKey(partitionKey));

                //Get Existing Item
                var existingItem = res.Resource;

                //Replace existing item values with new values 
                existingItem.Name = emp.Name;
                existingItem.Country = emp.Country;
                existingItem.City = emp.City;
                existingItem.Department = emp.Department;
                existingItem.Designation = emp.Designation;

              var updateRes=  await container.ReplaceItemAsync(existingItem, emp.id, new PartitionKey(partitionKey));

                return Ok(updateRes.Resource);

            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
          
        }

Step 11: Create Method to Delete Employee

Create the DeleteEmployee method in the EmployeeController.cs and add the following code to delete the employee by employeeId and partition key.

        [HttpDelete]
        public async Task<IActionResult> DeleteEmployee(string empId, string partitionKey)
        {

            try
            {

                var container = ContainerClient();
               var response= await container.DeleteItemAsync<EmployeeModel>(empId, new PartitionKey(partitionKey));
                return Ok(response.StatusCode);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
        }

    }

The entire code of the EmployeeController.cs class file will look like the following after adding all the methods together:

EmployeeController.cs

using EmployeeManagement.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;

namespace EmployeeManagement.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController : ControllerBase
    {
       
        // Cosmos DB details, In real use cases, these details should be configured in secure configuraion file.
        private readonly string CosmosDBAccountUri = "https://localhost:8081/";
        private readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        private readonly string CosmosDbName = "EmployeeManagementDB";
        private readonly string CosmosDbContainerName = "Employees";


        /// <summary>
        /// Commom Container Client, you can also pass the configuration paramter dynamically.
        /// </summary>
        /// <returns> Container Client </returns>
        private  Container  ContainerClient()
        {

            CosmosClient cosmosDbClient = new CosmosClient(CosmosDBAccountUri, CosmosDBAccountPrimaryKey);
            Container containerClient = cosmosDbClient.GetContainer(CosmosDbName, CosmosDbContainerName);
            return containerClient;
           
        }


        [HttpPost]
        public async Task<IActionResult> AddEmployee(EmployeeModel employee)
        {
            try
            {
                var container = ContainerClient();
                var response = await container.CreateItemAsync(employee, new PartitionKey(employee.Department));

                return Ok(response);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
               
        }

        [HttpGet]
        public async Task<IActionResult> GetEmployeeDetails()
        {
            try
            {
                var container = ContainerClient();
                var sqlQuery = "SELECT * FROM c";
                QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);
                FeedIterator<EmployeeModel> queryResultSetIterator = container.GetItemQueryIterator<EmployeeModel>(queryDefinition);


                List<EmployeeModel> employees = new List<EmployeeModel>();

                while (queryResultSetIterator.HasMoreResults)
                {
                    FeedResponse<EmployeeModel> currentResultSet = await queryResultSetIterator.ReadNextAsync();
                    foreach (EmployeeModel employee in currentResultSet)
                    {
                        employees.Add(employee);
                    }
                }

                return Ok(employees);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
           
        }
        [HttpGet]
        public async Task<IActionResult> GetEmployeeDetailsById(string employeeId,string partitionKey)
        {

            try
            {
                var container = ContainerClient();
                ItemResponse<EmployeeModel> response = await container.ReadItemAsync<EmployeeModel>(employeeId, new PartitionKey(partitionKey));
                return Ok(response.Resource);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

        }
        [HttpPut]
        public async Task<IActionResult> UpdateEmployee(EmployeeModel emp,string partitionKey)
        {

            try
            {

                var container = ContainerClient();
                ItemResponse<EmployeeModel> res = await container.ReadItemAsync<EmployeeModel>(emp.id, new PartitionKey(partitionKey));

                //Get Existing Item
                var existingItem = res.Resource;

                //Replace existing item values with new values 
                existingItem.Name = emp.Name;
                existingItem.Country = emp.Country;
                existingItem.City = emp.City;
                existingItem.Department = emp.Department;
                existingItem.Designation = emp.Designation;

              var updateRes=  await container.ReplaceItemAsync(existingItem, emp.id, new PartitionKey(partitionKey));

                return Ok(updateRes.Resource);

            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
          
        }

        [HttpDelete]
        public async Task<IActionResult> DeleteEmployee(string empId, string partitionKey)
        {

            try
            {

                var container = ContainerClient();
               var response= await container.DeleteItemAsync<EmployeeModel>(empId, new PartitionKey(partitionKey));
                return Ok(response.StatusCode);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
        }

    }
}

Now, we have all the code and required configuration to work with Azure CosmosDB in our sample application.

Step 12: Run the ASP.NET Core API Application

Now press Keyboard F5 or the Visual Studio Run button to run the application. After running the application, the following screen will be shown in the browser with swagger UI having all the methods which we have created in our ASP.NET core web API, as shown in the following screenshot:


Now, we will test the functionality by using the Swagger UI, but you can use Postman or any other tool to execute the API endpoints.

Step 13: Azure Cosmos DB CRUD Demo 

Watch the following animated image to see how the insert, read, update, and delete operations of Azure Cosmos DB work.

Add Employees


Get List of Employees and Employee by Id




Update the Employee


Delete the Employee by Id





Download the source code from Github using the following link:

Summary

How To Connect Azure Kubernetes Cluster Using Kubectl

Connecting to an Azure Kubernetes Service (AKS) cluster is a crucial step in managing and interacting with the resources on the cluster. In this article, we will go through the process of connecting to an AKS cluster using kubectl commands with examples and the command in the console. 

Install Azure CLI

The first step is to install the Azure CLI. This tool is required to authenticate to the AKS cluster. You can install the Azure CLI by following the instructions provided by Microsoft at the following link: 

https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest

Install kubectl

Next, we need to install kubectl, which is the command-line tool for interacting with Kubernetes clusters. You can install kubectl by following the instructions provided by Kubernetes at the following link:

Authenticate to the AKS cluster

To authenticate to the AKS cluster, you will need to run the following command, replacing "myResourceGroup" and "myAKSCluster" with the appropriate values for your cluster:

az aks get-credentials --resource-group myResourceGroup --name myAKSCluster

This command will configure kubectl to use the credentials of the AKS cluster, allowing you to interact with the cluster using kubectl commands.

Verify the connection:

Once you have authenticated to the AKS cluster, you can verify the connection by running the following command:

kubectl get nodes

This command will display a list of the nodes in the AKS cluster, indicating that you have successfully connected to the cluster. The output should look something like this:


Summary

I hope from the preceding step-by-step explanation you have learned how to connect to an existing Azure Kubernetes Service (AKS) cluster using kubectl commands.

Differences between Azure Service Bus Basic, Standard and Premium Tiers

Azure Service Bus is a messaging service provided by Microsoft Azure that enables applications to communicate with one another in a reliable and scalable manner. It allows for asynchronous communication between applications, allowing them to send and receive messages without the need for a direct connection.



In this article, we will learn about the pricing model of the Azure service bus. The Azure Service Bus comes in three different tiers:
  • Basic
  • Standard
  • Premium
Each tier has its own set of features and pricing model.

Basic Tier:

  • The Basic Tier is the entry-level offering of Azure Service Bus.
  • It provides a set of core messaging capabilities, including queues, topics, and subscriptions.
  • The Basic tier is designed for simple messaging needs and is suitable for small workloads.
  • it has a pay-as-you-go pricing model, with a lower cost than the standard and premium tiers.
  • It has lower throughput and message size limits than the standard and premium tiers.
  • It does not support features such as auto-forwarding and scheduled messaging.
  • It does not have the same level of security, compliance, and governance features as the standard and premium tiers.
  • It doesn't have a built-in VNet support.

Standard Tier:

  • The Standard tier is an enhanced version of Azure Service Bus that provides additional features and capabilities than the Basic tier.
  • It provides a set of core messaging capabilities, including queues, topics, and subscriptions.
  • The Standard tier is designed for basic messaging needs and is suitable for small to medium-sized workloads.
  • It provides a shared infrastructure, which means that resources are shared with other tenants.
  • It has a pay-as-you-go pricing model and provides a set of predefined throughput units.
  • It provides features such as auto-forwarding and scheduled messaging.
  • It has better security and compliance features than the Basic Tier.
  • It supports features such as partitioning, which allows for higher throughput and message size limits than the Basic Tier.
  • It doesn't have a built-in VNet support.

Premium Tier:

  • The Premium tier is a more advanced version of Azure Service Bus with more features and capabilities than the Standard tier.
  • It provides a set of core messaging capabilities, including queues, topics, and subscriptions.
  • The Premium tier is designed for enterprise-grade messaging needs and is suitable for large-scale workloads.
  • It provides a dedicated infrastructure, which means that resources are dedicated to a specific tenant.
  • It has a consumption-based pricing model and provides a set of predefined throughput units.
  • It provides features such as auto-forwarding, scheduled messaging, and partitioning.
  • It has better security, compliance, and governance features than the Standard Tier.
  • It has built in support for VNET and private endpoint 
  • It provides enhanced performance features such as active-active replication, which allows for automatic failover and disaster recovery.

Summary

I hope the above explanation helps you understand that the Basic tier is the entry-level offering of Azure Service Bus. It's designed for simple messaging needs and is suitable for small workloads. The Standard tier provides additional features and capabilities over the Basic tier, making it suitable for small to medium-sized workloads, while the Premium tier provides the most advanced features and capabilities, making it suitable for large-scale workloads and enterprise-grade messaging needs.

What is Azure IoT Hub Device Twin

The Azure IoT Hub Device Twin allows to store and retrieve metadata about an IoT device in the cloud. This metadata, also known as "twin". This information can be used to configure and manage the device, as well as to monitor its status and troubleshoot issues. In this blog, we will take a closer look at Azure IoT Hub Device Twin and provide an example of how it can be used in a real-world scenario.

Each device twin contains the following set of properties that describe the current state of the device, as well as a set of desired properties that specify the desired state of the device.

  • Desired Properties
  • Reported Properties
  • Twin Tags

Desired Properties: 

The desired Properties in the Azure IoT Hub Device twins are the configurations and settings that the IoT solution or the application wants the device to have. These are the configurations and settings that the application wants the device to have, and it can update them by sending an update request to the IoT hub. The device can read these desired properties and apply the changes to its behaviour accordingly.

  • Desired properties are used to configure and control the behaviour of the device remotely.
  • Desired properties can be used to send new configuration settings or commands to the device.
  • The device can read the desired properties and take actions based on the new settings.
  • The application can update desired properties at any time, and the device will receive the updates and act accordingly.
  • Desired properties can be used to implement a simple form of device management, such as reboot or reset commands.
  • Desired properties can be used to update firmware, change device configuration, or update a device's behavior.
  • Desired properties are updated by the application and can be accessed by the device via the Azure IoT SDK.

Reported Properties: 

The reported properties in an Azure IoT Hub Device Twins are the device's current state and configurations.These are the properties that the device is reporting back to the IoT hub, and they can be used to monitor the status and health of the device.

  • Reported properties are used to report the device's current state and configurations.
  • Reported properties can be used to report sensor data, device status, error messages, and other information.
  • The IoT solution or the application can read reported properties to monitor the status and health of the device.
  • The device can update reported properties at any time, and the IoT hub will receive the updates and act accordingly.
  • Reported properties can be used to implement a simple form of device monitoring, such as checking if the device is online or offline.
  • Reported properties can be used to report the device's location, temperature, battery level, and other telemetry data.
  • Reported properties are updated by the device and can be accessed by the IoT solution or the application via the Azure IoT SDK.

Twin Tags:

Azure IoT Hub Device Twins also support a feature called "Twin Tags," which allows you to add metadata to the Device Twin properties, including the desired and reported properties. These tags can be used to filter, query, and identify the devices in your solution.

  • Twin tags are used to add metadata to the device's twin properties.
  • Twin tags can be used to filter, query, and identify the devices in your solution.
  • The IoT solution or the application can add tags to the Device Twin to filter and group the devices according to specific characteristics.
  • Twin tags can be used to add information such as the device's location, manufacturer, and model.
  • Twin tags can be used to filter devices based on their characteristics, such as device type, location, or firmware version.
  • Twin tags can be used to segment devices into different groups, such as test devices, production devices, or devices in a specific region.
  • Twin tags can be used to filter devices based on specific criteria, and then apply different policies or rules to each group of devices.
  • Twin tags are stored in the Azure IoT hub and can be accessed by the IoT solution or the application via the Azure IoT SDK.

Example:

Consider a smart thermostat device that is connected to the Azure IoT platform. The device twin for this device might contain the following properties:

  • Desired temperature: The temperature that the user wants the thermostat to be set to.
  • Reported temperature: The temperature that the thermostat is currently set to.
  • Battery level: The current battery level of the thermostat.
  • Firmware versionThe version of the firmware currently installed on the thermostat.
  • Twin tagsLocation (e.g. "Living Room"), Device type (e.g. "Thermostat")
The device twin uses the JSON structure, which contains two main sections:
  • Desired
  • Reported
The "desired" section contains the desired properties that are set by the cloud, and the "reported" section contains the reported properties that are reported by the device.

{
  "desired": {
    "temperature": 72,
    "thermostatMode": "Heat"
  },
  "reported": {
    "temperature": 68,
    "thermostatMode": "Cool",
    "batteryLevel": 0.75,
    "firmwareVersion": "1.0.0"
  },
  "tags": {
    "location": "Living Room",
    "deviceType": "Thermostat"
  }
}

In the preceding example, the desired temperature is set to 72 degrees and the thermostat mode is set to "heat," while the reported temperature is 68 degrees, the thermostat mode is "cool," the battery level is 0.75, and the firmware version is 1.0.0. The device twin also has two tags: location and device type.

Key Points: IoT Hub Device Twin

  • Azure IoT Hub Device Twins are JSON documents that store metadata and configurations for devices connected to an IoT hub.
  • The size of the Device Twin JSON document is limited to 8 KB.
  • The property depth is limited to 32 levels, meaning that the Device Twin JSON document can only have 32 nested levels of properties.
  • If the size of the device twin or property depth exceeds these limits, the update will fail and an error will be returned.
  • The device twin can be used to store and retrieve configuration information, such as desired properties and reported properties.
  • The desired properties are updated by the application, and the reported properties are updated by the device.
  • Desired and reported properties can also be used to implement a simple form of device management, such as reboot or reset commands.
  • The device twin is stored in the Azure IoT hub, so it will be highly available and automatically backed up.
  • The device twin is specific to the device, so it can store device-specific information like version, device model, and firmware.
  • The device twin can also be used to store the device's location, which can be useful for tracking and monitoring.

Summary

I hope the preceding explanations helped you understand that Azure IoT Device Twins are a powerful feature that allows developers to synchronise the state of their IoT devices with the cloud. Each device twin contains a set of properties that describe the current state of the device, as well as a set of desired properties that specify the desired state of the device. The desired and reported properties can be updated at any time, making it easy to keep track of the state of your devices and take appropriate actions.

Related Articles

Consistency Levels in Azure Cosmos DB with an Example

The consistency level in Azure Cosmos DB determines how quickly you can read data that has been written or inserted into the database, in other words, when you write data to Cosmos DB, the consistency level determines how long it will take for that data to be readable by other operations.

The Azure Cosmos DB has five different consistency levels, as follows:
  • Strong
  • Bounded staleness
  • Session
  • Consistent prefix
  • Eventual

Strong

This level provides the highest level of consistency, meaning that all read and write operations are guaranteed to be consistent. 
For example, if you write data to Cosmos DB and then immediately read that data, you are guaranteed to get the same data back. However, this level may result in slower performance compared to the other levels.

Bounded staleness

This level allows some degree of inconsistency in the data, but guarantees that any read operation will not return data that is more than a certain number of versions or time intervals behind the latest write.
For example, if you set the staleness to 5 minutes, any read operation will return data that is at most 5 minutes old.

Session

This level provides a consistent view of data within a single session. If a client establishes a session with Cosmos DB, all read and write operations within that session will be consistent. 
For example, if you write data to Cosmos DB and then immediately read that data within the same session, you are guaranteed to get the same data back.

Consistent prefix

This level guarantees that read operations will always return the most recent write operation, but does not guarantee that all previous write operations will be reflected in the read. 
For example, if you write data A, B, and C to Cosmos DB in that order, a read operation may return either A and B, or B and C, but not A and C.

Eventual

This level provides the lowest level of consistency, meaning that it may take some time for write operations to be reflected in read operations. This level is useful for scenarios where high availability is more important than consistency. 
For example, if you write data to Cosmos DB and then immediately read that data, you may not necessarily get the same data back, but the data you do get will eventually reflect all of the write operations

Summary

I hope, from all the examples above, you have learned about the Azure Cosmos DB consistency levels. If you like it, share it with your friends and subscribe to the blog and YouTube channel for more articles.

Related articles

What is Azure IoT Hub?

In my last article, we learned about the Azure device provisioning service, which allows us to manage IoT devices. If you have not read my previous article about the Azure device provisioning service yet, then please read it using the following link:

Now we have a platform to manage the IoT devices, but what about connecting the devices to some platform and getting the data from those connected devices? We must connect the device to some gateway platform to establish a secure connection between the cloud and the device to exchange the data. So, in this article, we will learn about the Azure IoT hub and the role of the IoT hub in managing the IoT devices' communication and telemetry data.

What is Azure IoT?

Azure IoT is the IoT gateway for IoT devices, which allows bi-directional communication between IoT devices and the cloud and from the cloud to IoT devices. Azure IoT can process the millions of IoT devices and route the messages to specific data storage platforms.

Key Advantages of Azure IoT

  • Built-in UI to manage and monitor the IoT devices
  • Capture entire device lifecycle events using the device lifecycle change event feature.
  • Allows us to upgrade the firmware of single or bulk numbers of devices using the automatic device management feature.
  • Built-in support for bidirectional communication between IoT devices and the cloud
  • The IoT hub allows us to connect edge devices and IoT devices, which means the IoT hub is capable of connecting low-powered and high-processing devices.
  • IoT devices can send telemetry data as well as connect devices over a network using the AMQP, MQTT, and HTTPS protocols to the Azure IoT hub.
  • The Azure IoT Hub has multiple device authentication mechanisms, including X509, TPM, and symmetric keys.
  • The message routing feature helps to route messages to a specific data store and data processing platform.
  • built-in support for uploading the file for a specific device, which can be used for device upgradation or storing device process-related information.
  • Azure IoT hub IoT Hub allows us to send commands to the device, which can help change the behaviour of the device using the "Cloud to Device" message feature.
  • provides the device-twinning feature for storing metadata or other information about IoT devices.
  • Azure IoT Hub is intended to be a secure platform for device communication and authentication, utilising communication protocols AMQP, MQTT, and HTTPS as well as authentication mechanisms such as X509, TPM, and symmetric keys.
  • The IoT hub provides various options to establish bi-directional communication between the cloud and devices programmatically with SDKs in C#, Java, Python, Node.js, and Android, as well as an API for the IoT hub.
  • allows you to enable or disable the connected IoT devices.
  • built-in support for routing and filtering the messages to the other services.

Creating An Azure IoT Hub Using Azure Portal


Azure IoT Hub can be created using:
  • Azure CLI
  • SDK
  • API
  • ARM
  • Azure portal 
In this article, we will be creating an IoT hub using the portal so we can avoid confusion for beginners. Now let’s start creating the azure IoT hub step-by-step via the Azure portal.

Prerequisites

 
To create any Azure service, we need an active Azure subscription, whether it’s a paid or trial subscription. I am assuming you have an active Azure subscription

Step 1: Go to the Azure Portal

Navigate to the portal.azure.com using your browser and login into the portal with valid credentials, as shown in the following image:


After a successful login, the page will be redirected to the Azure portal, by default, the dashboard page is set as:

Step 2: Create Azure IoT

Find the create resource option which can be found on the left top side of the portal as shown in the following image or follow any other option which you may know to create the resource (service) in the Azure portal:



Click on the left side option to create a resource & type IoT hub into the populated search box, it will pop up the following screen as:



As shown in the preceding image click on the create button, it will show the following screen:



Provide required details as shown in the preceding image:
  • Subscription: Choose the available azure subscription which you want to use for creating service from drop-down list
  • Resource Group: Choose an existing resource group or create a new resource group that you may want to use.
  • Region: Choose the deployment location for IoT hub device provisioning from the given list. However, the device provisioning service is global and associated with any specific location, but you must specify a location for the resource group where the metadata associated with the service profile will reside.
  • IoT Hub Name: Name of the IoT hub service which must contain only alphanumeric characters or a hyphen.
After providing all the basic required details, click to review and create the IoT hub, which skips the remaining steps, or click to choose the next step, networking. It shows the following screen to configure networking:



In the above image, we choose the connectivity method for the IoT hub which decides which network the devices can connect to the IoT hub, there are three methods:
  • Public Endpoint all Network
  • Public Endpoint selected IP addresses
  • Private Endpoint 
Public EndPoint all Network

This option allows us to connect devices to the IoT hub on all public networks for whoever has access to public URI and the required credentials.

Public Endpoint selected IP addresses

Even you have a public endpoint (URI) but want to restrict devices, you should connect from a specific IP address. Then you can define the range of IP addresses. The IoT hub allows you to connect only to devices that fall within the defined IP address range. This option gives the useful feature to allow only known networks to connect to the devices

Private EndPoint

This is the URI or endpoint which allows us to connect devices over the private network, which gives the robust security between devices and IoT hub communication
Once you choose your intended connectivity method, click on the next step which shows the step to configure the scalability of the IoT hub as:


The preceding management step allows us to define the scalability and security of the IoT hub with the help of the following options:
  • Pricing and Scale Tier
  • IoT Hub Units
  • Defender

Pricing and Scale Tier

 
There are different types of pricing and scale tiers that decide how many messages the device sends to the IoT hub per day and what feature does it supports. The features and message frequency of IoT hub can differ based on the pricing and scale tier. The pricing tiers are categorized as:


Free Tier

 
The F1 is the free tier by using you can use the free tier of IoT hub for your learning and check how IoT hub works. it allows 8000 messages per day with limited feature

Basic Tier


The basic tier is sub-categorized into the three types as
  • B1
  • B2
  • B3
Basic tiers are suitable for development activities but you can not get all the features in this pricing and scale tier.


Standard Tier


The standard pricing and scale tier provides the most advanced features and scales for the incoming IoT messages, The standard tier subcategorized into the three types as:
  • S1
  • S2
  • S3 
These tiers are most suitable for a production environment where hyper scalability and advanced security are required. Once you choose the configuration for the IoT hub, click on the next step tags, which shows the following screen:



The tagging helps to identify or categorize the services across the line of applications, after providing tags details, click on the next step review and create, it will show the following screen to review the details before creating the service:


After reviewing details, click on the create button, it will take some time to create the service. Once the service is created, the status can be notified on the notification icon as shown in the following image: 


Now click on the Go to resource button, you will be redirected to the newly created IoT hub service as shown in the following image:


Let’s learn about the preceding Azure IoT hub key sections in brief, listed below:
  • Overview
  • Certificates
  • Built-in Endpoints
  • Query Explorer
  • IoT Devices
  • Automatic Device Management
  • Messaging
  • Security
  • Monitoring
Overview
 
The overview section of the IoT hub is like a dashboard where you can see an overview of the service details, including the charts for incoming messages, status, etc.

Certificates
 
This section allows to add and save the device certificates which can be assigned to the devices during creating or adding the devices to the IoT hub.

Built-in Endpoints
 
This section contains the details which allow us to use the IoT hub as an event hub. The event hub compatible connectionString gives almost the same functionality as an event hub without creating any instance of the event hub.

Query Explorer
 
This section allows us to query devices that reside in the IoT hub. This feature is useful to query any device from the millions of devices from the IoT hub.

IoT Devices
 
This section lets you add the different types of IoT devices and related configuration.

Automatic Device Management
 
This section allows us to upgrade the firmware of individual or bulk of IoT devices based on the properties of the device such as tags or deviceId.

Messaging
 
This feature allows to capture the IoT device messages and their related events also you can route the messages to any other service such as data store etc.

Security
 
This section allows to secure the IoT devices using the IoT defender feature and create the security-related alerts

Monitoring

This section allows to monitor the logs related to the IoT hub, you can set any filter or rule for monitoring and create the alerts

Summary

I hope this article was useful for understanding the basics of the Azure IoT hub service.

Articles you may interested

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode