Access Cosmos DB data from an MVC Application

Azure Cosmos DB is a fully managed globally distributed multi-model data service. Developers can leverage its capabilities of low latency, 99.99% high availability, predictable throughput, and multiple well-defined consistency models to develop applications that need faster reads and write from anywhere in the world.

Developers can harness the power of Cosmos DB to develop various applications to cater to the need of enterprises. An MVC application is one good example to showcase capabilities for the multi-model data service.

In the article, we will build an MVC application to access and display data from Cosmos DB. Inserting data from the application into Cosmos DB is not in the scope of this post. So let’s begin.

Prerequisites

  1. An Azure Subscription
  2. Visual Studio for development

Create Storage Account

This storage account is where we will back up Azure Cosmos DB data

  • Search Storage Accounts and click Add
  • Provide details and click Review + Create
  • Click on Containers
  • Click on +Container
  • Provide Name and click Create
  • Insert some sample documents with below schema in the container
{
    "id" = 001,
    "machineName": "machine01",
    "serverName": "server01",
    "process": "manual",
    "status": "active"
}

Create an MVC Web Application

  • Open Visual Studio 2019 on your computer.
  • On the File menu, select New, and then choose Project.
  • In the New Project dialog, select Templates / Visual C# / Web/ ASP.NET Web Application (.NET Framework),
  • Name your project, and then select MVC and then click OK.
  • In the Solution Explorer, right click on your new web application, and then click Manage NuGet Packages.
  • In the NuGet tab, click Browse, and search Azure DocumentDB and click Install.

Connect to an Azure Cosmos DB account

  • Create ServerDetails entity class in Models folder
public class ServerDetails
{
    public string MachineName { get; set; }
    public string ServerName { get; set; }
    public string Process { get; set; }

    public string Status { get; set; }

}
  • In HomeController class add ServerDetails Action 
public ActionResult ServerDetails()
{
    return View();
}
  • Then, we need to add a View to the employee action. Right Click on View > Add View
  • Add these references in HomeController.cs
using System.Net;  
using Microsoft.Azure.Documents;  
using Microsoft.Azure.Documents.Client;
  • Add these two constants in constructor 
string EndpointUrl;  
    private string PrimaryKey;  
    private DocumentClient client;  
    public HomeController(){  
        EndpointUrl = "<your endpoint URL>";  
        PrimaryKey = "<your primary key>"; }  

Get Azure Cosmos URI and Primary Key

  • Go to your Azure Cosmos DB account, and then click Keys.
  • Copy URI and Endpoint
  • Replace the values in Placeholder
public HomeController()  
{  
    EndpointUrl = "<https://xxx.documents.azure.com:443/>";  
    PrimaryKey = "<xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>”  
  }  
  • Create a new instance of the DocumentClient.
public  HomeController()  
    {  
        EndpointUrl = "https:// xxxxx.documents.azure.com:443/";  
        PrimaryKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";  
        client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);  
          
    }  

Query Azure Cosmos DB

  • Add below code to HomeController.cs
public ActionResult ServerDetails()
        {
            FeedOptions queryOptions = new FeedOptions { EnableCrossPartitionQuery = true , MaxItemCount = -1 };
            IQueryable<ServerDetails> serverQuery = this.client.CreateDocumentQuery<ServerDetails>(
                    UriFactory.CreateDocumentCollectionUri("DemoDB", "DemoContainer"), queryOptions)
                    .Where(f => f.Status == "Disconnect");
            return View(serverQuery);
        } 

This post was a simple demonstration of how to access the data. Developers can achieve much more by leveraging the well-defined consistency models and low latency. Also, the multi-model capability of the service gives an edge over other database services to design and develop as per the data structure.

So explore Cosmos DB and keep learning!!!



Categories: ASP.Net, Azure, Azure CosmosDB

Tags: , ,

Leave a Reply