This article will show how to configure and use CosmoDB on an ASP.Net MVC web application

The tasks will be stored as JSON documents in Azure Cosmos DB

Download code here: https://code.msdn.microsoft.com/ASPNET-with-CosmoDB-5adc63c8/file/179882/1/WebApp.zip 

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 ASP.NET MVC Web Application

Go to Visual StudioFile New Project menu, expand the Web category, and pick ASP.NET Web Application like on the image below

Select the template MVC:

STEP 3 - Create CosmoDB on Azure Portal

Go to Azure Portal an select Database -> Azure Cosmo DB

Fill the data requested and select the option Create

After CosmoDB was created, we can access the Keys that will be used in our web app.

For that select your database, and on the options panel select the option Keys. All the necessary keys will be created as you can see on the image below.

STEP 4 - Configure CosmoDB on WebApp

Add new Nuget package to your application as you can see on the image below.

Create your MVC:

  • We create a car model with 3 properties
C#
Editar Script|Remove
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using Newtonsoft.Json; 
 
namespace WebApp.Models 
{ 
    public class Car 
    { 
        [JsonProperty(PropertyName = "id")] 
        public string Id { getset; } 
 
        [JsonProperty(PropertyName = "model")] 
        public string Model { getset; } 
 
        [JsonProperty(PropertyName = "Year")] 
        public string Year { getset; } 
    } 
}
 
  • Add a CarController
  • And two views configured like this:
    • List View

  • Create View

Like the list view, only need to change ViewName and Template associated (on this case), we must use the Create Template

This is the final structure of our solution:

To run this web app we need to create a generic repository, to connect to Azure CosmoDB. Check the code below.

C#
Editar Script|Remove
using Microsoft.Azure.Documents; 
using Microsoft.Azure.Documents.Client; 
using Microsoft.Azure.Documents.Linq; 
using System.Configuration; 
using System.Linq.Expressions; 
using System.Threading.Tasks; 
using System.Net; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
 
namespace WebApp 
{ 
    public static class Repository<T> where T : class 
    { 
        private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"]; 
        private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"]; 
        private static DocumentClient client; 
 
        public static void Initialize() 
        { 
            client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]); 
            CreateDatabaseIfNotExistsAsync().Wait(); 
            CreateCollectionIfNotExistsAsync().Wait(); 
        } 
 
        private static async Task CreateDatabaseIfNotExistsAsync() 
        { 
            try 
            { 
                await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId)); 
            } 
            catch (DocumentClientException e) 
            { 
                if (e.StatusCode == System.Net.HttpStatusCode.NotFound) 
                { 
                    await client.CreateDatabaseAsync(new Database { Id = DatabaseId }); 
                } 
                else 
                { 
                    throw; 
                } 
            } 
        } 
 
        private static async Task CreateCollectionIfNotExistsAsync() 
        { 
            try 
            { 
                await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId)); 
            } 
            catch (DocumentClientException e) 
            { 
                if (e.StatusCode == System.Net.HttpStatusCode.NotFound) 
                { 
                    await client.CreateDocumentCollectionAsync( 
                        UriFactory.CreateDatabaseUri(DatabaseId), 
                        new DocumentCollection { Id = CollectionId }, 
                        new RequestOptions { OfferThroughput = 1000 }); 
                } 
                else 
                { 
                    throw; 
                } 
            } 
        } 
 
        public static async Task<IEnumerable<T>> GetItemsAsync() 
        { 
            IDocumentQuery<T> query = client.CreateDocumentQuery<T>( 
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId)) 
                .AsDocumentQuery(); 
 
            List<T> results = new List<T>(); 
            while (query.HasMoreResults) 
            { 
                results.AddRange(await query.ExecuteNextAsync<T>()); 
            } 
 
            return results; 
        } 
 
        public static async Task<Document> CreateItemAsync(T item) 
        { 
            return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item); 
        } 
    } 
}
For more information, please consult the official link from Microsoft: https://docs.microsoft.com/en-us/azure/cosmos-db/documentdb-dotnet-application

STEP 5 - Results

You can now, access to your CosmoDB on Azure portal, and check the data created

As you can see, all the data is in JSON format

Resources

Official Site: https://docs.microsoft.com/en-us/azure/cosmos-db/documentdb-dotnet-application

My personal blog: http://joaoeduardosousa.wordpress.com/