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. return databaseId;
    14. }
    15. }
    16. /// <summary>
    17. /// Retrieves the Collection to use from Web Config
    18. /// </summary>
    19. private static string collectionId;
    20. private static String CollectionId
    21. {
    22. get
    23. {
    24. if (string.IsNullOrEmpty(collectionId))
    25. {
    26. collectionId = ConfigurationManager.AppSettings["collection"];
    27. }
    28. return collectionId;
    29. }
    30. }
  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. return client;
    14. }
    15. }
  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. return database;
    11. }
    12. }
    13. private static Database ReadOrCreateDatabase()
    14. {
    15. var db = Client.CreateDatabaseQuery()
    16. .Where(d => d.Id == DatabaseId)
    17. .AsEnumerable()
    18. .FirstOrDefault();
    19. if (db == null)
    20. {
    21. db = Client.CreateDatabaseAsync(new Database { Id = DatabaseId }).Result;
    22. }
    23. return db;
    24. }
  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. return collection;
    11. }
    12. }
    13. private static DocumentCollection ReadOrCreateCollection(string databaseLink)
    14. {
    15. var col = Client.CreateDocumentCollectionQuery(databaseLink)
    16. .Where(c => c.Id == CollectionId)
    17. .AsEnumerable()
    18. .FirstOrDefault();
    19. if (col == null)
    20. {
    21. col = Client.CreateDocumentCollectionAsync(databaseLink, new DocumentCollection { Id = CollectionId }).Result;
    22. }
    23. return col;
    24. }
Define the Model
  1. public class Note
  2. {
  3. [JsonProperty(PropertyName = "id")]
  4. public string Id { get; set; }
  5. public string Title { get; set; }
  6. public string Description { get; set; }
  7. }
Add the Controller
Generate the Views

a. Create

b. Edit

c. Index

d. Details

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. return View(note);
  12. }
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. Note note = (Note)DocumentDBRepository.GetNote(id);
  8. if (note == null)
  9. {
  10. return HttpNotFound();
  11. }
  12. return View(note);
  13. }
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. Note note = (Note)DocumentDBRepository.GetNote(id);
  8. if (note == null)
  9. {
  10. return HttpNotFound();
  11. }
  12. return View(note);
  13. }
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. return View(note);
  11. }
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. return await Client.ReplaceDocumentAsync(doc.SelfLink, note);
  8. }
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. if (id == null)
  4. {
  5. return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  6. }
  7. Note note = (Note)DocumentDBRepository.GetNote(id);
  8. if (note == null)
  9. {
  10. return HttpNotFound();
  11. }
  12. return View(note);
  13. }
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. return View(note);
  9. }
See Also