60
Hands-On Lab Windows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version: 1.0.0 Last updated: 2/18/2022 Page | 1

Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

  • Upload
    dobao

  • View
    227

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Hands-On LabWindows Azure: Building ASP.NET Web Form Applications with Windows AzureLab version: 1.0.0

Last updated: 5/8/2023

Page | 1

Page 2: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

CONTENTS

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

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

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

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

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

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

EXERCISE 2 - USING LIVE ID AUTHENTICATION.................................................................................38Task 1 - Registering the Application in the Azure Services Developer Portal.....................................38

Task 2 - Adding Live ID Authentication to the Application.................................................................46

SUMMARY................................................................................................................................................ 54

Page | 2

Page 3: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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.

In addition to ASP.NET provider-based authentication, applications in the Azure environment can take advantage of the identity and authentication system provided by Windows Live to gain access to an enormous user base. As well as verifying the identity of visitors to a site, the Windows Live ID service provides delegated authentication that allows applications to act on behalf of a Windows Live ID user to access Web services and sites that use Windows Live ID authentication.

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

Use Windows Live ID Authentication with Windows Azure

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 3.5 SP1

Microsoft Visual Studio 2008 SP1 (or above)

Windows Azure Tools for Microsoft Visual Studio (November 2009)

Page | 3

Page 4: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

You must also have Internet access to complete the Windows Live ID exercise.

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. Run the SetupLab.cmd script located in the lab's Source\Setup folder to check dependencies and install any missing prerequisites.

2. Once you have verified every prerequisite, follow the instructions to install the code snippets.

Using the Code Snippets

With code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them. For example,

To add this code snippet in Visual Studio, you simply place the cursor where you would like the code to be inserted, start typing the snippet name (without spaces or hyphens), in this case LabNameEx01RunmethodCS, watch as Intellisense picks up the snippet name, and then hit the TAB key twice once the snippet you want is selected. The code will be inserted at the cursor location.

Page | 4

Page 5: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 1Hit TAB to select the highlighted snippet.

Figure 2Hit TAB again and the snippet will expand

To insert a code snippet using the mouse rather than the keyboard, right-click where you want the code snippet to be inserted, select Insert Snippet followed by My Code Snippets and then pick the relevant snippet from the list.

To learn more about Visual Studio IntelliSense Code Snippets, including how to create your own, please see http://msdn.microsoft.com/en-us/library/ms165392.aspx.

Exercises

This Hands-On Lab comprises the following exercises:

1. Using Azure ASP.NET Providers

2. Using LiveID Authentication

Page | 5

Page 6: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Estimated time to complete this lab: 60 minutes.

Exercise 1: Using 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 sample 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 2008 in elevated administrator mode, from Start | All Programs | Microsoft Visual Studio 2008 by right clicking the Microsoft Visual Studio 2008 shortcut and choosing Run as Administrator.

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

3. Add a new Cloud Service project to the solution. In Solution Explorer, right-click the Begin solution node, point to Add and select New Project.

4. In the Add New Project dialog, choose the Cloud Service 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

Page 7: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 3Configuring the application to run as a Cloud Service

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

Page | 7

Page 8: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 4Configuring roles in the cloud service project

6. 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 5Associating a Web Role project in the solution

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

Page | 8

Page 9: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 6Associating the Web Forms application as a Web Role project

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

Page | 9

Page 10: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 7Adding a reference to the Windows Azure components

9. 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, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </listeners> </trace> </system.diagnostics>

</configuration>

Page | 10

Page 11: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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

11. 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.WindowsAzureImports Microsoft.WindowsAzure.DiagnosticsImports Microsoft.WindowsAzure.ServiceRuntime

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

C#namespace WebFormAzureStore{ public class WebRole : RoleEntryPoint { }}

Visual Basic

Public Class WebRole

Page | 11

Page 12: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Inherits RoleEntryPoint

End Class

13. 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(){ DiagnosticMonitor.Start("DiagnosticsConnectionString"); CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => { configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)); });

return base.OnStart();}

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

Visual Basic

Public Overrides Function OnStart() As Boolean DiagnosticMonitor.Start("DiagnosticsConnectionString") CloudStorageAccount.SetConfigurationSettingPublisher(Function(configName, configSetter) SetConfiguration(configName, configSetter))

Return MyBase.OnStart()End Function

Private Function SetConfiguration(ByVal configName As Object, ByVal configSetter As System.Func(Of String, Boolean)) As Object configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)) Return NothingEnd Function

Page | 12

Page 13: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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.

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. You will also create the pages required to register new accounts and log in users to the application.

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.

Figure 8Page | 13

Page 14: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Configuring the authentication mode of the application

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

4. Add a new content form to allow users to log in to the application. In Solution Explorer, right-click the WebFormAzureStore project, point to Add and click New Item, select the Web Content Form template, set the name to Login.aspx and click Add.

Figure 9Adding a new content form to the project (Visual C#)

Page | 14

Page 15: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 10Adding a new content form to the project (Visual Basic)

5. In the Select a Master Page dialog, choose Site.Master and click OK.

Figure 11Selecting a master page for the content form

Page | 15

Page 16: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

6. In the Login.aspx page, update the MainContent placeholder by inserting the following (highlighted) markup that includes a caption and a Login control.

ASP.NET

...<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h1>Welcome to the Azure Store</h1> <asp:Login ID="Login1" runat="server" CssClass="login" DisplayRememberMe="false" LoginButtonType="Link" TitleText="Please login to continue" DestinationPageUrl="~/Store/Products.aspx" /></asp:Content>

7. Press CTRL + S to save the Login.aspx file.

8. Add a new content form to allow users to create new accounts. In Solution Explorer, right-click the WebFormAzureStore project, point to Add and click New Item, select the Web Content Form template, set the name to Register.aspx and click Add. In the Select a Master Page dialog, choose Site.Master and click OK.

9. In the Register.aspx page, update the MainContent placeholder by inserting the following (highlighted) markup that includes a caption and a CreateUserWizard control.

ASP.NET

...<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h1>Registration</h1> <asp:CreateUserWizard ID="CreateUserWizard1" runat="server" CssClass="login" CreateUserButtonType="Link" CancelButtonType="Link" ContinueButtonType="Link" DisplayCancelButton="true" StartNextButtonType="Link" StepNextButtonType="Link" StepPreviousButtonType="Link" CancelDestinationPageUrl="~/Login.aspx" ContinueDestinationPageUrl="~/Store/Products.aspx"> <WizardSteps> <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server"> </asp:CreateUserWizardStep> <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server"> </asp:CompleteWizardStep> </WizardSteps>

Page | 16

Page 17: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

</asp:CreateUserWizard></asp:Content>

10. Press CTRL + S to save the Register.aspx 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 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.

Page | 17

Page 18: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 12Adding 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.

Figure 13Creating a new configuration setting for the role

Page | 18

Page 19: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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

Figure 14Configuring 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 empty, and replace it with the following configuration block.

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

Page | 19

Page 20: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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

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.TableStorageMembershipProvider" description="Membership provider using table storage" applicationName="WebFormAzureStore" 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 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.

Page | 20

Page 21: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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 15Development 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.

Page | 21

Page 22: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 16Log in form indicating that authentication is required to proceed

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

Page | 22

Page 23: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 17Creating a new user account

Page | 23

Page 24: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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

Figure 18Account 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 | 24

Page 25: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 19Products 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" CssClass="login" ...

Page | 25

Page 26: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

<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="CreateUserWizardStep1" runat="server"> </asp:CreateUserWizardStep> <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server"> </asp:CompleteWizardStep> </WizardSteps></asp:CreateUserWizard>

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 | 26

Page 27: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

(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){ 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 | 27

Page 28: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Visual Basic

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 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 IfEnd 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(){ 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 Web Form Applications with Windows Azure - Ex01 Initialize Roles - VB)

Page | 28

Page 29: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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") End If

If (Not System.Web.Security.Roles.RoleExists("Enterprise")) Then System.Web.Security.Roles.CreateRole("Enterprise") End IfEnd 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#

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

Page | 29

Page 30: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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 BasicProtected 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 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) NextEnd Sub

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>

Page | 30

Page 31: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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

Page 32: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 20Registration 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 | 32

Page 33: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 21Products 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 | 33

Page 34: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 22Products 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 | 34

Page 35: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 23Check 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 development fabric icon and select Show Development Fabric UI.

17. In the Development Fabric, right-click the AzureStoreService node and choose Suspend.

Page | 35

Page 36: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 24Suspending the service role instance

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

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

20. Close the browser window to stop the application.

Task 5 – Configuring Session Support Using the Azure TableStorageSessionProvider

Page | 36

Page 37: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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/> <add name="TableStorageSessionStateProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider" 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 development fabric icon and select Show Development Fabric UI.

7. In the Development Fabric, right-click the AzureStoreService node and choose Suspend. Wait until the service stops as indicated by the instance icon turning red.

Page | 37

Page 38: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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.

Exercise 2 - Using Live ID Authentication

In this exercise, you will update the Azure Store application to incorporate Live ID Authentication. To do this, you will modify the log in page to add a Live ID Authentication section that includes a specially formatted link that sends users to the Windows Live ID sign-in page. The service then directs them back to the application along with a unique, site-specific identifier.

When a Live ID user accesses the site for the first time, the application displays a registration page allowing the visitor to associate the Live ID with a membership account in the site.

Task 1 - Registering the Application in the Azure Services Developer Portal

To implement Windows Live ID, you must register the application at the Azure Services Developer Portal and receive an application ID for use with the service.

When users browse to the site, the application presents them with a link to log in using a Live ID. Users can click the link to access the Windows Live site and authenticate using their Live ID credentials. After successfully authenticating, the Live ID site redirects them back to a page that you set up when you register the application.

To specify the URL of the return page, you must determine the port used by the application when running in the development fabric. By default, the application uses port 80. However, if the port is in use when the application starts, the development fabric assigns a different port number, usually the next one available.

In this task, you execute the application to determine the port number used in your environment. Then, you register the application in the Azure Services Developer Portal.

1. Open Microsoft Visual Studio 2008 in elevated administrator mode, from Start | All Programs | Microsoft Visual Studio 2008 by right clicking the Microsoft Visual Studio 2008 shortcut and choosing Run as Administrator.

Page | 38

Page 39: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

2. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex2-UsingLiveID\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.

Note: 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 WebFormAzureStore project, right-click Products.aspx and select Set As Start Page.

3. Press F5 to build and run the application.

4. Open the development fabric UI by right clicking its icon in the system tray and selecting Show Development Fabric UI.

Figure 25Opening the development fabric UI

5. In the Development Fabric, select Service Details for the current deployment. Take note of the value shown in the IP Address column and in particular, the port number used. You will use this value shortly when you register the application in the Azure Services Developer Portal.

Page | 39

Page 40: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 26Determining the port number assigned by the development fabric

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

Note: If you previously completed the Building ASP.NET MVC Applications with Windows Azure lab and have already created the AzureAuthentication project in the Azure Services Developer Portal as well as registered a domain name for the application in your hosts file, then you may skip the remaining steps in this task.

However, you will need the values that the portal assigned to the project for its application ID and secret key. You can retrieve these settings by visiting the portal or from the Web.config file in the solution you created for the MVC Application lab.

7. Go to the Azure Services Developer Portal.

8. Sign in using your Windows Live ID.

9. If this is your first visit to this site, create a new developer portal account; otherwise, skip to step 12.

10. Review the privacy statement and click I Agree to proceed.

Page | 40

Page 41: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 27Creating a new developer portal account

11. Wait until account provisioning is complete and click Continue.

Figure 28Account successfully created

12. If not already selected, choose the Live Services tab and then click New Service.

Page | 41

Page 42: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 29Creating a new service component

13. Next, click Live Services: Existing APIs to create a new service component.

Figure 30Registering a new application

14. If this is your first service component, you must accept the terms of use before you can proceed. Review the terms of use document and click I Accept to continue.

Page | 42

Page 43: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 31Accepting the terms of use

15. Create a new service component to register the application for this exercise. In the Service Component Properties, fill in the form fields as shown below.

Field Value

Service Component Label Azure Authentication

Service Component Description

Windows Azure Platform Kit

Domain <yourdomain>

Return URL http://<yourdomain>:<portnumber>/LiveID/auth-handler.ashx

Note: The Domain value shown above as <yourdomain> is a placeholder for a domain name that identifies your service component. Choose a value that is unique and follows domain-naming rules. It is not necessary for the domain to be registered. Be aware that you cannot choose a domain that is already in use by other service components in the Azure Services Developer Portal. If another registered component already uses the name you select, you will be notified. Choose a different domain name and re-submit the form.

The return URL is the URL of the page on your Web site to which the Windows Live ID authentication service redirects users after they have successfully signed in, signed out, or cleared their cookies. The port number in the Return URL field shown above as <portnumber>, is the port at which the application listens when running in the development fabric in your environment, which you determined previously in this task.

For more information, see Getting Your Application ID for Web Authentication.

Page | 43

Page 44: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 32Creating a new service component

16. Click Create to register your service component in the portal. The component management page shows the Application ID and Secret Key assigned to the component. You will use these values in the next task to configure the application.

Page | 44

Page 45: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 33Retrieving the Application ID and Secret Key values

17. Create an entry for the chosen domain in your hosts file. Open a command prompt with administrator privileges. Change the current directory to Assets in the Source folder of the lab and execute the following command, where <yourdomain> is the domain name chosen in the previous step.

Command Prompt

updatehostsfile <yourdomain>

For example, to add the domain store.azureplatformkit.com to your hosts file, execute the following command.

updatehostsfile store.azureplatformkit.com

Page | 45

Page 46: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 34Creating an entry in the hosts file for the chosen domain

Task 2 - Adding Live ID Authentication to the Application

After users successfully sign in or out, the Windows Live ID service responds by redirecting them to your Web site—specifically to the return URL that you specified when you registered your service component. The Azure Store solution includes a handler named auth-handler.ashx in the LiveID folder that receives and appropriately processes this response. The handler implementation is based on code available in the Windows Live ID SDK. For more information, see Handling the Response from the Service.

In this task, you modify the Azure Store site to enable Windows Live ID authentication. To do this, you update the log in page to include a Windows Live Authentication section that contains an IFRAME element pointing at the Live ID service. Next, you create a method to register new users and associate their Windows Live ID with their account in the membership database. Then, you update the LogOff action to sign out from Live ID. Finally, you configure the settings used by the code that handles the response from the service.

1. Update the login form of the application to incorporate a Windows Live Authentication section. Open the Login.aspx page and insert the following (highlighted) markup immediately below the <h1> tag.

Note: The markup displays a Web authentication sign-in link by using an iframe with a specially crafted source URL that points to the Windows Live ID authentication site. For more information, see Displaying a Sign-in Link.

Page | 46

Page 47: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

ASP.NET (C#)

...<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h1>Welcome to the Azure Store</h1> <fieldset> <legend>Windows Live Authentication</legend> <p>Now you can sign in using your LiveID account:</p> <p> <iframe id="WebAuthControl" name="WebAuthControl" src="http://login.live.com/controls/WebAuthButton.htm?appid=<%=ConfigurationManager.AppSettings["wll_appid"]%>&context=myContext&style=font-size%3A+10pt%3B+font-family%3A+verdana%3B+background%3A+white%3B" width="80px" height="20px" marginwidth="0" marginheight="0" align="middle" frameborder="0" scrolling="no" style="border-style: hidden; border-width: 0"></iframe> </p> </fieldset> <fieldset> <legend>Forms Authentication</legend> <asp:Login ID="Login1" runat="server" CssClass="login" DisplayRememberMe="false" LoginButtonType="Link" TitleText="Please login to continue" DestinationPageUrl="~/Store/Products.aspx" /> </fieldset></asp:Content>...

ASP.NET (Visual Basic)

...<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h1>Welcome to the Azure Store</h1> <fieldset> <legend>Windows Live Authentication</legend> <p>Now you can sign in using your LiveID account:</p> <p> <iframe id="WebAuthControl" name="WebAuthControl" src="http://login.live.com/controls/WebAuthButton.htm?appid=<%=ConfigurationManager.AppSettings("wll_appid")%>&context=myContext&style=font-size%3A+10pt%3B+font-family%3A+verdana%3B+background%3A+white%3B" width="80px" height="20px" marginwidth="0" marginheight="0"

Page | 47

Page 48: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

align="middle" frameborder="0" scrolling="no" style="border-style: hidden; border-width: 0"></iframe> </p> </fieldset> <fieldset> <legend>Forms Authentication</legend> <asp:Login ID="Login1" runat="server" CssClass="login" DisplayRememberMe="false" LoginButtonType="Link" TitleText="Please login to continue" DestinationPageUrl="~/Store/Products.aspx" /> </fieldset></asp:Content>...

2. Next, add a method to register users signing in with a Windows Live ID. Open the code-behind file for the NewLiveUser.aspx page inside the LiveID folder and insert the following (highlighted) code into the body of the OnRegisterUser method.

(Code Snippet – Building Web Form Applications with Windows Azure - Ex02 OnRegisterUser method - C#)

C#

protected void OnRegisterUser(object sender, EventArgs e){ WindowsLive.WindowsLiveLogin wll = new WindowsLive.WindowsLiveLogin(true);

WindowsLive.WindowsLiveLogin.User WLIDUser = wll.ProcessToken(this.Request.Cookies["webauthtoken"].Value);

Guid providerUserKey = new Guid(WLIDUser.Id); MembershipCreateStatus status; MembershipUser user = Membership.CreateUser( this.userName.Text, Membership.GeneratePassword(12, 2), this.email.Text, null, null, true, providerUserKey, out status); Roles.AddUserToRole(this.userName.Text, this.roles.SelectedItem.Text);

FormsAuthentication.RedirectFromLoginPage(this.userName.Text, true); Response.Redirect("~/Store/Products.aspx");

Page | 48

Page 49: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

}

(Code Snippet – Building Web Form Applications with Windows Azure - Ex02 OnRegisterUser method - VB)

Visual Basic

Protected Sub OnRegisterUser(ByVal sender As Object, ByVal e As EventArgs) Dim wll As New WindowsLive.WindowsLiveLogin(True)

Dim WLIDUser As WindowsLive.WindowsLiveLogin.User = wll.ProcessToken(Me.Request.Cookies("webauthtoken").Value)

Dim providerUserKey As New Guid(WLIDUser.Id) Dim status As MembershipCreateStatus Dim user As MembershipUser = Membership.CreateUser(Me.userName.Text, Membership.GeneratePassword(12, 2), Me.email.Text, Nothing, Nothing, True, providerUserKey, status) System.Web.Security.Roles.AddUserToRole(Me.userName.Text, Me.roles.SelectedItem.Text)

FormsAuthentication.RedirectFromLoginPage(Me.userName.Text, True) Response.Redirect("~/Store/Products.aspx")End Sub

Note: The OnRegisterUser method decodes and validates a Windows Live ID web authentication token to create a User object and obtain its Id property. It then creates a new user in the membership database using this ID and the username, email, and role name obtained from the registration form.

3. Finally, update the log out sequence to sign out the Live ID session. Open the code-behind file for the Site.Master master page, locate the OnLoggedOut method and insert the following (highlighted) code block that redirects to the logout URL when users sign off after having signed in using a Live ID.

(Code Snippet – Building Web Form Applications with Windows Azure - Ex02 OnLoggedOut method - C#)

C#

protected void OnLoggedOut(object sender, EventArgs e){ this.Session.Clear();

Page | 49

Page 50: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

// check if Live ID authentication cookie is present if (Request.Cookies["webauthtoken"] != null) { // retrieve the log-out URL var wll = new WindowsLive.WindowsLiveLogin(true); string logoutUrl = wll.GetLogoutUrl(); Response.Redirect(logoutUrl); }}

(Code Snippet – Building Web Form Applications with Windows Azure - Ex02 OnLoggedOut method - VB)

Visual Basic

Protected Sub OnLoggedOut() Me.Session.Clear()

' check if Live ID authentication cookie is present If Request.Cookies("webauthtoken") IsNot Nothing Then ' retrieve the log-out URL Dim wll = New WindowsLive.WindowsLiveLogin(True) Dim logoutUrl As String = wll.GetLogoutUrl() Response.Redirect(logoutUrl) End IfEnd Sub

4. To complete the task, configure the application ID and secret key settings for the application. Open the Web.config file in the root folder of the WebFormAzureStore project and locate the <appSettings> section. In this section, replace the value of the wll_appid and wll_secret settings with the application ID and secret key values that you recorded when you registered the application in the Azure Services Developer Portal.

Figure 35Configuring the Live ID settings for the application

The application ID is a 16-character string that represents your application. The secret key is a security key that Windows Live ID uses to encrypt and sign all tokens that it sends to your site.

Page | 50

Page 51: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

5. Press F5 to build and run the application.

6. In the application’s log in page, under the Windows Live Authentication section, click Sign in.

Figure 36Logging in using Windows Live ID

7. In the Windows Live log in page, enter your Live ID credentials and click Sign In.

Page | 51

Page 52: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 37Signing in to Windows Live

8. After successfully signing in, the application shows a registration page where you can associate your Live ID with a new account in the membership database. Fill in the registration form and click Register.

Page | 52

Page 53: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 38Registering your Live ID at the site

9. After associating your Live ID account with the site, the application displays its products page. Notice the user name in the upper right corner of the window. It should match the name you specified when you registered the account

Page | 53

Page 54: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

Figure 39Successful authentication using a Live ID

10. Click Logout in the upper right corner of the window to close your session.

11. In the Log on page, click Sign In once again. Notice that in this occasion, because you previously registered your Live ID with the membership provider, you proceed straight to the products page.

12. Close the browser window to shut down 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

Page | 54

Page 55: Building ASP.NET Web Form Applications with …skydev.pha.jhu.edu/.../Lab.docx · Web viewWindows Azure: Building ASP.NET Web Form Applications with Windows Azure Lab version:1.0.0

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. Finally, you learnt how to take advantage of Windows Live ID to authenticate users in your Windows Azure application.

Page | 55