Share via


ASP.NET - Connect to CosmoDB Azure Database

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 Studio’s File New Project menu, expand the Web category, and pick ASP.NET Web Application like on the image below

https://code.msdn.microsoft.com/site/view/file/179873/1/cosmodb_1.png

Select the template MVC:

https://code.msdn.microsoft.com/site/view/file/179874/1/cosmodb_2.png

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

https://code.msdn.microsoft.com/site/view/file/179875/1/cosmodb_3.png

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.

https://code.msdn.microsoft.com/site/view/file/179876/1/cosmodb_4.png

STEP 4 - Configure CosmoDB on WebApp

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

https://code.msdn.microsoft.com/site/view/file/179877/1/cosmodb_5.png

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 { get; set; } 
 
        [JsonProperty(PropertyName = "model")] 
        public string Model { get; set; } 
 
        [JsonProperty(PropertyName = "Year")] 
        public string Year { get; set; } 
    } 
}

 

  • Add a CarController
  • And two views configured like this:
    • List View

https://code.msdn.microsoft.com/site/view/file/179878/1/cosmodb_6.png

  • 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:

https://code.msdn.microsoft.com/site/view/file/179879/1/cosmodb_7.png

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: /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

https://code.msdn.microsoft.com/site/view/file/179880/1/cosmodb_8.png

https://code.msdn.microsoft.com/site/view/file/179881/1/cosmodb_9.png

Resources

Official Site: /en-us/azure/cosmos-db/documentdb-dotnet-application

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