Professional Documents
Culture Documents
To highlight how you can efficiently leverage Azure Cosmos DB to store and query JSON
documents, this tutorial will provides an end-to-end walk-through showing you how to build a todo
app using Azure Cosmos DB. The tasks will be stored as JSON documents in Azure Cosmos DB.
3. In the Create Azure Cosmos DB Account page, enter the settings for the new
Azure Cosmos DB account.
4. Then, click on the Review + Create button. Lastly, if the information correct, click
the Create button.
5. The account creation takes a few minutes. Wait for the portal to display the
“Congratulation! Your Azure Cosmos DB Account was created” page.
6. Now, navigate to the Azure Cosmos DB account page, and click Keys, as these
values are used in the web application you create next.
7. Now, create a new ASP .NET Core Web Application from the ground-up.
1. Open Visual Studio. From the main menu, select File > New > Project.
2. In the New Project dialog box, select Web > ASP.NET Core Web
Application > Todo. Then select OK.
3. In the New ASP.NET Core Web Application dialog box, select .NET
Core > ASP.NET Core 2.0 > Web Application (Model-View-Controller). Then
select OK.
1. The Azure Cosmos DB .Net SDK is packaged and distributed as a NuGet package.
To get the NuGet package in Visual Studio, use the NuGet package manager in
Visual Studio by right clicking on the project in Solution Explorer and then clicking
Manage NuGet Packages.
2. In the NuGet Browse box, type Azure DocumentDB. Then, press the install button.
3. Once the package is installed, your Visual Studio solution should resemble the
following with two new references added, Microsoft.Azure.Documents.Core.dll and
Newtonsoft.Json.
In Solution Explorer, right click the Models folder, click Add. Then,
click Class.
The Add New Item dialog box appears. Name your new class as Item.cs
and click Add.
In this new Item.cs file, add the following after the last using statement.
using Newtonsoft.Json;
Now replace this public class Item with the below code:
NOTES:
All data in Azure Cosmos DB is passed over the wire and stored as JSON. To control the way your objects are
serialized/deserialized by JSON.NET, you can use the JsonProperty attribute as demonstrated in the Item class
we just created. You don't have to do this but I want to ensure that my properties follow the JSON camelCase
naming conventions. Not only can you control the format of the property name when it goes into JSON, but you
can entirely rename your .NET properties like I did with the Description property.
2. Add a controller
In the Add Scaffold dialog box, select MVC Controller - Empty, and
select Add.
Once the file is created, your Visual Studio solution should resemble the
following with the new ItemController.cs file in Solution Explorer.
In Solution Explorer, expand the Views folder and add an Item folder.
Then, right click the Items folder, click Add. Then, click View.
Once all these values are set, click Add and let Visual Studio create a
new template view. Once it is done, it will open the .cshtml file that was
created. We can close that file in Visual Studio as we will come back to
it later.
In Solution Explorer, right click the Items folder again, click Add.
Then, click View.
In Solution Explorer, right click the Items folder again, click Add.
Then, click View.
Once this is done, close all the .cshtml documents in Visual Studio as we
will return to these views later.
1. Listing incomplete Items in the MVC Web Application. The first thing to do
here is add a class that contains all the logic to connect to and use Azure Cosmos
DB.
2. For this tutorial we'll encapsulate all this logic in to a repository class called
DocumentDBRepository.
In the Solution Explorer, right-click on the project, click Add > Class.
Name the new class as DocumentDBRepository and click Add.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using System.Configuration;
using System.Linq.Expressions;
using System.Net;
using Microsoft.Extensions.Configuration;
using System.IO;
await
client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollec
tionUri(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;
}
}
}
The url and key can be retrieved from the azure portal. Screen shot as
below:
Now, to wiring up the Azure Cosmos DB repository, now let's add our
application logic.
The first thing we need to do is prepare a todo list page for displaying the
incomplete work items. Add the following red highlighted code
statements within the DocumentDBRepository class.
using System.Net;
using System.Threading.Tasks;
using todo.Models;
Now, open the startup.cs file and add the below red highlighted code
statement in the public Startup(IConfiguration configuration)
Then open the _Layout.cshtml and the button “To Do List” in the
navigation bar list.
Once you finish the above steps, build and run this project, you should
now see something that looks this. The page look empty because we still
haven’t insert any new incomplete items into the Cosmo DB.
Let's put some items into our database so we have something more than an empty grid
to look at.
Let's add some code to Azure Cosmos DBRepository and ItemController to persist the
record in Azure Cosmos DB.
Similar as below:
2. Open the ItemController.cs file and add the following highlighted code statements
within the class. This is how ASP.NET MVC knows what to do for
the Create action. In this case just render the associated Create.cshtml view created
earlier.
3. Now, build and run your application. Once you click on the “Create New” button,
you will be able to see the create page appear in the browser.
4. Now, we need some more code in this controller that will accept the submission
from the Create view. Add the next highlighted block of code to the
ItemController.cs class that tells ASP.NET MVC what to do with a form POST
for this controller.
5. Finally, build and run your application. You now can insert a new data into the
Cosmo DB by using the Create page.
g. Editing Items
Estimation time for this section G: 15 Minutes.
There is second thing for us to do is to add the ability to edit Items in the database and
to mark them as complete.
The view for editing was already added to the project, so we just need to add some code
to our controller and to the DocumentDBRepository class again.
Similar as below:
[ActionName("Edit")]
public async Task<ActionResult> EditAsync(string id)
{
if (id == null)
{
return BadRequest();
}
return View(item);
}
[HttpPost]
[ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<ActionResult>
EditAsync([Bind("Id,Name,Description,Completed")] Item item)
{
if (ModelState.IsValid)
{
await DocumentDBRespository<Item>.UpdateItemAsync(item.Id,
item);
return RedirectToAction("Index");
}
return View(item);
}
3. Now, open the Index.cshtml and replace the below highlighted lines
to become
4. Now, build and run the application again. Click on the Edit button, you will see
the edit page. You can edit the data now using that page.
5. In the edit page, tick the Completed checkbox. Once you save the page, you will
find out the data is missing from the Index incomplete list.
h. Exercise 1: Add a new page for displaying the completed items from
the Cosmo DB.
Estimation time for this section H: 20 Minutes.
In Solution Explorer, expand the Views folder and add an Item folder.
Then, right click the Items folder, click Add. Then, click View.
Similar as below:
4. Now, build and run the application again. Click on the Delete button and you will
see the delete page. You can delete the data now using that page.
Example:
In Solution Explorer, expand the Views folder and add an Item folder.
Then, right click the Items folder, click Add. Then, click View.
3. Now, build and run the application again. Click on the Details button, you will see
the details page. You can view single data now using that page.
Example:
1. Once your complete application is working correctly with Azure Cosmos DB, you
have to deploy this web app to Azure App Service.
Summary:
In this tutorial, we learned how to build an ASP .Net web application with the Azure Cosmo
Document DB.