33
Page | 1 Hands-On Lab Windows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version: 2.0.0 Last updated: 12/6/2010

Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 1

Hands-On Lab

Windows Azure: Building ASP.NET Web Form Applications with Windows Azure

Lab version: 2.0.0

Last updated: 12/6/2010

Page 2: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 2

CONTENTS

OVERVIEW ................................................................................................................................................... 3

EXERCISE 1: USING THE AZURE ASP.NET PROVIDERS ....................................................................... 5 Task 1 – Configuring the Application to Run in Windows Azure .......................................................... 5

Task 2 – Configuring Authenticated Access to the Application .......................................................... 12

Task 3 – Configuring Membership Support Using the Azure TableStorageMembershipProvider ..... 12

Task 4 – Configuring Role Support Using the Azure TableStorageRoleProvider ................................ 20

Task 5 – Configuring Session Support Using the Azure TableStorageSessionProvider ....................... 32

SUMMARY .................................................................................................................................................. 33

Page 3: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 3

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:

Migrate an ASP.NET Web Form application to Windows Azure

Use Forms Authentication with Windows Azure

Use Azure ASP.NET providers for membership, role, and session state support

During this lab, you will explore how to use these features in an ASP.NET Web Form application. To learn

how to do this for an ASP.NET MVC application, see the Building ASP.NET MVC Applications with

Windows Azure lab.

Prerequisites

The following is required to complete this hands-on lab:

Microsoft .NET Framework 4.0

Microsoft Visual Studio 2010

Windows Azure Tools for Microsoft Visual Studio 1.3

Note: This hands-on lab has been designed to use the latest release of the Windows Azure Tools for

Visual Studio 2010 (version 1.3).

Page 4: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 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:

1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder.

2. Double-click the Dependencies.dep file 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 the Setup.docx document in the Assets folder 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 exercise:

1. Using Azure ASP.NET Providers

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

Page 5: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 5

development environment, there may be differences in these procedures that you need to take into

account.

Exercise 1: Using the Azure ASP.NET

Providers

In this exercise, you configure a sample shopping cart application implemented with ASP.NET Web

Forms to run in Windows Azure and modify it 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 the Application to Run in Windows Azure

The Azure Store is a standard ASP.NET Web Forms 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 development fabric.

In this task, you create a Cloud Service project to configure the application to run in Windows Azure.

1. Open Microsoft Visual Studio 2010 in 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-UsingAzureProviders\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.

4. Add a new Cloud project to the solution. In the File menu, point to Add and then select New

Project.

5. In the Add New Project dialog, choose the Cloud category under Project types and then select

Windows Azure Cloud Service from the list of installed templates. Set the name of the project

to AzureStoreService, keep the proposed location in the solution folder and click OK.

Page 6: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 6

Figure 1

Configuring the application to run as a Cloud Service

6. In the New Cloud Service Project dialog, click OK without adding new roles to the solution

because you will use the existing application as a Web role.

Figure 2

Configuring roles in the cloud service project

Page 7: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 7

7. Associate the ASP.NET Web Forms 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 a Web Role project in the solution

8. In the Associate with Role Project dialog, select the WebFormAzureStore project and click OK.

Figure 4

Associating the Web Forms application as a Web Role project

Page 8: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 8

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.

9. Add a reference to the assemblies required to support the Azure environment. In Solution

Explorer, right-click the WebFormAzureStore 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

10. Configure a TraceListener to enable diagnostics logging for the application. Open the

Web.config file and insert a system.diagnostics section as shown below.

XML

<configuration>

...

<system.diagnostics>

<trace autoflush="false" indentsize="4">

<listeners>

<add name="AzureDiagnostics"

type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener,

Page 9: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 9

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.

11. Add an entry point class to the Web role. In Solution Explorer, right-click the

WebFormAzureStore project, point to Add and select Class. In the Add New Item dialog, set the

Name to WebRole.cs (for Visual C# projects) or WebRole.vb for (Visual Basic projects) and click

Add.

12. In the WebRole.cs or WebRole.vb file, declare the following namespaces.

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 Azure Namespaces

- C#)

C#

using Microsoft.WindowsAzure;

using Microsoft.WindowsAzure.Diagnostics;

using Microsoft.WindowsAzure.ServiceRuntime;

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 Azure Namespaces

- VB)

Visual Basic

Imports Microsoft.WindowsAzure

Imports Microsoft.WindowsAzure.Diagnostics

Imports Microsoft.WindowsAzure.ServiceRuntime

13. Update the declaration of the WebRole class to inherit the RoleEntryPoint class.

C#

namespace WebFormAzureStore

{

Page 10: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 10

public class WebRole

: RoleEntryPoint

{

}

}

Visual Basic

Public Class WebRole

Inherits RoleEntryPoint

End Class

14. Add an OnStart method to set up Windows Azure Diagnostics and initialize the configuration

settings publisher.

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 WebRole OnStart -

C#)

C#

public override bool OnStart()

{

return base.OnStart();

}

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 WebRole OnStart -

VB)

Visual Basic

Public Overrides Function OnStart() As Boolean

Return MyBase.OnStart()

End Function

Note: The WebRole class is the entry point of the role. It contains methods that Windows

Azure calls at various stages during its lifetime.

Here, you override the OnStart method. Windows Azure invokes OnStart when the role starts.

Typically, you use this method to execute initialization code for the application. Alternatively,

web roles can place their initialization code in the ASP.NET Application_Start method.

In this case, the initialization code starts the diagnostic monitor to collect diagnostic data

locally for the role instance. In addition, it sets up a publisher that enables configuration

settings for Azure Storage to be retrieved from the service configuration file.

Page 11: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 11

15. In the Global.asax file from the Web role, declare the following namespaces.

C#

using Microsoft.WindowsAzure;

using Microsoft.WindowsAzure.ServiceRuntime;

Visual Basic

Imports Microsoft.WindowsAzure

Imports Microsoft.WindowsAzure.ServiceRuntime

16. Find the Application_Start method and initialize the configuration settings publisher.

(Code Snippet – Building MVC Applications with Windows Azure - Ex01

SetConfigurationSettingPublisher – C#)

C#

void Application_Start(object sender, EventArgs e)

{

Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((c

onfigName, configSetter) =>

{

configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

});

...

}

(Code Snippet – Building MVC Applications with Windows Azure - Ex01

SetConfigurationSettingPublisher - VB)

Visual Basic

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)

CloudStorageAccount.SetConfigurationSettingPublisher(Function(configName,

configSetter)

configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))

...

End Sub

Page 12: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 12

Task 2 – 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. Configure authorization for the Store folder to require authenticated access. Open the

Web.config file of the WebFormAzureStore project and insert the following (highlighted)

configuration block as a direct child of the <configuration> element.

Web.config

<?xml version="1.0"?>

<configuration>

...

<location path="Store">

<system.web>

<authorization>

<deny users="?"/>

<allow users="*"/>

</authorization>

</system.web>

</location>

</configuration>

2. Set the authentication mode of the application. To do this, locate the <authentication> element

within <system.web> and change its mode attribute to the value Forms. Within the

<authentication> element, create a <forms> element and set the value of its loginUrl attribute

to Account/Login.aspx, as shown below.

Figure 6

Configuring the authentication mode of the application

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

Task 3 – 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, right-

click the Begin solution, point to Add and select Existing Project. Browse to

Page 13: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 13

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. You can find the original source code 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 WebFormAzureStore project node and click Add Reference. In the Add Reference dialog,

switch to the Projects node, select the AspProviders project and click OK.

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 nodes and

double-click the WebFormAzureStore node to open the properties window for this role.

4. In the WebFormAzureStore[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.

Page 14: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 14

Figure 8

Creating a new configuration setting for the role

5. In the Storage Connection String dialog, choose the option labeled Use development storage

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 of the WebFormAzureStore 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

Page 15: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 15

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 Azure ASP.NET providers override those in the

Web.config file. By using the Windows Azure settings, you can avoid repackaging the

application when changing provider settings.

Web.config

<?xml version="1.0"?>

<configuration>

...

<appSettings>

<add key="DataConnectionString" value="UseDevelopmentStorage=true"/>

</appSettings>

...

</configuration>

9. Configure the application to use the membership provider in the AspProviders project. To do

this, insert the following (highlighted) configuration block as a direct child of the <system.web>

element.

Web.config

<configuration>

...

<system.web>

...

<!-- Membership Provider Configuration -->

<membership defaultProvider="TableStorageMembershipProvider"

userIsOnlineTimeWindow="20">

<providers>

<clear/>

<add name="TableStorageMembershipProvider"

type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageMembershipProv

ider"

description="Membership provider using table storage"

applicationName="WebFormAzureStore"

enablePasswordRetrieval="false"

enablePasswordReset="true"

requiresQuestionAndAnswer="false"

Page 16: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

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 is set and that

a start up page has been designated.

To set the start up project, in Solution Explorer, right-click the AzureStoreService project and

select Set as StartUp Project.

To designate a start page, in Solution Explorer, expand the Store folder in the

WebFormsAzureStore project, right-click Products.aspx and select Set As Start Page.

10. Press F5 to build and run the application. An initialization procedure may be required the first

time you execute an application that uses storage in your development environment. If this

happens, wait until the procedure is complete and review its status. Click OK to continue.

Figure 10

Page 17: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 17

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 Store folder. 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.

Figure 11

Log in form indicating that authentication is required to proceed

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

Page 18: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 18

Figure 12

Creating a new user account

Page 19: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 19

13. After creating the account, the application displays a confirmation message. Click Continue to

proceed to the products page.

Figure 13

Account successfully created

14. After successfully 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 20: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 20

Figure 14

Products page displaying the current user

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

Task 4 – 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.aspx and insert the

following (highlighted) markup to add a new step in the CreateUserWizard control.

ASP.NET

<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"

EnableViewState="true" >

...

Page 21: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 21

<WizardSteps>

<asp:WizardStep>

<div>Choose a customer profile:</div>

<asp:RadioButtonList ID="roles" runat="server"

RepeatDirection="Vertical"

RepeatLayout="Flow" CssClass="role" />

</asp:WizardStep>

<asp:CreateUserWizardStep ID="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.

ASP.NET

<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" CssClass="login"

... OnCreatedUser="OnCreatedUser"

<WizardSteps>

3. In the Register.aspx.cs code-behind file, add the following code to define the OnCreatedUser

event handler.

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 OnCreatedUser -

C#)

C#

protected void OnCreatedUser(object sender, EventArgs e)

{

var list =

(RadioButtonList)this.CreateUserWizard1.WizardSteps[0].FindControl("roles");

System.Web.Security.Roles.AddUserToRole(

this.CreateUserWizard1.UserName,

list.SelectedItem.Text);

}

Page 22: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 22

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 OnCreatedUser -

VB)

Visual Basic

Protected Sub OnCreatedUser()

Dim list =

DirectCast(Me.CreateUserWizard1.WizardSteps(0).FindControl("roles"),

RadioButtonList)

System.Web.Security.Roles.AddUserToRole(Me.CreateUserWizard1.UserName,

list.SelectedItem.Text)

End Sub

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 - Ex01 Page_Load - C#)

C#

protected void 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)

{

list.Items[0].Selected = true;

}

}

}

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 Page_Load - VB)

Page 23: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 23

Visual Basic

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Handles Me.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

End If

End If

End Sub

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

users. 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 Web Form Applications with Windows Azure - Ex01 Initialize Roles -

C#)

C#

protected void Application_Start()

{

Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((c

onfigName, configSetter) =>

{

configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

});

LoadProducts();

// Initialize the application roles

if (!System.Web.Security.Roles.RoleExists("Home"))

{

System.Web.Security.Roles.CreateRole("Home");

}

Page 24: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 24

if (!System.Web.Security.Roles.RoleExists("Enterprise"))

{

System.Web.Security.Roles.CreateRole("Enterprise");

}

}

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 Initialize Roles - VB)

Visual Basic

Sub Application_Start()

CloudStorageAccount.SetConfigurationSettingPublisher(Function(configName,

configSetter)

configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))

LoadProducts()

' Initialize the application roles

If (Not System.Web.Security.Roles.RoleExists("Home")) Then

System.Web.Security.Roles.CreateRole("Home")

End If

If (Not System.Web.Security.Roles.RoleExists("Enterprise")) Then

System.Web.Security.Roles.CreateRole("Enterprise")

End If

End Sub

Note: Although you could use the OnStart method of the web role to initialize the application

roles, by using the ASP.NET Application_Start method the application remains host-

environment agnostic and allows you to run the unmodified application outside Azure, leaving

the OnStart method dedicated to Azure specific initialization.

Note that you may need to remove the DiagnosticMonitorTraceListener in the

system.diagnostics section of the configuration file in order to run the application outside the

Azure environment.

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 - Ex01 Page_Init - C#)

C#

Page 25: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 25

protected void Page_Init(object sender, EventArgs e)

{

var products = this.Application["Products"] as List<string>;

var itemsInSession = this.Session["Cart"] as List<string> ?? new

List<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"));

}

foreach (var product in filteredProducts)

{

this.products.Items.Add(product);

}

}

(Code Snippet – Building Web Form Applications with Windows Azure - Ex01 Page_Init - VB)

Visual Basic

Protected Sub Page_Init() Handles Me.Init

Dim products = TryCast(Me.Application("Products"), List(Of String))

Dim itemsInSession = If(TryCast(Me.Session("Cart"), List(Of String)), New

List(Of String)())

' 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"))

End If

For Each product In filteredProducts

Me.products.Items.Add(product)

Next

End Sub

Page 26: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 26

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, insert the following (highlighted) configuration block as a direct child of the

<system.web> element.

Web.config

<configuration>

...

<system.web>

...

<!-- RoleManager Provider Configuration -->

<roleManager enabled="true"

defaultProvider="TableStorageRoleProvider"

cacheRolesInCookie="true"

cookieName=".ASPXROLES"

cookieTimeout="30"

cookiePath="/"

cookieRequireSSL="false"

cookieSlidingExpiration="true"

cookieProtection="All">

<providers> <clear/>

<add name="TableStorageRoleProvider"

type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageRoleProvider"

description="Role provider using table storage"

applicationName="WebFormAzureStore" />

</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 an additional step to input the type of customer. Create a new user and

assign it a Home customer profile.

Page 27: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 27

Figure 15

Registration page showing the new role assignment step

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

includes home products.

Page 28: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 28

Figure 16

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 29: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 29

Figure 17

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 30: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 30

Figure 18

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 31: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 31

Figure 19

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 and type iisreset.

Figure 20

Executing iisreset command

Page 32: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 32

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, then wait 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, which maintains 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 5 – Configuring Session Support Using the Azure TableStorageSessionProvider

Windows Azure can potentially host a Web role on multiple machines inside the fabric, which makes in-

memory 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 WebFormAzureStore project, insert the following (highlighted)

configuration block as an immediate child of the <system.web> element.

Web.config

<configuration>

...

<system.web>

...

<!-- SessionState Provider Configuration -->

<sessionState mode="Custom"

customProvider="TableStorageSessionStateProvider">

<providers>

<clear/>

Page 33: Hands-On Labaz12722.vo.msecnd.net/wazplatformtrainingcourse2-11/Labs/... · 2010. 12. 6. · 1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder. 2. Double-click

Page | 33

<add name="TableStorageSessionStateProvider"

type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStatePr

ovider"

applicationName="WebFormAzureStore" />

</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 EmulatorUI.

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. Now, restart the service instance once again. To do this, right-click the AzureStoreService node

and choose Run, then wait for the service to start.

9. 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.

10. Close the browser window to stop the application.

Summary

By completing this hands-on lab, you saw the changes that are necessary to run an existing ASP.NET

Web Form 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.