You are on page 1of 55

Hands-On Lab

Building ASP.NET Applications with Windows Azure


Lab version: Last updated: 2.0.0 6/22/2011

Page | 1

CONTENTS OVERVIEW ............................................................................................................................................. 3 EXERCISE 1: MOVING A WEB APPLICATION TO THE CLOUD ........................................................... 5

Task 1 Preparing the Application to Run in Windows Azure ........................................................... 5


EXERCISE 2: USING THE AZURE ASP.NET PROVIDERS WITH MVC APPLICATIONS..................... 12

Task 1 Configuring Authenticated Access to the Application ........................................................ 12 Task 2 Configuring Membership Support Using the Azure TableStorageMembershipProvider ..... 13 Task 3 Configuring Role Support Using the Azure TableStorageRoleProvider ............................... 21 Task 4 Configuring Session Support Using the Azure TableStorageSessionProvider ...................... 30
EXERCISE 3: USING THE AZURE ASP.NET PROVIDERS WITH WEB FORM APPLICATIONS ......... 31

Task 1 Configuring Authenticated Access to the Application ........................................................ 32 Task 2 Configuring Membership Support Using the Azure TableStorageMembershipProvider ..... 32 Task 3 Configuring Role Support Using the Azure TableStorageRoleProvider ............................... 41 Task 4 Configuring Session Support Using the Azure TableStorageSessionProvider ...................... 53
SUMMARY ............................................................................................................................................ 54

Page | 2

Overview
ASP.NET supports different implementations of the application providers for membership, role, profile and session management. Most providers come with a version that is based on a SQL database, or uses in-memory representations of data managed by the providers. The Windows Azure samples include provider implementations that make use of scalable and reliable blob and table storage services. Additionally, the providers deal with the problem of Web applications that are hosted on a variety of different machines inside the Windows Azure fabric. When you deploy your Web application in the Windows Azure data centers, the storage services for tables and blobs are readily available and are therefore easily accessible from your application.

Objectives
In this hands-on lab, you will learn how to: y y y Migrate ASP.NET Web Form and MVC applications to Windows Azure UseForms Authentication with Windows Azure Use Azure ASP.NET providers for membership, role, and session state support

The lab shows how to use these features for both ASP.NET Web Form and ASP.NET MVC applications and has anexercise dedicated to each technology. Since both exercises use the same scenario and cover the same material, choose the one that is most relevant to your needs.

Prerequisites
The following is required to complete this hands-on lab: y y y Microsoft .NET Framework 4.0 Microsoft Visual Studio 2010 Windows Azure Tools for Microsoft Visual Studio 1.4

Setup
For convenience, much of the code used in this hands-on lab is available as Visual Studio code snippets. To check the prerequisites of the lab and install the code snippets: Page | 3

1. Open a Windows Explorer window and browse to the lab sSource\Setupfolder. 2. Double-click theDependencies.depfile in this folder to launch the Dependency Checker tool and install any missing prerequisites and the Visual Studio code snippets. 3. If the User Account Control dialog is shown, confirm the action to proceed.

Note: This process may require elevation. The .dep extension is associated with the Dependency Checker tool during its installation. For additional information about the setup procedure and how to install the Dependency Checker tool, refer to theSetup.docxdocument in theAssetsfolder of the training kit.

Using the Code Snippets


Throughout the lab document, you will be instructed to insert code blocks. For your convenience, most of that code is provided as Visual Studio Code Snippets, which you can use from within Visual Studio 2010 to avoid having to add it manually. If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the Setup.docx document in the Assets folder of the training kit, which contains a section describing how to use them.

Exercises
This hands-on lab includes the following exercises: 1. Moving a Web Application to the Cloud 2. Using the Azure ASP.NET Providers with MVC Applications 3. Using the Azure ASP.NET Providers with Web Form Applications

Estimated time to complete this lab: 45 minutes. Note:When you first start Visual Studio, you must select one of the predefined settings collections. Every predefined collection is designed to match a particular development style and determines window layouts, editor behavior, IntelliSense code snippets, and dialog box options. The procedures in this lab describe the actions necessary to accomplish a given task in Visual Studio when using the General Development Settings collection. If you choose a different settings collection for your development environment, there may be differences in these procedures that you need to take into account.

Page | 4

Exercise 1: Moving a Web Application to the Cloud


In this exercise, you configure a sample shopping cart application implemented with ASP.NET to run in Windows Azure.

Task 1 Preparing the Application to Run in Windows Azure The Azure Store is a standard ASP.NET sample that mimics a simple commerce application. It presents a list of products that users can select and add to their shopping cart. Before you begin, you may wish to build and run the solution and become acquainted with its operation. In its initial state, the application runs outside the compute emulator. In this task, you create a Windows Azure project in Visual Studio to prepare the application to run in Windows Azure. 1. Open Visual Studioin elevated administrator mode from Start | All Programs | Microsoft Visual Studio 2010 by right clicking the Microsoft Visual Studio 2010 shortcut and choosing Run as administrator. 2. If the User Account Control dialog appears, click Continue. 3. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex1-MovingMVCAppsToAzure\Beginor Ex1-MovingWebAppsToAzure\Beginin the Source folder of the lab, select Begin.sln in the folder for the language of your preference (Visual C# or Visual Basic) and click Open. Note: Depending on your needs, you may wish to explore migrating ASP.NET MVC or ASP.NET Web Form applications to Windows Azure.The procedures in this exercise are common to both types of application.Choose the most appropriate solution.

4. Next, create a newcloud service project and add it to the solution. In the File menu, point to Add and select New Project. In the Add New Project dialog, expand the language of your preference (Visual C# or Visual Basic) in the Installed Templateslist and select Cloud. Choose theWindows Azure Project template,set the Name of the projectto AzureStoreService,keep the proposed location in the solution s folder and then click OK.

Page | 5

Figure 1 Configuring the application to run in Windows Azure

5. In the New Windows Azure Project dialog, click OK without adding new roles to the solution because you will use the existing application as a web role.

Figure 2 No additional roles are required Page | 6

6. Associate the ASP.NET project to the cloud project. In Solution Explorer, right-click the Roles node in the AzureStoreService project, point to Add and select Web Role Project in solution.

Figure 3 Associating the web role project

7. In the Associate with Role Project dialog, select the AzureStore project and click OK.

Figure 4 Associating the Web Role project Page | 7

Note: When you associate a new role, Visual Studio updates the ServiceDefinition.csdef and the ServiceConfiguration.cscfg files. If either of these files is currently open, make sure that you save it to preserve these changes.

8. Add a reference to the assemblies required to support the Azure environment. In Solution Explorer, right-click the AzureStore project, select Add Reference, click the .NET tab, select the Microsoft.WindowsAzure.Diagnostics, Microsoft.WindowsAzure.ServiceRuntime, and Microsoft.WindowsAzure.StorageClient components and click OK.

Figure 5 Adding a reference to the Windows Azure components

9. Configure a TraceListener to enable diagnostics logging for the application. To do this, open the Web.config file of the AzureStore project and insert a system.diagnostics section as shown (highlighted) below. (Code Snippet Building ASP.NET Applications with Windows Azure - Ex01 DiagnosticMonitorTraceListener) Page | 8

XML
<configuration> ... <system.diagnostics> <traceautoflush="false"indentsize="4"> <listeners> <addname="AzureDiagnostics"type="Microsoft.WindowsAzure.Diagnostics.Diagnostic MonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </listeners> </trace> </system.diagnostics> </configuration>

Note: These settings in the system.diagnostics section configure a trace listener specific to Windows Azure that allows the application to trace code execution using the classes and methods available in the System.Diagnostics.Trace class. This step is usually unnecessary for roles created in Visual Studio because they already include the necessary settings in their role templates.

10. In the Global.asax file of the web role, declare the following namespaces. C#
usingMicrosoft.WindowsAzure; usingMicrosoft.WindowsAzure.ServiceRuntime;

Visual Basic
ImportsMicrosoft.WindowsAzure ImportsMicrosoft.WindowsAzure.ServiceRuntime

11. Next, find the Application_Start method and insert the following (highlighted) code at the start of the method to initialize the configuration settings publisher. (Code Snippet Building ASP.NET Applications with Windows Azure - Ex01 SetConfigurationSettingPublisher C#) C#
voidApplication_Start(object sender, EventArgs e) {

Page | 9

Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((c onfigName, configSetter) => { configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)); }); ... }

(Code Snippet Building ASP.NET Applications with Windows Azure - Ex01 SetConfigurationSettingPublisher - VB) Visual Basic
SubApplication_Start(ByVal sender AsObject, ByVal e AsEventArgs) CloudStorageAccount.SetConfigurationSettingPublisher(Function(configName, configSetter) configSetter(RoleEnvironment.GetConfigurationSettingValue(configName))) ... EndSub

Note: A configuration setting publisher simplifies the retrieval of storage account configuration settings. Applications only need to set up the publisher once using CloudStorageAccount.SetConfigurationSettingPublisher, and then elsewhere, whenever they require access to a storage account, they only require the name of the corresponding setting to access the storage account using CloudStorageAccount.FromConfigurationSetting.

Note: Web roles can define a WebRole class with the entry point of the role. This class contains methods that Windows Azure calls at various stages during the role s lifetime, for example, the OnStart method is called during role start up. You can use this method to initialize the role. Note, however, that for web roles executing in full IIS mode, Internet Information Server hosts the web application in a separate process (w3wp.exe), while the role entry point executes in a different process (WaIISHost.exe). Consequently, most web role initialization tasks need to be performed in the ASP.NET Application_Start method.

12. For an ASP.NET MVC project, ensure that the System.Web.MVC assembly is included in the service package that you deploy to Windows Azure. To do this: For a Visual C# project, expand the References node in Solution Explorer for the AzureStore project, right-click the System.Web.MVC assembly and select Properties. Page | 10

For a Visual Basic project,in Solution Explorer, right-click the AzureStore project and select Properties. In the Project Properties window, switch to the References tab, select the System.Web.MVC assembly, and press F4. To add the assembly to the service package, in the Properties window for the System.Web.Mvc assembly, change the value of the Copy Local setting to True.

Figure 6 Including assemblies in the service package deployed to Windows Azure

Note: In general, you need to set Copy Local = True for any assembly that is not installed by default in the Windows Azure VMs to ensure that it is deployed with your application.

Note: Depending on the type of application that you chose for the exercise that you have just completed, you may wish to proceed with Exercise 2: Using the Azure ASP.NET Providers with MVC Applications or Exercise 3: Using the Azure ASP.NET Providers with Web Form Applications.

Page | 11

Exercise 2: Using the Azure ASP.NET Providers with MVC Applications


In this exercise, you modify the ASP.NET MVC application to use the ASP.NET providers from the Windows Azure samples. You start by adding authentication to the site using the membership provider. Next, you implement the role provider to classify users and customize the products that the application offers. Finally, you configure the session state provider to store the contents of the shopping cart.

Task 1 Configuring Authenticated Access to the Application In this task, you configure the application to require authenticated access to the pages that implement the shopping cart. 1. If necessary, open Visual Studioin elevated administrator mode from Start | All Programs | Microsoft Visual Studio 2010 by right clicking the Microsoft Visual Studio 2010 shortcut and choosing Run as administrator. 2. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex2-UsingAzureProvidersWithMVCApps\Begin in the Source folder of the lab, select Begin.sln in the folder for the language of your preference (Visual C# or Visual Basic) and click Open. Alternatively, you may continue with the solution that you completed during Exercise 1. 3. In the Controllers folder, open HomeController.cs(for a Visual C# project) or HomeController.vb (for a Visual Basic project) and decorate the class with anAuthorize attribute. This configures the application to require authenticated access for every available action on this controller. C#
[HandleError] [Authorize] publicclassHomeController : HomeController { ... }

Visual Basic
<HandleError()> _ <Authorize()> _ PublicClassHomeController Inherits System.Web.Mvc.Controller

Page | 12

... EndClass

4. Save the HomeController.csor HomeController.vbfile.

Task 2 Configuring Membership Support Using the Azure TableStorageMembershipProvider In this task, you add and configure the Azure ASP.NET providers for membership, role, and session. 1. Add the Windows Azure ASP.NET Providers project to the solution. In Solution Explorer, rightclick the Begin solution, point to Add and select Existing Project. Browse to Assets\AspProvidersin the Sourcefolder of the lab, select the AspProviders.csproj project and click Open. Note: The AspProvidersprojectis available as a sample. It is included as part of this training kit for your convenience and is based on the original source code found in the MSDN Code Gallery.The project contains the implementation of ASP.NET application providers for membership, role, profile, and session state.

2. Add a reference in the web role to the AspProviders project. In Solution Explorer, right-click the AzureStore project node and click Add Reference. In the Add Reference dialog, switch to the Projectstab, select theAspProviders project and click OK.

Page | 13

Figure 7 Adding a reference to the sample Azure ASP.NET Providers project

3. Update the service configuration to include a connection string to the Azure Storage account where the data will be stored. In the AzureStoreService project, expand the Roles node and double-click the AzureStore node to open the properties window for this role. 4. In the AzureStore[Role] properties window, select the Settings tab and click Add Setting. Set the Name of the new setting to DataConnectionString and change the Type to ConnectionString. Then, in the Value column, click the button labeled with an ellipsis.

Figure 8 Page | 14

Creating a new configuration setting for the role

5. In the Storage Account Connection String dialog, choose the option labeled Use the Windows Azure storage emulator and click OK.

Figure 9 Configuring a storage connection string

6. Press CTRL + S to save your changes to the role configuration. 7. Open the Web.config file located in the root folder of the AzureStore project. 8. (Optional) Configure the storage account information required by the ASP.NET providers in the application configuration file. To do this, locate the <appSettings> element, which should be empty, and replace it with the following configuration block. If the appSettings element is missing, insert it as a direct child of the <configuration> element. Note: In addition to the service configuration file, you can also configure the Azure providers in the Web.config file of the application. This allows you to host the application outside the Azure fabric and still take advantage of the Azure ASP.NET providers and Azure storage. However, when the application runs in the Windows Azure environment, configuration settings in the service configuration file for the ASP.NET providers take precedence over those in the Web.config file. By using the Windows Azure settings, you can avoid redeploying the application when changing provider settings. Page | 15

(Code Snippet Building ASP.NET Applications with Windows Azure Ex02DataConnectionString) XML
<configuration> ... <appSettings> <addkey="DataConnectionString"value="UseDevelopmentStorage=true"/> </appSettings> ... </configuration>

9. Configure the application to use the membership provider in the AspProviders project. To do this, replace the existing <membership> section inside the <system.web> element with the following (highlighted) configuration. Note: The default ASP.NET MVC template in Visual Studio creates the configuration settings for the AspNetSqlMembershipProvider, which uses SQL Server for storage.

(Code Snippet Building ASP.NET Applications with Windows Azure Ex02TableStorageMembershipProvider) XML
<configuration> ... <system.web> ... <authenticationmode="Forms"> ... </authentication> <!-- Membership Provider Configuration --> <membershipdefaultProvider="TableStorageMembershipProvider"userIsOnlineTimeWin dow="20"> <providers> <clear/> <addname="TableStorageMembershipProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageMembershipProv ider" description="Membership provider using table storage" applicationName="AzureStore" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false"

Page | 16

minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0" requiresUniqueEmail="true" passwordFormat="Hashed"/> </providers> </membership> </system.web> ... </configuration>

Important: Before you execute the solution, make sure that the start-up project and the startup page are set. To set the start up project, in Solution Explorer, right-click the AzureStoreService project and select Set as StartUp Project. To designate the start page, in Solution Explorer, right-click the AzureStore project and select Properties. In the Properties window, select the Web tab and in the Start Action, select Specific Page.For the MVC project, leave the value of this field blank.

10. Press F5 to build and run the application.An initialization procedure may be required the first time you execute an application that uses the Windows Azure storage emulator. If this happens, wait until the procedure is complete and review its status. Click OK to continue.

Page | 17

Figure 10 Development storage initialization procedure status

11. Notice that the application redirects you to the log in page when it starts because the authorization settings now require authenticated access to the Home controller. The membership database is initially empty, so you first need to create an account before you can proceed. In the log in page, click Register to access the user registration form.

Page | 18

Figure 11 Authentication required to proceed

12. Fill in the registration form and click Create User to register your account.

Page | 19

Figure 12 Creating a new user account

13. After creating your account, the system automatically logs you inand displays the products page. Notice your user name displayed in the upper right corner of the window.

Page | 20

Figure 13 Products page displaying the current user

14. Close the browser window to stop the running application.

Task 3 Configuring Role Support Using the Azure TableStorageRoleProvider In this task, you add role support to the application using the Azure role provider. This requires updating the registration process to capture the role of the user and configuring the settings for the role provider. To demonstrate the use of roles, you update the products page to filter the list of products based on the type of user. 1. Add code to the start-up routine to initialize the roles supported by the application. The code creates two roles, Home and Enterprise, which the application uses to classify different types of user. OpenGlobal.asax.cs(for Visual C# projects) or Global.asax.vb (for Visual Basic projects) and insert the following (highlighted) code into theApplication_Start method. Page | 21

(Code Snippet Building ASP.NETApplications with Windows Azure - Ex02Initialize Roles - C#) C#
protectedvoid Application_Start() { ... LoadProducts(); // Initialize the application roles if (!System.Web.Security.Roles.RoleExists("Home")) { System.Web.Security.Roles.CreateRole("Home"); } if (!System.Web.Security.Roles.RoleExists("Enterprise")) { System.Web.Security.Roles.CreateRole("Enterprise"); } }

(Code Snippet Building ASP.NETApplications with Windows Azure - Ex02Initialize Roles - VB) Visual Basic
Sub Application_Start() ... LoadProducts() ' Initialize the application roles If (Not System.Web.Security.Roles.RoleExists("Home")) Then System.Web.Security.Roles.CreateRole("Home") EndIf If (Not System.Web.Security.Roles.RoleExists("Enterprise")) Then System.Web.Security.Roles.CreateRole("Enterprise") EndIf EndSub

2. Change the Index action to filter the list of products based on the type of user. In the Controllers folder, open the HomeController.cs file (for a Visual C# project) or the HomeController.vb file (for a Visual Basic project) and insert the following (highlighted) code into the Index method immediately below the line that declares and initializes the filteredProducts variable. (Code Snippet Building ASP.NETApplications with Windows Azure - Ex02 Filter Products - C#) C# Page | 22

publicActionResultIndex() { var products = this.HttpContext.Application["Products"] asList<string>; var itemsInSession = this.Session["Cart"] asList<string> ?? newList<string>(); // add all products currently not in session var filteredProducts = products.Where(item => !itemsInSession.Contains(item)); // Add additional filters here // filter product list for home users if (User.IsInRole("Home")) { filteredProducts = filteredProducts.Where(item => item.Contains("Home")); } return View(filteredProducts); }

(Code Snippet Building ASP.NETApplications with Windows Azure - Ex02 Filter Products- VB) Visual Basic
Function Index() As ActionResult Dim products = TryCast(Me.HttpContext.Application("Products"), List(OfString)) Dim itemsInSession = If(TryCast(Me.Session("Cart"), List(OfString)), New List(OfString)()) ' add all products currently not in session Dim filteredProducts = products.Where(Function(item) (Not itemsInSession.Contains(item))) ' Add additional filters here ' filter product list for home users If User.IsInRole("Home") Then filteredProducts = filteredProducts.Where(Function(item) item.Contains("Home")) EndIf Return View(filteredProducts) EndFunction

Note:The inserted code appends an additional filter for users in the Home role that returns only items containing the text Home .

Page | 23

3. Configure the application to use the role provider in the AspProviders project. In the Web.config file, replace the existing <roleManager> section inside the <system.web> element with the following (highlighted) configuration. Note: The default ASP.NET MVC template in Visual Studio creates the configuration settings for the AspNetSqlRoleProvider, which uses SQL Server for storage, and the AspNetWindowsTokenRoleProvider, which uses Windows groups.

(Code Snippet Building ASP.NET Applications with Windows Azure Ex02TableStorageRoleProvider) XML
<configuration> ... <system.web> ... <!-- RoleManager Provider Configuration --> <roleManagerenabled="true" defaultProvider="TableStorageRoleProvider" cacheRolesInCookie="true" cookieName=".ASPXROLES" cookieTimeout="30" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All"> <providers> <clear/> <addname="TableStorageRoleProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageRoleProvider" description="Role provider using table storage" applicationName="AzureStore" /> </providers> </roleManager> ... </system.web> ... </configuration>

4. Press F5 to build and run the application. 5. In the log in page, click Register to access the user registration form. Notice that the registration wizard now displays a section to specify the role of the customer. Create a new user and assign it a Home customer profile. Page | 24

Figure 14 Registration page showing role information

6. Logged in as a Home user, proceed to the products page. Notice that the list of products only includes home products.

Page | 25

Figure 15 Products page showing a filtered list of products based on role

7. Click the Logout link in the upper left corner of the application window. 8. Register a new account and assign this user an Enterprise profile. Notice that the list of displayed products differs from that seen by a Home user.

Page | 26

Figure 16 Products page showing Enterprise products

9. Select a product from the list and click Add item to cart. You may repeat the process to store additional items in the cart. 10. Click the Check Out link to view the contents of the shopping cart. Verify that the items you selected appear on the list.

Page | 27

Figure 17 Check out page showing the contents of the shopping cart

11. Do not close the browser window or navigate away from the checkout page. 12. In the task bar, right-click the compute emulator icon and select Show Compute Emulator UI. 13. In the Compute Emulator, right-click the AzureStoreService node and chooseSuspend.

Page | 28

Figure 18 Suspending the service role instance

14. Open a command window in elevated administrator mode, from Start | All Programs | Accessories | Command Prompt by right clicking the Command Prompt shortcut and choosing Run as administrator. At the command prompt, type iisreset.

Figure 19 Restarting Internet Information Server Page | 29

Note: The preceding two steps, recycling the role and restarting IIS, simulate what would happen in the Windows Azure platform when a role instance is restarted.

15. Go back to the Compute Emulator and wait until the service stops as indicated by the instance icon turning red. Now, restart the service instance once again. To do this, right-click the AzureStoreService node and choose Run, thenwait for the service to start. 16. Switch back to the browser window showing the check out page and click Refresh. Notice that the order now appears empty. Note: The application is currently using inproc session state, whichmaintains all session state in-memory. When you stop the service instance, it discards all session state including the contents of the shopping cart. In the following task, you will configure the application to store session state in Azure storage, which allows the application to maintain session state in the presence of restarts and across multiple machines hosting the application.

17. Close the browser window to stop the application.

Task 4 Configuring Session Support Using the Azure TableStorageSessionProvider Windows Azure can potentially host a Web role on multiple machines inside the fabric, which makes inmemory session state unsuitable for such an environment. In contrast, the session state provider in the AspProviders project uses table storage to store configuration information about the session and blob storage to store the session state itself. In this task, you configure the application to use the Azure session state provider. 1. Configure the application to use the session provider in the AspProviders project. To do this, in the Web.config file of the AzureStore project, insert the following (highlighted) configuration block as a direct child of the <system.web> element. (Code Snippet Building ASP.NET Applications with Windows Azure Ex02TableStorageSessionStateProvider) XML
<configuration> ... <system.web> ... <!-- SessionState Provider Configuration --> <sessionStatemode="Custom"

Page | 30

customProvider="TableStorageSessionStateProvider"> <providers> <clear/> <addname="TableStorageSessionStateProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStatePr ovider" applicationName="AzureStore" /> </providers> </sessionState> ... </system.web> ... </configuration>

2. Press F5 to build and run the application. 3. Log in and navigate to the products page. Select one or more products from the list and click Add item to cart. Repeat the process to store additional items in the cart. 4. Click the Check Out link to view the contents of the shopping cart. Verify that the items you selected appear on the list. 5. Do not close the browser window or navigate away from the checkout page. 6. In the task bar, right-click the compute emulator icon and select Show Compute Emulator UI. 7. In the Compute Emulator, right-click the AzureStoreService node and chooseSuspend. Wait until the service stops as indicated by the instance icon turning red. 8. Open a command window in elevated administrator mode, from Start | All Programs | Accessories | Command Prompt by right clicking the Command Prompt shortcut and choosing Run as administrator. At the command prompt, type iisreset. 9. Now, restart the service instance once again. To do this, right-click the AzureStoreService node and choose Run, thenwait for the service to start. 10. Switch back to the browser window showing the check out page and click Refresh. Notice that the order is intact. This confirms that the session state can persist through application restarts when using the Azure provider. 11. Close the browser window to stop the application.

Exercise 3: Using the Azure ASP.NET Providers with Web Form Applications
Page | 31

In this exercise, you modify the ASP.NET Web Form application to use the ASP.NET providers from the Windows Azure samples. You start by adding authentication to the site using the membership provider. Next, you implement the role provider to classify users and customize the products that the application offers. Finally, you configure the session state provider to store the contents of the shopping cart.

Task 1 Configuring Authenticated Access to the Application In this task, you configure the application to require authenticated access to the pages that implement the shopping cart. 1. If necessary, open Visual Studioin elevated administrator mode from Start | All Programs | Microsoft Visual Studio 2010 by right clicking the Microsoft Visual Studio 2010 shortcut and choosing Run as administrator. 2. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex3-UsingAzureProvidersWithWebApps\Begin in the Source folder of the lab, select Begin.sln in the folder for the language of your preference (Visual C# or Visual Basic) and click Open. Alternatively, you may continue with the solution that you completed during Exercise 1. 3. Configure authorization for the Store folder to require authenticated access. Open the Web.config file of the AzureStore project and insert the following (highlighted) configuration block as a direct child of the <configuration> element. (Code Snippet Building ASP.NET Applications with Windows Azure - Ex03Configuring Authorization) XML
<?xmlversion="1.0"?> <configuration> ... <locationpath="Store"> <system.web> <authorization> <denyusers="?"/> <allowusers="*"/> </authorization> </system.web> </location> </configuration>

4. Press CTRL + S to save the Web.config file.

Task 2 Configuring Membership Support Using the Azure TableStorageMembershipProvider Page | 32

In this task, you add and configure the Azure ASP.NET providers for membership, role, and session. 1. Add the Windows Azure ASP.NET Providers project to the solution. In Solution Explorer, rightclick the Begin solution, point to Add and select Existing Project. Browse to Assets\AspProviders in the Source folder of the lab, select the AspProviders.csproj project and click Open. Note: The AspProviders project is available as a sample. It is included as part of this training kit for your convenience and is based on the original source code found in the MSDN Code Gallery. The project contains the implementation of ASP.NET application providers for membership, role, profile, and session state.

2. Add a reference in the web role to the AspProviders project. In Solution Explorer, right-click the AzureStore project node and click Add Reference. In the Add Reference dialog, switch to the Projects tab, select the AspProviders project and click OK.

Figure 20 Adding a reference to the sample Azure ASP.NET Providers project

Page | 33

3. Update the service configuration to include a connection string to the Azure Storage account where the data will be stored. In the AzureStoreService project, expand the Roles node and double-click the AzureStore node to open the properties window for this role. 4. In the AzureStore[Role] properties window, select the Settings tab and click Add Setting. Set the Name of the new setting to DataConnectionString and change the Type to ConnectionString. Then, in the Value column, click the button labeled with an ellipsis.

Figure 21 Creating a new configuration setting for the role

5. In the Storage Account Connection String dialog, choose the option labeled Use the Windows Azure storage emulator and click OK.

Figure 22 Configuring a storage connection string Page | 34

6. Press CTRL + S to save your changes to the role configuration. 7. Open the Web.config file located in the root folder of the AzureStore project. 8. (Optional) Configure the storage account information required by the ASP.NET providers in the application configuration file. To do this, locate the <appSettings> element, which should be empty, and replace it with the following configuration block. If the appSettings element is missing, insert it as a direct child of the <configuration> element. Note: In addition to the service configuration file, you can also configure the Azure providers in the Web.config file of the application. This allows you to host the application outside the Azure fabric and still take advantage of the Azure ASP.NET providers and Azure storage. However, when the application runs in the Windows Azure environment, configuration settings in the service configuration file for the ASP.NET providers take precedence over those in the Web.config file. By using the Windows Azure settings, you can avoid redeploying the application when changing provider settings.

(Code Snippet Building ASP.NET Applications with Windows Azure Ex03DataConnectionString) XML
<configuration> ... <appSettings> <addkey="DataConnectionString"value="UseDevelopmentStorage=true"/> </appSettings> ... </configuration>

9. Configure the application to use the membership provider in the AspProviders project. To do this, replace the existing <membership> section inside the <system.web> element with the following (highlighted) configuration. Note: The default ASP.NET Web Application template in Visual Studio creates the configuration settings for the AspNetSqlMembershipProvider, which uses SQL Server for storage.

(Code Snippet Building ASP.NET Applications with Windows Azure Ex03TableStorageMembershipProvider) XML Page | 35

<configuration> ... <system.web> ... <authenticationmode="Forms"> ... </authentication> <!-- Membership Provider Configuration --> <membershipdefaultProvider="TableStorageMembershipProvider"userIsOnlineTimeWin dow="20"> <providers> <clear/> <addname="TableStorageMembershipProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageMembershipProv ider" description="Membership provider using table storage" applicationName="AzureStore" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0" requiresUniqueEmail="true" passwordFormat="Hashed"/> </providers> </membership> </system.web> ... </configuration>

Important: Before you execute the solution, make sure that the start-up project and the startup page are set. To set the start up project, in Solution Explorer, right-click the AzureStoreService project and select Set as StartUp Project. To designate the start page, in Solution Explorer, right-click the AzureStore project and select Properties. In the Properties window, select the Web tab and in the Start Action, select Specific Page.For the Web Form project, set the value of this field to Store/Products.aspx.

10. Press F5 to build and run the application.An initialization procedure may be required the first time you execute an application that uses the Windows Azure storage emulator. If this happens, wait until the procedure is complete and review its status. Click OK to continue. Page | 36

Figure 23 Development storage initialization procedure status

11. Notice that the application redirects you to the log in page when it starts because the authorization settings now require authenticated access to the Home controller. The membership database is initially empty, so you first need to create an account before you can proceed. In the log in page, click Register to access the user registration form.

Page | 37

Figure 24 Authentication required to proceed

12. Fill in the registration form and click Create User to register your account.

Page | 38

Figure 25 Creating a new user account

13. Once you complete the wizard, the application displays a confirmation message. Click Continue to proceed to the products page.

Page | 39

Figure 26 Account successfully created

14. After creating your account, the system automatically logs you in and displays the products page. Notice your user name displayed in the upper right corner of the window.

Page | 40

Figure 27 Products page displaying the current user

15. Close the browser window to stop the running application.

Task 3 Configuring Role Support Using the Azure TableStorageRoleProvider In this task, you add role support to the application using the Azure role provider. This requires updating the registration process to capture the role of the user and configuring the settings for the role provider. To demonstrate the use of roles, you update the products page to filter the list of products based on the type of user. 1. Update the registration process to assign a role to the user. Open Register.aspxin the Account folder and insert the following (highlighted) markup to add a new step in the CreateUserWizard control. Page | 41

(Code Snippet Building Web Form Applications with Windows Azure - Ex03 Role WizardStep) HTML
<asp:CreateUserWizardID="CreateUserWizard1"runat="server"EnableViewState="true "> ... <WizardSteps> <asp:WizardStep> <div>Choose a customer profile:</div> <asp:RadioButtonListID="roles"runat="server" RepeatDirection="Vertical" RepeatLayout="Flow"CssClass="role"/> </asp:WizardStep> <asp:CreateUserWizardStepID="RegisterUserWizardStep"runat="server"> <ContentTemplate> <h2> Create a New Account </h2> <p> Use the form below to create a new account. </p> ...

2. Add an event handler for the event that fires when the wizard creates the user. Add an OnCreatedUser attribute to the CreateUserWizard control and set the name of the event handler to OnCreatedUser.

Figure 28 Adding an event handler for the CreatedUser event

3. In Solution Explorer, right-click Register.aspx.cs and then select View Code to open its codebehind file. Insert the following code to define the OnCreatedUser event handler. (Code Snippet Building Web Form Applications with Windows Azure - Ex03OnCreatedUser - C#) C#
protectedvoid OnCreatedUser(object sender, EventArgs e) {

Page | 42

var list = (RadioButtonList)this.CreateUserWizard1.WizardSteps[0].FindControl("roles"); System.Web.Security.Roles.AddUserToRole( this.CreateUserWizard1.UserName, list.SelectedItem.Text); }

(Code Snippet Building Web Form Applications with Windows Azure - Ex03OnCreatedUser - VB) Visual Basic
ProtectedSub OnCreatedUser() Dim list = DirectCast(Me.CreateUserWizard1.WizardSteps(0).FindControl("roles"), RadioButtonList) System.Web.Security.Roles.AddUserToRole(Me.CreateUserWizard1.UserName, list.SelectedItem.Text) EndSub

Note: The code retrieves the role selected in the wizard and then adds the user to this role using the configured role provider.

4. Insert the following code into the body of the Page_Load method to initialize the CreateUserWizard control using the roles defined by the application. (Code Snippet Building Web Form Applications with Windows Azure - Ex03Page_Load - C#) C#
protectedvoid Page_Load(object sender, EventArgs e) { CreateUserWizard1.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"]; if (!IsPostBack) { var list = (RadioButtonList)this.CreateUserWizard1.WizardSteps[0].FindControl("roles"); list.DataSource = System.Web.Security.Roles.GetAllRoles().OrderByDescending(a => a); list.DataBind(); if (list.Items.Count > 0) {

Page | 43

list.Items[0].Selected = true; } } }

(Code Snippet Building Web Form Applications with Windows Azure - Ex03Page_Load - VB) Visual Basic
ProtectedSub Page_Load(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesMe.Load CreateUserWizard1.ContinueDestinationPageUrl = Request.QueryString("ReturnUrl") If (Not IsPostBack) Then Dim list = DirectCast(Me.CreateUserWizard1.WizardSteps(0).FindControl("roles"), RadioButtonList) list.DataSource = System.Web.Security.Roles.GetAllRoles().OrderByDescending(Function(a) a) list.DataBind() If list.Items.Count > 0 Then list.Items(0).Selected = True EndIf EndIf EndSub

5. Add code to the start-up routine to initialize the roles supported by the application. The code creates two roles, Home and Enterprise, which the application uses to classify different types of user. Open Global.asax.cs (for Visual C# projects) or Global.asax.vb (for Visual Basic projects) and insert the following (highlighted) code into the Application_Start method. (Code Snippet Building ASP.NETApplications with Windows Azure - Ex03Initialize Roles - C#) C#
protectedvoid Application_Start() { ... LoadProducts(); // Initialize the application roles if (!System.Web.Security.Roles.RoleExists("Home")) { System.Web.Security.Roles.CreateRole("Home");

Page | 44

} if (!System.Web.Security.Roles.RoleExists("Enterprise")) { System.Web.Security.Roles.CreateRole("Enterprise"); } }

(Code Snippet Building ASP.NETApplications with Windows Azure - Ex03Initialize Roles - VB) Visual Basic
Sub Application_Start() ... LoadProducts() ' Initialize the application roles If (Not System.Web.Security.Roles.RoleExists("Home")) Then System.Web.Security.Roles.CreateRole("Home") EndIf If (Not System.Web.Security.Roles.RoleExists("Enterprise")) Then System.Web.Security.Roles.CreateRole("Enterprise") EndIf EndSub

6. Change the product page to filter the list of products based on the type of user. Open the Products.aspx.cs code-behind file (for a Visual C# project) or the Products.aspx.vb code-behind file (for a Visual Basic project) in the Store folder and insert the following (highlighted) code into the Page_Init method, immediately below the line that declares and initializes the filteredProducts variable. (Code Snippet Building Web Form Applications with Windows Azure - Ex03Page_Init - C#) C#
protectedvoid Page_Init(object sender, EventArgs e) { var products = this.Application["Products"] asList<string>; var itemsInSession = this.Session["Cart"] asList<string> ?? newList<string>(); // add all products currently not in session var filteredProducts = products.Where(item => !itemsInSession.Contains(item)); // Add additional filters here // filter product list for home users if (User.IsInRole("Home")) {

Page | 45

filteredProducts = filteredProducts.Where(item => item.Contains("Home")); } foreach (var product in filteredProducts) { this.products.Items.Add(product); } }

(Code Snippet Building Web Form Applications with Windows Azure - Ex03Page_Init - VB) Visual Basic
ProtectedSub Page_Init() HandlesMe.Init Dim products = TryCast(Me.Application("Products"), List(OfString)) Dim itemsInSession = If(TryCast(Me.Session("Cart"), List(OfString)), New List(OfString)()) ' add all products currently not in session Dim filteredProducts = products.Where(Function(item) (Not itemsInSession.Contains(item))) ' Add additional filters here ' filter product list for home users If User.IsInRole("Home") Then filteredProducts = filteredProducts.Where(Function(item) item.Contains("Home")) EndIf ForEach product In filteredProducts Me.products.Items.Add(product) Next EndSub

Note: The inserted code appends an additional filter for users in the Home role that returns only items containing the text Home .

7. Configure the application to use the role provider in the AspProviders project. In the Web.config file, replace the existing <roleManager> section inside the <system.web> element with the following (highlighted) configuration. Note: The default ASP.NET Web Application template in Visual Studio creates the configuration settings for the AspNetSqlRoleProvider, which uses SQL Server for storage, and the AspNetWindowsTokenRoleProvider, which uses Windows groups. Page | 46

(Code Snippet Building ASP.NET Applications with Windows Azure Ex03TableStorageRoleProvider) XML
<configuration> ... <system.web> ... <!-- RoleManager Provider Configuration --> <roleManagerenabled="true" defaultProvider="TableStorageRoleProvider" cacheRolesInCookie="true" cookieName=".ASPXROLES" cookieTimeout="30" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All"> <providers> <clear/> <addname="TableStorageRoleProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageRoleProvider" description="Role provider using table storage" applicationName="AzureStore" /> </providers> </roleManager> ... </system.web> ... </configuration>

8. Press F5 to build and run the application. 9. In the log in page, click Register to access the user registration form. Notice that the registration wizard now displays a section to specify the role of the customer. Create a new user and assign it a Home customer profile.

Page | 47

Figure 29 Registration page showing role information

10. Logged in as a Home user, proceed to the products page. Notice that the list of products only includes home products.

Page | 48

Figure 30 Products page showing a filtered list of products based on role

11. Click the Logout link in the upper left corner of the application window. 12. Register a new account and assign this user an Enterprise profile. Notice that the list of displayed products differs from that seen by a Home user.

Page | 49

Figure 31 Products page showing Enterprise products

13. Select a product from the list and click Add item to cart. You may repeat the process to store additional items in the cart. 14. Click the Check Out link to view the contents of the shopping cart. Verify that the items you selected appear on the list.

Page | 50

Figure 32 Check out page showing the contents of the shopping cart

15. Do not close the browser window or navigate away from the checkout page. 16. In the task bar, right-click the compute emulator icon and select Show Compute Emulator UI. 17. In the Compute Emulator, right-click the AzureStoreService node and choose Suspend.

Page | 51

Figure 33 Suspending the service role instance

18. Open a command window in elevated administrator mode, from Start | All Programs | Accessories | Command Prompt by right clicking the Command Prompt shortcut and choosing Run as Administrator. At the command prompt, type iisreset.

Figure 34 Restarting Internet Information Server Page | 52

Note: These two steps, recycling the role and restarting IIS, simulate what would happen in the Windows Azure platform when a role instance is restarted.

19. Go back to the Compute Emulator and wait until the service stops as indicated by the instance icon turning red. Now, restart the service instance once again. To do this, right-click the AzureStoreService node and choose Run, thenwait for the service to start. 20. Switch back to the browser window showing the check out page and click Refresh. Notice that the order now appears empty. Note: The application is currently using inproc session state, whichmaintains all session state in-memory. When you stop the service instance, it discards all session state including the contents of the shopping cart. In the following task, you will configure the application to store session state in Azure storage, which allows the application to maintain session state in the presence of restarts and across multiple machines hosting the application.

21. Close the browser window to stop the application.

Task 4 Configuring Session Support Using the Azure TableStorageSessionProvider Windows Azure can potentially host a Web role on multiple machines inside the fabric, which makes inmemory session state unsuitable for such an environment. In contrast, the session state provider in the AspProviders project uses table storage to store configuration information about the session and blob storage to store the session state itself. In this task, you configure the application to use the Windows Azure session state provider. 1. Configure the application to use the session provider in the AspProviders project. To do this, in the Web.config file of the AzureStore project, insert the following (highlighted) configuration block as an immediate child of the <system.web> element. (Code Snippet Building ASP.NET Applications with Windows Azure Ex03TableStorageSessionStateProvider) XML
<configuration> ... <system.web> ... <!-- SessionState Provider Configuration --> <sessionStatemode="Custom"

Page | 53

customProvider="TableStorageSessionStateProvider"> <providers> <clear/> <addname="TableStorageSessionStateProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStatePr ovider" applicationName="AzureStore" /> </providers> </sessionState> ... </system.web> ... </configuration>

2. Press F5 to build and run the application. 3. Log in and navigate to the products page. Select one or more products from the list and click Add item to cart. Repeat the process to store additional items in the cart. 4. Click the Check Out link to view the contents of the shopping cart. Verify that the items you selected appear on the list. 5. Do not close the browser window or navigate away from the checkout page. 6. In the task bar, right-click the compute emulator icon and select Show Compute Emulator UI. 7. In the Compute Emulator, right-click the AzureStoreService node and choose Suspend. Wait until the service stops as indicated by the instance icon turning red. 8. Open a command window in elevated administrator mode, from Start | All Programs | Accessories | Command Prompt by right clicking the Command Prompt shortcut and choosing Run as administrator. At the command prompt, type iisreset. 9. Now, restart the service instance once again. To do this, right-click the AzureStoreService node and choose Run, thenwait for the service to start. 10. Switch back to the browser window showing the check out page and click Refresh. Notice that the order is intact. This confirms that the session state can persist through application restarts when using the Azure provider. 11. Close the browser window to stop the application.

Summary
Page | 54

By completing this hands-on lab, you saw the changes that are necessary to run an existing ASP.NET application in the Windows Azure environment. You explored authentication and how to use membership, role, and session state providers that are based on scalable and reliable blob and table storage services to handle applications running on multiple machines inside the Windows Azure fabric.

Page | 55

You might also like