Using Microsoft Azure DocumentDB In An ASP.NET MVC Application

Scope

The following article demonstrates use of Microsoft Azure DocumentDB in an ASP.NET MVC Application.

Introduction


Azure DocumentDB is a NoSQL storage service which stores JSON documents natively and provides indexing capabilities along with other interesting features.

The following are some of the key terms used in this article:

Collection

A collection is a named logical container for documents.

A database may contain zero or more named collections and each collection consists of zero or more JSON documents.

Being schema-free, the documents in a collection do not need to share the same structure or fields.

Since collections are application resources, they can be authorized using either the master key or resource keys.

DocumentClient

The DocumentClient provides a client-side logical representation of the Azure DocumentDB service. This client is used to configure and execute requests against the service.

Creating a DocumentDB Account

Please refer to this article to create and setup a DocumentDB Account on Microsoft Azure.

Getting Started

To get started, create a new ASP.NET MVC project in Visual Studio and add the DocumentDB NuGet package by going to Tools NuGet Package Manager > package Manager Console and key in the following:

Install-Package Microsoft.Azure.Documents.Client -Pre

mvc template

console

The Web.Config File

Retrieve the endpoint(URI) and the authKey (Primary/Secondary key) from your DocumentDb Account and add them in the Web Config file.

The keys database and collection represents the name of the database and collections that shall be used in your applications respectively.

Config File
  1. <add key="endpoint" value="xxx" />    
  2. <add key="authKey" value="xxx" />    
  3. <add key="database" value="NotesCb" />    
  4. <add key="collection" value="NotesCOllectionCb" /> sCOllectionCb"   
Create DocumentDB Repository Class

This is where all the codes that shall be used to communicate with Azure DocumentDB shall be found.
  1. Retrieve the DatabaseId and CollectionId from the Web.Config file
    1. /// <summary>  
    2. /// Retrieve the Database ID to use from the Web Config  
    3. /// </summary>  
    4. private static string databaseId;  
    5. private static String DatabaseId  
    6. {  
    7.     get  
    8.     {  
    9.         if (string.IsNullOrEmpty(databaseId))  
    10.         {  
    11.             databaseId = ConfigurationManager.AppSettings["database"];  
    12.         }  
    13.    
    14.         return databaseId;  
    15.     }  
    16. }  
    17.    
    18. /// <summary>  
    19. /// Retrieves the Collection to use from Web Config  
    20. /// </summary>  
    21. private static string collectionId;  
    22. private static String CollectionId  
    23. {  
    24.     get  
    25.     {  
    26.         if (string.IsNullOrEmpty(collectionId))  
    27.         {  
    28.             collectionId = ConfigurationManager.AppSettings["collection"];  
    29.         }  
    30.    
    31.         return collectionId;  
    32.     }  
    33. }  
  2. Retrieve the DocumentClient

    The document Client provides a client-side logical representation of the Azure DocumentDB service.

    This client is used to configure and execute requests against the service.
    1. private static DocumentClient client;  
    2. private static DocumentClient Client  
    3. {  
    4.     get  
    5.     {  
    6.         if (client == null)  
    7.         {  
    8.             string endpoint = ConfigurationManager.AppSettings["endpoint"];  
    9.             string authKey = ConfigurationManager.AppSettings["authKey"];  
    10.             Uri endpointUri = new Uri(endpoint);  
    11.             client = new DocumentClient(endpointUri, authKey);  
    12.         }  
    13.    
    14.         return client;  
    15.     }  
    16. }  
  3. Get the database that shall be used

    If no database is found, the method ReadOrCreateDatabase() is called, to verify if the database exist and creates if it does not exist.
    1. private static Database database;  
    2. private static Database Database  
    3. {  
    4.     get  
    5.     {  
    6.         if (database == null)  
    7.         {  
    8.             database = ReadOrCreateDatabase();  
    9.         }  
    10.    
    11.         return database;  
    12.     }  
    13. }  
    14.    
    15. private static Database ReadOrCreateDatabase()  
    16. {  
    17.    
    18.     var db = Client.CreateDatabaseQuery()  
    19.                     .Where(d => d.Id == DatabaseId)  
    20.                     .AsEnumerable()  
    21.                     .FirstOrDefault();  
    22.    
    23.     if (db == null)  
    24.     {  
    25.         db = Client.CreateDatabaseAsync(new Database { Id = DatabaseId }).Result;  
    26.     }  
    27.    
    28.     return db;  
    29. }  
  4. Get the DoucmentCollection which will be used

    A collection is a named logical container for documents.

    A database may contain zero or more named collections and each collection consists of zero or more JSON documents.

    If the required collection is not found, the method ReadOrCreateCollection is called that creates it.
    1. private static DocumentCollection collection;    
    2. private static DocumentCollection Collection    
    3. {    
    4.     get    
    5.     {    
    6.         if (collection == null)    
    7.         {    
    8.             collection = ReadOrCreateCollection(Database.SelfLink);    
    9.         }    
    10.      
    11.         return collection;    
    12.     }    
    13. }    
    14.      
    15. private static DocumentCollection ReadOrCreateCollection(string databaseLink)    
    16. {    
    17.      
    18.     var col = Client.CreateDocumentCollectionQuery(databaseLink)    
    19.                       .Where(c => c.Id == CollectionId)    
    20.                       .AsEnumerable()    
    21.                       .FirstOrDefault();    
    22.      
    23.     if (col == null)    
    24.     {    
    25.         col = Client.CreateDocumentCollectionAsync(databaseLink, new DocumentCollection { Id = CollectionId }).Result;    
    26.     }    
    27.      
    28.     return col;    
    29. }   
Define the Model
  1. public class Note    
  2. {    
  3.    [JsonProperty(PropertyName = "id")]    
  4.    public string Id { getset; }    
  5.    public string Title { getset; }    
  6.    public string Description { getset; }    
  7. }   
Add the Controller
  • Right-Click on Controller, then Add and click Controller.
  • Select MVC5 Controller - Empty.
  • Call it the NoteController.

    MVC5 Controller

    Controller
Generate the Views

a. Create

  • Right-Click on Views, Note, then Add View.

  • Set the parameters as in the following image and click Add.

    Generate the Views

b. Edit

  • Right-Click on Views, Note and Add View.

  • Set the parameters as in the following image and click Add.

    Add View

c. Index

  • Right click on Views, Note, then Add View.

  • Set the parameters as in the following image and click Add.

    Set the parameters

d. Details

  • Right click on Views, Note and then Add View.

  • Set the parameters as in the following image and click Add.

    Click on Add
Implement the Create Page

This allows the user to add a new note and save it in the Document Database.

In the note controller, add the following code to redirect the user to the create page on the Create Action. 
  1. public ActionResult Create()  
  2. {  
  3.     return View();  
  4. }  
Implement the Create Page

The next step is to implement the method that shall be triggered when the save button is clicked.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public async Task<ActionResult> Create([Bind(Include = "Id,Title,Description")] Note note)  
  4. {  
  5.     if (ModelState.IsValid)  
  6.     {  
  7.         await DocumentDBRepository.CreateItemAsync(note);  
  8.         //return RedirectToAction("Index");  
  9.         return RedirectToAction("Create");  
  10.            
  11.     }  
  12.     return View(note);  
  13. }  
Notice that the Redirect to the Index page is commented as it has not been created at this stage.

The method CreateItemAsync needs to be added to the DocumentRespository which performs the insert.
  1. //Create  
  2. public static async Task<Document> CreateItemAsync(Note note)  
  3. {  
  4.     return await Client.CreateDocumentAsync(Collection.SelfLink, note);  
  5. }  
CreateDocument

When clicking on Save, the following should happen.

a. Create the Database

Create the Database

b. Create the Collection

create the Collection

c. Create the Document

Create the Document

Implement the Index Page


In the Note Controller, replace the contents of the Index method with the following:
  1. public ActionResult Edit(string id)  
  2. {  
  3.     if (id == null)  
  4.     {  
  5.         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  6.     }  
  7.    
  8.     Note note = (Note)DocumentDBRepository.GetNote(id);  
  9.     if (note == null)  
  10.     {  
  11.         return HttpNotFound();  
  12.     }  
  13.    
  14.     return View(note);  
  15. }  
The Index page now displays a list of notes.

Index  

Implement the Edit Page

a. In the controller, implement the following method which fetch the selected note to edit and returns it to the page to display.
  1. public ActionResult Edit(string id)  
  2. {  
  3.     if (id == null)  
  4.     {  
  5.         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  6.     }  
  7.    
  8.     Note note = (Note)DocumentDBRepository.GetNote(id);  
  9.     if (note == null)  
  10.     {  
  11.         return HttpNotFound();  
  12.     }  
  13.    
  14.     return View(note);  
  15. }  
b. In the repository, implement the GetNote method, which returns a document based on its ID
  1. public static Note GetNote(string id)  
  2. {  
  3.     return Client.CreateDocumentQuery<Note>(Collection.DocumentsLink)  
  4.                 .Where(d => d.Id == id)  
  5.                 .AsEnumerable()  
  6.                 .FirstOrDefault();  
  7. }  
At this point, when clicking on Edit from the Index page, the selected note is displayed.
Edit from the Index page

c. In the controller, implement the edit method that shall be triggered when clicking on the save button.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public async Task<ActionResult> Edit([Bind(Include = "Id,Title,Description")] Note note)  
  4. {  
  5.     if (ModelState.IsValid)  
  6.     {  
  7.         await DocumentDBRepository.UpdateNoteAsync(note);  
  8.         return RedirectToAction("Index");  
  9.     }  
  10.    
  11.     return View(note);  
  12. }  
d. In the repository, implement the UpdateNoteAsync, which replace the current document with the updated one.
  1. public static async Task<Document> UpdateNoteAsync(Note note)    
  2. {    
  3.     Document doc = Client.CreateDocumentQuery(Collection.DocumentsLink)    
  4.                         .Where(d => d.Id == note.Id)    
  5.                         .AsEnumerable()    
  6.                         .FirstOrDefault();    
  7.      
  8.     return await Client.ReplaceDocumentAsync(doc.SelfLink, note);    
  9. }  
Implement the Details Page

In the Controller, add the following method. It calls the GetNote method implemented for the Edit part and returns the required document.
  1. public ActionResult Details(string id)  
  2. {  
  3.    
  4.     if (id == null)  
  5.     {  
  6.         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  7.     }  
  8.    
  9.     Note note = (Note)DocumentDBRepository.GetNote(id);  
  10.     if (note == null)  
  11.     {  
  12.         return HttpNotFound();  
  13.     }  
  14.    
  15.     return View(note);  
  16.    
  17. }  
Details Page

Implement the Delete Method

Add the method Delete in the controller. It calls the Method DeleteNote in the Controller and returns the user to the Index page.
  1. public async Task<ActionResult> Delete([Bind(Include = "Id")] Note note)  
  2. {  
  3.     if (ModelState.IsValid)  
  4.     {  
  5.         await DocumentDBRepository.DeleteNote(note);  
  6.         return RedirectToAction("Index");  
  7.     }  
  8.    
  9.     return View(note);  
  10. }  
See Also


Similar Articles