Building an ASP.NET MVC Application Using Azure DocumentDB
Contents Overview and Azure account requrements... 3 Create a DocumentDB database account... 4 Running the DocumentDB web application... 10 Walk-thru the ASP.NET MVC application... 19 Deploy application to Azure Websites... 26 Conclusion... 29 Roll back Azure changes... 30 Terms of use... 32 Introduction to Azure SQL Database Service Tiers
Overview and Azure account requirements Estimated time to complete lab is 40-45 minutes. Overview To highlight how customers can efficiently leverage Azure DocumentDB to store and query JSON documents, this document provides an end-toend walk-through of building a ToDo List web application using Azure Document DB. This walk-through shows you how to use DocumentDB service provided by Azure to store and access data from an ASP.NET MVC web application hosted on Azure and presumes that you have some prior experience using ASP.NET MVC and Azure Websites. You will learn: 1. Creating and provisioning a DocumentDB Account 2. Creating a ASP.NET MVC Application 3. Connecting to and using Azure DocumentDB from your web application 4. Deploying the Web Application to Azure Websites By following this walkthrough, you will walk-thru a simple web-based task-management application that allows creating, retrieving and completing of tasks. The tasks will be stored as JSON documents in Azure DocumentDB. The resulting application allows you to create, edit, display and delete items stored in the DocumentDB database as shown below. Azure account requirements Introduction to Azure SQL Database Service Tiers 3
While carrying all of the exercises within this hands on lab you will either be making use of the the Azure Preview portal at https://portal.azure.com/. To perform this lab, you will require a Microsoft Azure account. If you do not have an Azure account, you can request a free trial version by going to http://azure.microsoft.com/en-us/pricing/freetrial/. Within the one-month trial version, you can perform other SQL Server 2014 hands on labs along with other tutorials available on Azure. Note, to sign up for a free trial, you will need a mobile device that can receive text messages and a valid credit card. Be sure to follow the Roll back Azure changes section at the end of this exercise after creating the Azure database so that you can make the most use of your $200 free Azure credit. Create a DocumentDB database account DocumentDB is a fully-managed document database-as-a-service with rich query and indexing capabilities over a schema-free JSON data model. It offers configurable and reliable performance, native JavaScript transactional processing, and is built for the cloud with elastic scale. Let s get started! Connect to SQLONE computer 1. Click on SQL2014DEMO-SQLO button on right side of the screen to connect to the SQLONE computer. Note, if you have a monitor that supports a larger screen resolution than 1024 x 768, you can change the screen resolution Introduction to Azure SQL Database Service Tiers 4
for the lab to go as high as 1920 x 1080. By going to a higher screen resolution, it will be easier to use SQL Server Management Studio. 2. Right click on the desktop and click on Screen resolution. 3. Select 1366 x 786 (a good minimum screen size for using SSMS) and click OK. 4. Click Keep Changes. 5. Resize the client hollaunchpad Online window for the lab to fit your screen resolution. 6. During the setup you will need to record credentials and server locations. Open notepad.exe to keep track of information Sign in to the Azure preview portal 1. Click on the IE toolbar button at the bottom of the desktop to launch IE with the Azure Management Portal. 2. Enter in your Microsoft ID that is associated with your Azure subscription and click Continue. This process validates your Microsoft ID to verify that it is associated with an Azure subscription. Introduction to Azure SQL Database Service Tiers 5
3. Enter in your password for the Sign in page and click Sign in to continue. 4. You should now be logged into the Azure Management portal. In order to create a DocumentDB database, you need to use the new Azure portal at https://portal.azure.com. Click on the Preview Portal in the IE favorites bar to go to the new portal. Create a DocumentDB account 1. Within the portal, click on the New button at the lower left portion if the page and then scroll down to you see DocumentDB and click on DocumentDB. Introduction to Azure SQL Database Service Tiers 6
2. The Azure portal then displays the New DocumentDB (Preview) blade to enter in the database specifics. For the ID, enter in the name of your database such as docdbtodo. The green smile icon will indicate that the ID is valid and not a duplicate of an existing name. Introduction to Azure SQL Database Service Tiers 7
3. Change the LOCATION to West US and leave the other items with the provided defaults. Click Create to create the database. Introduction to Azure SQL Database Service Tiers 8
The provisioning process will begin creating your database account. When the provisioning process is complete this can take up to 10 minutes you should see a notification appear in the notifications area of the portal and the tile on your start screen (if you selected to create one) will change to show the completed action. 4. Once provisioning is complete, clicking the DocumentDB tile from the start screen will bring up the main blade for this newly created DocumentDB account. 5. Open a blank Notepad window by clicking on the Notepad icon on the desktop toolbar. You will use this as a scratchpad to Introduction to Azure SQL Database Service Tiers 9
record the HTTP endpoint and Key values for your DocuementDB database. 6. Go back to the Azure portal and click the Keys button to display the Keys blade for your database. 7. Click on the clipboard icon next to the URI value and then paste it into your Notepad window. 8. Click on the clipboard icon next to the PRIMARY KEY value and then paste it into your Notepad window. You will use these values in the web application. Running the DocumentDB web application Test driving the ASP.NET web application In this section, you will test out the ASP.NET Model-View-Controller (MVC) Web application that creates the DocumentDB schema and allows you to create, edit and mark items as completed for a simple TODO application. 1. Click on the Visual Studio icon on the task bar to open Visual Studio. 2. On the Start Page, click on the todo project under the Recent list of projects. Introduction to Azure SQL Database Service Tiers 10
3. The project should open up with the Web.config file open in the editor. If the file is not open, go to the Solution Explorer and double-click on the Web.config file. 4. Replace the endpoint and authkey values with the URI and PRIMARY KEY settings for your DocuementDB account as shown above. The end result should look as follows. Introduction to Azure SQL Database Service Tiers 11
Note: The name of the database for the DocumentDB service will be called ToDoList as specified by the database key. The name of the collection is called Items. We ll go over collections a little later. Adding items to the DocumentDB ToDoList database 1. Click on the Internet Explorer debug toolbar button to start the application. Visual Studio will launch the application in a browser as shown below. 2. Click on the Create New link to go to the Create page. Introduction to Azure SQL Database Service Tiers 12
3. Type in a value for Name and Description, such as Name: Learn more about DocumentDB Description: Once I complete this lab, I will know more Introduction to Azure SQL Database Service Tiers 13
4. Click Create to add the JSON document with the information to the collection. The application will then show the record in the Index page. 5. Add two more items using steps 2 through 4. 6. On one of the items you just created, click the Delete link for it. This action removes the item from the Index list. Introduction to Azure SQL Database Service Tiers 14
7. Close the browser window for the web application. Explore what happened with DocumentDB Studio DocumentDB Studio is an application available on Github at https://github.com/mingaliu/documentdbstudio. This program allows you to connect to your DocumentDB service to explore and query items. If you want to use this tool on your own system, you will need to use Visual Studio to connect to the Github project and build the project. Note, on October 27, the Azure Portal will be updated with a new version of the DocumentDB blade that will allow you to perform much of the functionality provided by DocumentDB Studio. 1. Go to the desktop and double click the DocumentDB Studio shortcut. 2. Click on File -> Add Account to enter in the connection information to your DocumentDB. Introduction to Azure SQL Database Service Tiers 15
3. Copy your DocumentDB service URI into the Account Endpoint field and the PRIMARY KEY into the Account Secret field. Then, click OK. Note: DocumentDB supports several types of connections. When you select Gateway, DocumentDB routes all requests to through the DocumentDB to the appropriate data partition. The two other Direct connection types are for advanced usage that provides connections to specific data nodes. Use the default value of Gateway. 4. Expand the top node to display the ToDoList database. Expand the ToDoList node to display the Users and Items collection. Expand the Items collection to show the objects in the Introduction to Azure SQL Database Service Tiers 16
collection. Click on one of the items with a GUID name to show the items in the document. Notice that there are only two items in the list. When you deleted the item using the web application, it deleted the actual document. 5. To edit an item, right click on the item and click Update Document. 6. Drag the pane splitter so that you can see more of the top pane. Then change iscomplete :false, to iscomplete :true, Introduction to Azure SQL Database Service Tiers 17
7. Click on the Execute button to send the HTTP request to DocumentDB. DocumentDB Studio displays the committed result back into the lower pane. The DocumentDB Studio application makes it easy to see the structure of your items in a collection within your database. The DocumentDB Studio application can perform many other tasks. You can learn more about the program through the Github site at https://github.com/mingaliu/documentdbstudio. Introduction to Azure SQL Database Service Tiers 18
Walk-thru the ASP.NET MVC application Now that you have seen the Web application in action and how the data was stored in DocumentDB, the rest of the lab walks you through the key elements of the todo solution. Creating the solution from scratch If you were to create the todo application from scratch, you would perform the following actions in Visual Studio. You don t need to perform these actions in this lab. 1. In Visual Studio, click File - New Project and select the option to create a new ASP.NET MVC Web Application. 2. Name the application todo and specify c:\labs\documentdb for the Location then click Ok. Introduction to Azure SQL Database Service Tiers 19
3. Select the box on the lower right to "Host in the cloud". Selecting this option will pre-provision an Azure Website for you and make life a lot easier when it comes times to deploy the final working application. If you aren t signed in, click the Manage Subscriptions link. Click the Sign In button and use your Azure credentials. Click Close once your subscription shows up in the Accounts dialog. 4. Select OK and let Visual Studio scaffold the empty ASP.NET MVC template. If you chose to host this in the Cloud you will see at least one additional screen asking you to login to your Azure account and provide some values for your new Website. Proceed to supply all these Azure values and continue. You don t need to specify a Database server we're going to be using a new Azure DocumentDB database. Introduction to Azure SQL Database Service Tiers 20
Once Visual Studio has finished creating the boilerplate MVC application you have an empty ASP.NET application that you can run locally. 5. Install the DocumentDB NuGet package for the needed assemblies by clicking TOOLS -> NuGet Package Manager > Package Manager Console. 6. Type in the following command into the Package Manager Console Install-Package Microsoft.Azure.Documents.Client Pre Introduction to Azure SQL Database Service Tiers 21
At this point, your solution would have the necessary assemblies needed to work with DocumentDB. Let s now look at the various files that make up the application in the order they were created. Rather than show all of the code for the files, we will highlight the key elements of the program. Web.config 1. Go back to Visual Studio and review the Web.config file. The Web.config file is used to store configuration information about the web application. Typically, you would include connection string information a SQL Server database. Likewise, the application uses this file for the connection information to your DocumentDB service with the four lines that you modified earlier. <add key="endpoint" value="https://docdbtodo.documents.azure.com:443/"/> <add key="authkey" value="4cwsvbmbsq66wjo99vpcmi5k0rne2mts+azdbohd2fg1jqpireywrqrded2m7hk9dxievrasrj/qbf9ks1183q=="/> <add key="database" value="todolist"/> <add key="collection" value="items"/> Models > Item.cs 1. Expand the Models folder and double click to open the Item.cs file. Introduction to Azure SQL Database Service Tiers 22
The Item.cs file is used by the application to capture the structure of the JSON document that captures the schema for the document under the Items collection. public class Item { [JsonProperty(PropertyName="id")] public string Id { get; set; } [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "description")] public string Description { get; set; } [JsonProperty(PropertyName = "iscomplete")] public bool Completed { get; set; } } All data in DocumentDB 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. Not only can you control the format of the property name when it goes in to JSON, but you can entirely rename your.net properties with the Description property. You can, if you like, use JsonConverter objects here as well to completely control how serialization is handled. In order to get Visual Studio to resolve the "JsonProperty" attribute used here you need to add the following using statement to the using section of your class file: using Newtonsoft.Json; private static Database ReadOrCreateDatabase() { var db = Client.CreateDatabaseQuery().Where(d => d.id == DatabaseId).AsEnumerable().FirstOrDefault(); if (db == null) DocumentDBRepository.cs 1. Double click on the DocumentDBRepository.cs file under the todo project. This file contains all of the interaction code between the application and DocumentDB. For example, the following code starting at line 106 performs action to create a new ToDoList database if one doesn t already exist. Introduction to Azure SQL Database Service Tiers 23
{ } db = Client.CreateDatabaseAsync(new Database { Id = DatabaseId }).Result; } return db; Notes the use for the.where using LINQ query syntax that should be very familiar to.net developers. The following code at line 91 creates the Items collection within the ToDoList database. private static DocumentCollection ReadOrCreateCollection(string databaselink) { var col = Client.CreateDocumentCollectionQuery(databaseLink).Where(c => c.id == CollectionId).AsEnumerable().FirstOrDefault(); if (col == null) { col = Client.CreateDocumentCollectionAsync(databaseLink, new DocumentCollection { Id = CollectionId }).Result; } } return col; The code at line 123 returns the list of items where iscomplete: false in the JSON document. public static List<Item> GetIncompleteItems() { return Client.CreateDocumentQuery<Item>(Collection.DocumentsLink).Where(d =>!d.completed).asenumerable().tolist<item>(); } You can review the other members used to retrieve a specific document based on an ID, update the item and delete the item. Controllers > ItemController.cs 1. Expand the Controllers folder and double click on the ItemController.cs file. The ItemController is responsible for handling the data for the web application and interacting with DocumentDB through the methods defined in the DocumentDBRepository.cs file. For example, Index() displays the items Create() adds a new item Introduction to Azure SQL Database Service Tiers 24
Edit() changes the existing item Delete() deletes the item The Views 1. For each of the items above, there is a set of.cshtml files that handles the display of the page elements based on the data. Expand the Views -> Item folders to see the view files. 2. Open up each of these files: Create.cshtml, Details.cshtml, Edit.cshtml and Index.cshtml to see how the page elements are handled. 3. Under the Views -> Shared folder, is the _Layout.cshtml file. This file controls the overall frame for the application. Routing commands 1. Expand the App_Start folder and open the RouteConfig.cs file. 2. Starting at line 16, the following code changes the routine behavior to use the Item controller instead of the Home controller and use Index as the view to display. routes.maproute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Item", action = "Index", id = UrlParameter.Optional } ); Now if you run the application, it will call in to your ItemController and return the results of the GetIncompleteItems method to the Views\Item\Index view. The rest of code The rest of the files in the application were generated as part of the ASP.NET MVC Web Application template. To learn more about this type of web application, see the ASP.NET topic at http://www.asp.net/visual-studio/overview/2013/creating-webprojects-in-visual-studio. Introduction to Azure SQL Database Service Tiers 25
Deploy application to Azure Websites Now that you have the complete application working correctly against DocumentDB we're going to deploy this to Azure Websites. Steps you will perform to publish the application as an Azure Website 1. Right-click on the Project in Solution Explorer (make sure you're not still running it locally) and select Publish. 2. Click on Microsoft Azure Websites under Select a publish target. Introduction to Azure SQL Database Service Tiers 26
3. Click on the Sign In button. 4. Follow the prompts to enter your Microsoft ID credentials used for your Azure subscription. Note: When you sign in with your credentials, be sure to choose the option to save them. Otherwise, Visual Studio will prompt you several times during the process to use the current credentials. 5. Click on New once you are signed in. Introduction to Azure SQL Database Service Tiers 27
6. Enter in a valid web site name and make sure that the name validates. Change the Region value to US West to match the location of your DocumentDB service. Leave the Database server and No database since you are connecting to DocumentDB in the application. 7. Click Create to create the Azure Website. Once the action is complete, you will see the Connection page for the publishing process. Introduction to Azure SQL Database Service Tiers 28
Conclusion 8. Click Publish to complete the process. Visual Studio then launches the application on your Azure Website. Congratulations! You have just built your first ASP.NET MVC Application using Azure DocumentDB and published it to Azure Websites. Try extending the application Now that you have the application up and running, try modifying to do something different. For example, instead of Delete actually deleting the item, try changing the code update the IsComplete value to true. Introduction to Azure SQL Database Service Tiers 29
Or, try adding a new view that shows items that are marked as IsCompete or just show all the items. Roll back Azure changes Let s clean up the assets we have used during this hands on lab. Here are the items you should be delete from your subscription: Delete the Azure Website 1. Go to the Azure Preview Portal by clicking on the Preview Portal link on the IE favorites bar. 2. Click BROWSE on the left pane. 3. Click Websites in the Browse control. 4. Click in the Website name you created in the Websites blade. Introduction to Azure SQL Database Service Tiers 30
5. Click on the Delete button within the properties blade for your Website. 6. Click Yes to confirm. Delete DocumentDB 1. Scroll the preview back to the main Portal blade. Introduction to Azure SQL Database Service Tiers 31
2. Click on your DocumentDB tile as shown above. 3. Click on the Delete icon displayed in the DocumentDB database properties blade. 4. Click Yes to confirm. Note: As of October 15 th 2014, the Delete command does not work. You can now close the lab environment. Terms of use 2014 Microsoft Corporation. All rights reserved. By using this Hands-on Lab, you agree to the following terms: The technology/functionality described in this Hands-on Lab is provided by Microsoft Corporation in a sandbox testing environment for purposes of obtaining your feedback and to provide you with a learning experience. You may only use the Hands-on Lab to evaluate such technology features and functionality and provide feedback to Microsoft. You may not use it for any other purpose. You may not modify, copy, distribute, transmit, display, perform, reproduce, publish, license, create derivative works from, transfer, or sell this Hands-on Lab or any portion thereof. Introduction to Azure SQL Database Service Tiers 32
COPYING OR REPRODUCTION OF THE HANDS-ON LAB (OR ANY PORTION OF IT) TO ANY OTHER SERVER OR LOCATION FOR FURTHER REPRODUCTION OR REDISTRIBUTION IS EXPRESSLY PROHIBITED. THIS HANDS-ONLAB PROVIDES CERTAIN SOFTWARE TECHNOLOGY/PRODUCT FEATURES AND FUNCTIONALITY, INCLUDING POTENTIAL NEW FEATURES AND CONCEPTS, IN A SIMULATED ENVIRONMENT WITHOUT COMPLEX SET-UP OR INSTALLATION FOR THE PURPOSE DESCRIBED ABOVE. THE TECHNOLOGY/CONCEPTS REPRESENTED IN THIS HANDS-ON LAB MAY NOT REPRESENT FULL FEATURE FUNCTIONALITY AND MAY NOT WORK THE WAY A FINAL VERSION MAY WORK. WE ALSO MAY NOT RELEASE A FINAL VERSION OF SUCH FEATURES OR CONCEPTS. YOUR EXPERIENCE WITH USING SUCH FEATURES AND FUNCITONALITY IN A PHYSICAL ENVIRONMENT MAY ALSO BE DIFFERENT. FEEDBACK. If you give feedback about the technology features, functionality and/or concepts described in this Hands-on Lab to Microsoft, you give to Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software or documentation to third parties because we include your feedback in them. These rights survive this agreement. MICROSOFT CORPORATION HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH REGARD TO THE HANDS-ON LAB, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY, WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON- INFRINGEMENT. MICROSOFT DOES NOT MAKE ANY ASSURANCES OR REPRESENTATIONS WITH REGARD TO THE ACCURACY OF THE RESULTS, OUTPUT THAT DERIVES FROM USE OF THE VIRTUAL LAB, OR SUITABILITY OF THE INFORMATION CONTAINED IN THE VIRTUAL LAB FOR ANY PURPOSE. DISCLAIMER This lab contains only a portion of new features and enhancements in Microsoft SQL Server 2014. Some of the features might change in future releases of the product. In this lab, you will learn about some, but not all, new features. Introduction to Azure SQL Database Service Tiers 33