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.
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.
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. namespace WebApp
  12. {
  13. public static class Repository<T> where T : class
  14. {
  15. private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"];
  16. private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"];
  17. private static DocumentClient client;
  18. public static void Initialize()
  19. {
  20. client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
  21. CreateDatabaseIfNotExistsAsync().Wait();
  22. CreateCollectionIfNotExistsAsync().Wait();
  23. }
  24. private static async Task CreateDatabaseIfNotExistsAsync()
  25. {
  26. try
  27. {
  28. await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
  29. }
  30. catch (DocumentClientException e)
  31. {
  32. if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
  33. {
  34. await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
  35. }
  36. else
  37. {
  38. throw;
  39. }
  40. }
  41. }
  42. private static async Task CreateCollectionIfNotExistsAsync()
  43. {
  44. try
  45. {
  46. await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));
  47. }
  48. catch (DocumentClientException e)
  49. {
  50. if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
  51. {
  52. await client.CreateDocumentCollectionAsync(
  53. UriFactory.CreateDatabaseUri(DatabaseId),
  54. new DocumentCollection { Id = CollectionId },
  55. new RequestOptions { OfferThroughput = 1000 });
  56. }
  57. else
  58. {
  59. throw;
  60. }
  61. }
  62. }
  63. public static async Task<IEnumerable<T>> GetItemsAsync()
  64. {
  65. IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
  66. UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId))
  67. .AsDocumentQuery();
  68. List<T> results = new List<T>();
  69. while (query.HasMoreResults)
  70. {
  71. results.AddRange(await query.ExecuteNextAsync<T>());
  72. }
  73. return results;
  74. }
  75. public static async Task<Document> CreateItemAsync(T item)
  76. {
  77. return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item);
  78. }
  79. }
  80. }
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