ASP.NET - Connect To Azure Cosmos DB

Introduction 

 
This article will show how to configure and use CosmoDB in an ASP.Net MVC web application. The tasks will be stored as JSON documents in Azure Cosmos DB.
 
STEP 1 - Make sure you have installed the prerequisites
 
Without these requisites, the application will not run.
  • Visual Studio 2017
  • CosmoDB configuration on Azure Portal
STEP 2 - Create an ASP.NET MVC Web Application
 
Go to Visual Studio’s File >> New Project menu, expand the Web category, and pick ASP.NET Web Application.
 
Azure CosmoDB
 
Select the template as MVC.
 
Azure CosmoDB
 
STEP 3 - Create Cosmos DB on Azure Portal
 
Go to the Azure portal and select Database -> Azure Cosmo DB. Fill in the requested data and select the "Create" option.
 
Azure CosmoDB
 
After Cosmos DB is created, we can access the keys that will be used in our web app. For that, select your database and in the options panel, select "Keys". All the necessary keys will be created as you can see in the image below.
 
Azure CosmoDB
 
STEP 4 - Configure Cosmos DB on WebApp
 
Add a new NuGet package, "Microsoft.Azure.DocumentDB", to your application.
 
Azure CosmoDB
 
Create your MVC.
  • We create a car Model with 3 properties.
    1. using System;   
    2. using System.Collections.Generic;   
    3. using System.Linq;   
    4. using System.Web;   
    5. using Newtonsoft.Json;   
    6.    
    7. namespace WebApp.Models   
    8. {   
    9.     public class Car   
    10.     {   
    11.         [JsonProperty(PropertyName = "id")]   
    12.         public string Id { get; set; }   
    13.    
    14.         [JsonProperty(PropertyName = "model")]   
    15.         public string Model { get; set; }   
    16.    
    17.         [JsonProperty(PropertyName = "Year")]   
    18.         public string Year { get; set; }   
    19.     }   
    20. }  
  • Add a CarController.
  • And two Views configured like this,
     
    • List View
       
      Azure CosmoDB
       
  • Create View
Like the list view that only needs to change the ViewName and Template associated (in this case), we must use the "Create Template".
 
This is the final structure of our solution.
 
Azure CosmoDB
 
To run this web app, we need to create a generic repository to connect to Azure Cosmos DB. Check the code below.
 
C#
  1. using Microsoft.Azure.Documents;   
  2. using Microsoft.Azure.Documents.Client;   
  3. using Microsoft.Azure.Documents.Linq;   
  4. using System.Configuration;   
  5. using System.Linq.Expressions;   
  6. using System.Threading.Tasks;   
  7. using System.Net;   
  8. using System;   
  9. using System.Collections.Generic;   
  10. using System.Linq;   
  11.    
  12. namespace WebApp   
  13. {   
  14.     public static class Repository<T> where T : class   
  15.     {   
  16.         private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"];   
  17.         private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"];   
  18.         private static DocumentClient client;   
  19.    
  20.         public static void Initialize()   
  21.         {   
  22.             client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);   
  23.             CreateDatabaseIfNotExistsAsync().Wait();   
  24.             CreateCollectionIfNotExistsAsync().Wait();   
  25.         }   
  26.    
  27.         private static async Task CreateDatabaseIfNotExistsAsync()   
  28.         {   
  29.             try   
  30.             {   
  31.                 await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));   
  32.             }   
  33.             catch (DocumentClientException e)   
  34.             {   
  35.                 if (e.StatusCode == System.Net.HttpStatusCode.NotFound)   
  36.                 {   
  37.                     await client.CreateDatabaseAsync(new Database { Id = DatabaseId });   
  38.                 }   
  39.                 else   
  40.                 {   
  41.                     throw;   
  42.                 }   
  43.             }   
  44.         }   
  45.    
  46.         private static async Task CreateCollectionIfNotExistsAsync()   
  47.         {   
  48.             try   
  49.             {   
  50.                 await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));   
  51.             }   
  52.             catch (DocumentClientException e)   
  53.             {   
  54.                 if (e.StatusCode == System.Net.HttpStatusCode.NotFound)   
  55.                 {   
  56.                     await client.CreateDocumentCollectionAsync(   
  57.                         UriFactory.CreateDatabaseUri(DatabaseId),   
  58.                         new DocumentCollection { Id = CollectionId },   
  59.                         new RequestOptions { OfferThroughput = 1000 });   
  60.                 }   
  61.                 else   
  62.                 {   
  63.                     throw;   
  64.                 }   
  65.             }   
  66.         }   
  67.    
  68.         public static async Task<IEnumerable<T>> GetItemsAsync()   
  69.         {   
  70.             IDocumentQuery<T> query = client.CreateDocumentQuery<T>(   
  71.                 UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId))   
  72.                 .AsDocumentQuery();   
  73.    
  74.             List<T> results = new List<T>();   
  75.             while (query.HasMoreResults)   
  76.             {   
  77.                 results.AddRange(await query.ExecuteNextAsync<T>());   
  78.             }   
  79.    
  80.             return results;   
  81.         }   
  82.    
  83.         public static async Task<Document> CreateItemAsync(T item)   
  84.         {   
  85.             return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item);   
  86.         }   
  87.     }   
  88. }  
For more information, please visit the official link from Microsoft.
 
STEP 5 - Results
 
You can now access your Cosmos DB on the Azure portal and check the data created. As you can see, all the data is in JSON format.
 
Azure CosmoDB
 
Azure CosmoDB
 
Resources


Similar Articles