Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
Lab 9: Web Application Development with Azure Cosmos DB
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.
a.
1. 2.
Create an Azure Cosmos DB database account
Estimation time for this section A: 5 Minutes
In a new browser window, sign in to the Azure Portal.
Click Create a resource > Database > Azure Cosmos DB.
In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.
Level 3
Asia Pacific University of Technology & Innovation
Page 1 of 27
3.
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
4.
Then, click on the button. Lastly, if the information correct, click
the button.
The account creation takes a few minutes. Wait for the portal to display the “Congratulation! Your Azure Cosmos DB Account was created” page.
Now, navigate to the Azure Cosmos DB account page, and click Keys, as these values are used in the web application you create next.
Now, create a new ASP .NET Core Web Application from the ground-up.
5.
6.
7.
Level 3
Asia Pacific University of Technology & Innovation Page 2 of 27
Review + Create
Create
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
b.
1. 2.
Create an ASP.NET application project
Estimation time for this section B: 5 Minutes
Open Visual Studio. From the main menu, select File > New > Project.
3.
In the New Project dialog box, select Web > ASP.NET Core Web
Application > Todo. Then select OK.
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.
Level 3
Asia Pacific University of Technology & Innovation
Page 3 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
c.
1.
Add Azure Cosmos DB to the MVC Web Application Project.
Estimation time for this section C: 10 Minutes
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.
In the NuGet Browse box, type Azure DocumentDB. Then, press the install button.
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.
2.
3.
Level 3
Asia Pacific University of Technology & Innovation Page 4 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
Level 3 Asia Pacific University of Technology & Innovation Page 5 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
d.
Set up the ASP .Net MVC Core Application
Estimation time for this section D: 20 Minutes
1.
Add a JSON data model
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.
Level 3
Asia Pacific University of Technology & Innovation Page 6 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
2.
Add a controller
In Solution Explorer, right click the Controllers folder, click Add.
Then, click Controller.
In the Add Scaffold dialog box, select MVC Controller – Empty, and select Add.
In the Add Empty MVC Controller dialog box, name the controller ItemController, 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.
Level 3
Asia Pacific University of Technology & Innovation Page 7 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
3.
Add an Item Index view
In Solution Explorer, expand the Views folder and add an Item folder.
Then, right click the Items folder, click Add. Then, click View.
In the Add View dialog box, do the following:
In the View name box, type Index.
In the Template box, select List.
In the Model class box, select Item (todo.Models).
In the layout page box, select ~/Views/Shared/_Layout.cshtml.
Click Add.
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.
Level 3
Asia Pacific University of Technology & Innovation Page 8 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
4.
Add a New Item view
In Solution Explorer, right click the Items folder again, click Add.
Then, click View.
In the Add View dialog box, do the following:
Add an Edit Item view
In the View name box, type Create.
In the Template box, select Create.
In the Model class box, select Item (todo.Models).
In the layout page box, select ~/Views/Shared/_Layout.cshtml.
Click Add.
5.
In Solution Explorer, right click the Items folder again, click Add. Then, click View.
In the Add View dialog box, do the following:
In the View name box, type Edit.
In the Template box, select Edit.
In the Model class box, select Item (todo.Models).
In the layout page box, select ~/Views/Shared/_Layout.cshtml.
Click Add.
Once this is done, close all the .cshtml documents in Visual Studio as we
will return to these views later.
Level 3
Asia Pacific University of Technology & Innovation Page 9 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
e.
Wiring up Azure Cosmos DB.
Estimation time for this section E: 20 Minutes
In this section, we’ll add code to handle the following:
Listing incomplete Items.
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.
In the newly created DocumentDBRepository class and add the
following using statements above the namespace declaration.
Level 3
Asia Pacific University of Technology & Innovation Page 10 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
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;
Now replace this public class DocumentDBRepository with the below code.
public class DocumentDBRespository
{
private static readonly string DatabaseId = “ToDoList”;
private static readonly string CollectionId = “Items”;
private static DocumentClient client;
public static void Initialize()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(“appsettings.json”);
IConfigurationRoot Configuration = builder.Build();
client = new DocumentClient(new
Uri(Configuration[“Setting1:url”]),
Configuration[“Setting1:key”]);
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
{
Level 3
Asia Pacific University of Technology & Innovation Page 11 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
await
client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollec
tionUri(DatabaseId, CollectionId));
}
catch (DocumentClientException e)
{
if (e.StatusCode ==
System.Net.HttpStatusCode.NotFound)
},
1000 });
{
await client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(DatabaseId),
new DocumentCollection { Id = CollectionId
new RequestOptions { OfferThroughput =
} }
} else {
throw; }
We’re reading some values from configuration, so open the appsettings.json file of your application and add the following lines under the “AllowedHosts”: “*” line. Screen shot as below:
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.
Level 3
Asia Pacific University of Technology & Innovation Page 12 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
Level 3
Asia Pacific University of Technology & Innovation Page 13 of 27
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.
Now, modify the public class ItemController to look similar as below.
Open the ItemController.cs and add the following using
statements above the namespace declaration.
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)
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
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.
Level 3
Asia Pacific University of Technology & Innovation Page 14 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
f. Adding Items into the Azure Cosmo Document DB.
Estimation time for this section F: 15 Minutes.
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.
1. Add the following method to your DocumentDBRespository class.
Similar as below:
public static async Task
return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri( DatabaseId, CollectionId), item);
}
Level 3
Asia Pacific University of Technology & Innovation Page 15 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
2.
3.
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.
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.
Level 3
Asia Pacific University of Technology & Innovation Page 16 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
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.
Finally,
5.
build and run your application. You now can insert a new data into the
Level 3
Asia Pacific University of Technology & Innovation Page 17 of 27
Cosmo DB by using the Create page.
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
6. In the Azure Portal:
Level 3
Asia Pacific University of Technology & Innovation Page 18 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
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.
1. Add the following method to your DocumentDBRespository class.
public static async Task
return await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
}
public static async Task
try {
Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
return (T)(dynamic)document;
}
catch (DocumentClientException e) {
if (e.StatusCode == HttpStatusCode.NotFound) {
return null;
}
else {
throw; }
} }
Similar as below:
Level 3
Asia Pacific University of Technology & Innovation Page 19 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
2.
Add the following to the ItemController class.
[ActionName(“Edit”)]
public async Task
{
if (id == null)
{
return BadRequest();
}
Item item = await
DocumentDBRespository
if (item == null)
{
return NotFound();
}
return View(item);
}
[HttpPost]
[ActionName(“Edit”)]
[ValidateAntiForgeryToken]
public async Task
EditAsync([Bind(“Id,Name,Description,Completed”)] Item item)
{
if (ModelState.IsValid)
{
item);
}
await DocumentDBRespository
return RedirectToAction(“Index”);
return View(item);
}
3.
Now, open the Index.cshtml and replace the below highlighted lines
@Html.ActionLink(“Edit”, “Edit”,
@Html.ActionLink(“Details”, “Details”,
@Html.ActionLink(“Delete”, “Delete”,
to become
new { /* id=item.PrimaryKey */ })
|
|
Level 3
Asia Pacific University of Technology & Innovation
Page 20 of 27
new { /* id=item.PrimaryKey */ })
new { /* id=item.PrimaryKey */ })
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
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.
Level 3 Asia Pacific University of Technology & Innovation Page 21 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
h. Exercise1:Addanewpagefordisplayingthecompleteditemsfrom the Cosmo DB.
Estimation time for this section H: 20 Minutes. 1. Hint of answer keys as below.
Level 3
Asia Pacific University of Technology & Innovation Page 22 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
i.
Add a delete page.
Estimation time for this section I: 15 Minutes.
1.
Add a delete view.
In Solution Explorer, expand the Views folder and add an Item folder.
Then, right click the Items folder, click Add. Then, click View. In the Add View dialog box, do the following:
Add the following method to your DocumentDBRespository class.
Similar as below:
In the View name box, type Delete.
In the Template box, select Delete
In the Model class box, select Item (todo.Models).
In the layout page box, select ~/Views/Shared/_Layout.cshtml.
Click Add.
2.
public static async Task
return await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
}
Level 3
Asia Pacific University of Technology & Innovation Page 23 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
3.
Add the following to the ItemController class.
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:
Level 3
Asia Pacific University of Technology & Innovation Page 24 of 27
4.
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
Level 3 Asia Pacific University of Technology & Innovation Page 25 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
j.
Add a details page.
Estimation time for this section j: 10 Minutes.
1. Add a details view.
In Solution Explorer, expand the Views folder and add an Item folder. Then, right click the Items folder, click Add. Then, click View.
In the Add View dialog box, do the following:
2. Add the following to the ItemController class.
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:
In the View name box, type Details.
In the Template box, select Details.
In the Model class box, select Item (todo.Models).
In the layout page box, select ~/Views/Shared/_Layout.cshtml.
Click Add.
Level 3
Asia Pacific University of Technology & Innovation Page 26 of 27
Design and Developing Application in Cloud (CT071-3-5-3-DDAC) Web Application Development with Azure Cosmos DB
k. Exercise 2: Deploy the application to Azure App Service
Estimation time for this section K: 15 Minutes.
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.
Level 3 Asia Pacific University of Technology & Innovation Page 27 of 27