Learn Ethical Hacking, SQL Injection and XSS Script.

Protect your website from SQL Injection, XSS Script and avoid vulnerability.

Learn SharePoint 2010,MOSS and Convert ASP.Net application to SharePoint

Learn Dotnet,SQL,NO-SQL ,C#,VB.NET,Java Script,Dotnet Open source project.

Check the free hosting in LINUX and Windows Server

Using the Azure ASP.NET Providers with Web Form Applications

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

Task 1 – Configuring Authenticated Access to the Application

In this task, you configure the application to require authenticated access to the pages that implement the shopping cart.
  1. If necessary, open Visual Studio 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. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex3-UsingAzureProvidersWithWebApps\Begin in the Source folder of the lab, select Begin.sln in the folder for the language of your preference (Visual C# or Visual Basic) and click Open. Alternatively, you may continue with the solution that you completed during Exercise 1.
  3. Configure authorization for the Store folder to require authenticated access. Open the Web.config file of the AzureStore project and insert the following (highlighted) configuration block as a direct child of the <configuration> element.(Code Snippet – Building ASP.NET Applications with Windows Azure - Ex03 Configuring Authorization)
    XML
    <?xml version="1.0"?>
    <configuration>
      ...
    1.   <location path="Store">
    2.     <system.web> 
    3.       <authorization>
    4.         <deny users="?"/>
    5.         <allow users="*"/>
    6.       </authorization>
    7.     </system.web>
    8.   </location>
    </configuration>
  4. Press CTRL + S to save the Web.config file.

Task 2 – Configuring Membership Support Using the Azure TableStorageMembershipProvider

In this task, you add and configure the Azure ASP.NET providers for membership, role, and session.
  1. Add the Windows Azure ASP.NET Providers project to the solution. In Solution Explorer, 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 and is based on the original source code found in the MSDN Code Gallery. The project contains the implementation of ASP.NET application providers for membership, role, profile, and session state.
  2. Add a reference in the web role to the AspProviders project. In Solution Explorer, right-click the AzureStore project node and click Add Reference. In the Add Reference dialog, switch to the Projects tab, select the AspProviders project and click OK.
    Figure 1Adding a reference to the sample Azure ASP.NET Providers project
  3. Update the service configuration to include a connection string to the Azure Storage account where the data will be stored. In the AzureStoreService project, expand the Roles node and double-click the AzureStore node to open the properties window for this role.
  4. In the AzureStore[Role] properties window, select the Settings tab and click Add Setting. Set the Name of the new setting to DataConnectionString and change the Type to ConnectionString. Then, in the Value column, click the button labeled with an ellipsis.
    Figure 2Creating a new configuration setting for the role
  5. In the Storage Account Connection String dialog, choose the option labeled Use the Windows Azure storage emulator and click OK.
    Figure 3Configuring a storage connection string
  6. Press CTRL + S to save your changes to the role configuration.
  7. Open the Web.config file located in the root folder of the AzureStore project.
  8. (Optional) Configure the storage account information required by the ASP.NET providers in the application configuration file. To do this, locate the <appSettings> element, which should be empty, and replace it with the following configuration block. If the appSettings element is missing, insert it as a direct child of the <configuration> element.
    Note:
    In addition to the service configuration file, you can also configure the Azure providers in the Web.config file of the application. This allows you to host the application outside the Azure fabric and still take advantage of the Azure ASP.NET providers and Azure storage. However, when the application runs in the Windows Azure environment, configuration settings in the service configuration file for the ASP.NET providers take precedence over those in the Web.config file. By using the Windows Azure settings, you can avoid redeploying the application when changing provider settings.
    (Code Snippet – Building ASP.NET Applications with Windows Azure - Ex03 DataConnectionString)
    XML
    <configuration>
      ...
    1.   <appSettings>
    2.     <add key="DataConnectionString" value="UseDevelopmentStorage=true"/>
    3.   </appSettings>
      ...
    </configuration>
  9. Configure the application to use the membership provider in the AspProviders project. To do this, replace the existing <membership> section inside the <system.web> element with the following (highlighted) configuration.
    Note:
    The default ASP.NET Web Application template in Visual Studio creates the configuration settings for the AspNetSqlMembershipProvider, which uses SQL Server for storage.
    (Code Snippet – Building ASP.NET Applications with Windows Azure - Ex03 TableStorageMembershipProvider)
    XML
    <configuration>
      ...
      <system.web>
        ...
        <authentication mode="Forms">
          ...
        </authentication>
    
    
    

    1.     <!-- Membership Provider Configuration -->
    2.     <membership defaultProvider="TableStorageMembershipProvider" userIsOnlineTimeWindow="20" hashAlgorithmType="HMACSHA256">
    3.       <providers>
    4.         <clear/>
    5.         <add name="TableStorageMembershipProvider"
    6.              type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageMembershipProvider"
    7.              description="Membership provider using table storage"
    8.              applicationName="AzureStore"
    9.              enablePasswordRetrieval="false"
    10.              enablePasswordReset="true"
    11.              requiresQuestionAndAnswer="false"
    12.              minRequiredPasswordLength="1"
    13.              minRequiredNonalphanumericCharacters="0"
    14.              requiresUniqueEmail="true"
    15.              passwordFormat="Hashed"/>
    16.       </providers>
    17.     </membership>
      </system.web>
      ...
    </configuration>
    Note:
    Important: Before you execute the solution, make sure that the start-up project and the start-up page are set. To set the start up project, in Solution Explorer, right-click the AzureStoreService project and select Set as StartUp Project.
    To designate the start page, in Solution Explorer, right-click the AzureStore project and select Properties. In the Properties window, select the Web tab and in the Start Action, select Specific Page. For the Web Form project, set the value of this field to Store/Products.aspx.
  10. Press F5 to build and run the application. An initialization procedure may be required the first time you execute an application that uses the Windows Azure storage emulator. If this happens, wait until the procedure is complete and review its status. Click OK to continue.
    Figure 4Development storage initialization procedure status
  11. Notice that the application redirects you to the log in page when it starts because the authorization settings now require authenticated access to the Home controller. The membership database is initially empty, so you first need to create an account before you can proceed. In the log in page, click Register to access the user registration form.
    Figure 5Authentication required to proceed
  12. Fill in the registration form and click Create User to register your account.
    Figure 6Creating a new user account
  13. Once you complete the wizard, the application displays a confirmation message. Click Continue to proceed to the products page.
    Figure 7Account successfully created
  14. After creating your account, the system automatically logs you in and displays the products page. Notice your user name displayed in the upper right corner of the window.
    Figure 8Products page displaying the current user
  15. Close the browser window to stop the running application.

Task 3 – Configuring Role Support Using the Azure TableStorageRoleProvider

In this task, you add role support to the application using the Azure role provider. This requires updating the registration process to capture the role of the user and configuring the settings for the role provider. To demonstrate the use of roles, you update the products page to filter the list of products based on the type of user.
  1. Update the registration process to assign a role to the user. Open Register.aspx in the Account folder and insert the following (highlighted) markup to add a new step in the CreateUserWizard control.(Code Snippet – Building Web Form Applications with Windows Azure - Ex03 Role WizardStep)
    HTML
    <asp:CreateUserWizard ID="CreateUserWizard1" runat="server" EnableViewState="true" >
      ...
      <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.
    Figure 9Adding an event handler for the CreatedUser event
  3. In Solution Explorer, right-click Register.aspx.cs (for a Visual C# project) or Register.aspx.vb (for a Visual Basic project) and then select View Code to open its code-behind file. Insert the following code to define the OnCreatedUser event handler.(Code Snippet – Building Web Form Applications with Windows Azure - Ex03 OnCreatedUser - C#)
    C#
    1. protected void OnCreatedUser(object sender, EventArgs e)
    2. {
    3.   var list =  (RadioButtonList)this.CreateUserWizard1.WizardSteps[0].FindControl("roles");
    4.   System.Web.Security.Roles.AddUserToRole(
    5.                              this.CreateUserWizard1.UserName,
    6.                              list.SelectedItem.Text);
    7. }
    (Code Snippet – Building Web Form Applications with Windows Azure - Ex03 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 - Ex03 Page_Load - C#)
    C#
    protected void Page_Load(object sender, EventArgs e)
    {
      CreateUserWizard1.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
    
    
    

    1.   if (!IsPostBack)
    2.   {
    3.     var list = (RadioButtonList)this.CreateUserWizard1.WizardSteps[0].FindControl("roles");
    4.     list.DataSource = System.Web.Security.Roles.GetAllRoles().OrderByDescending(a => a);
    5.     list.DataBind();
    6.     if (list.Items.Count > 0)
    7.     {
    8.       list.Items[0].Selected = true;
    9.     }
    10.   }
    }
    (Code Snippet – Building Web Form Applications with Windows Azure - Ex03 Page_Load - VB)
    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 user. Open Global.asax.cs (for Visual C# projects) or Global.asax.vb (for Visual Basic projects) and insert the following (highlighted) code into the Application_Start method.(Code Snippet – Building ASP.NET Applications with Windows Azure - Ex03 Initialize Roles - C#)
    C#
    protected void Application_Start()
    {
      ...
      LoadProducts();
    
    
    

    1.   // Initialize the application roles 
    2.   if (!System.Web.Security.Roles.RoleExists("Home"))
    3.   {
    4.     System.Web.Security.Roles.CreateRole("Home");
    5.   }
    6.   if (!System.Web.Security.Roles.RoleExists("Enterprise"))
    7.   {
    8.     System.Web.Security.Roles.CreateRole("Enterprise");
    9.   }
    }
    (Code Snippet – Building ASP.NET Applications with Windows Azure - Ex03 Initialize Roles - VB)
    Visual Basic
    Sub Application_Start()
      ...
      LoadProducts()
    
    
    

      ' Initialize the application roles 
      If (Not System.Web.Security.Roles.RoleExists("Home")) Then
        System.Web.Security.Roles.CreateRole("Home")
      End If
      If (Not System.Web.Security.Roles.RoleExists("Enterprise")) Then
        System.Web.Security.Roles.CreateRole("Enterprise")
      End If
    End Sub
  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 - Ex03 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

    1.   // filter product list for home users
    2.   if (User.IsInRole("Home"))
    3.   {
    4.     filteredProducts = filteredProducts.Where(item => item.Contains("Home"));
    5.   }
      foreach (var product in filteredProducts)
      {
        this.products.Items.Add(product);
      }
    }
    (Code Snippet – Building Web Form Applications with Windows Azure - Ex03 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
    Note:
    The inserted code appends an additional filter for users in the Home role that returns only items containing the text “Home”.
  7. Configure the application to use the role provider in the AspProviders project. In the Web.config file, replace the existing <roleManager> section inside the <system.web> element with the following (highlighted) configuration.
    Note:
    The default ASP.NET Web Application template in Visual Studio creates the configuration settings for the AspNetSqlRoleProvider, which uses SQL Server for storage, and the AspNetWindowsTokenRoleProvider, which uses Windows groups.
    (Code Snippet – Building ASP.NET Applications with Windows Azure - Ex03 TableStorageRoleProvider)
    XML
    <configuration>
      ...
      <system.web>
        ...
    1.     <!-- RoleManager Provider Configuration -->
    2.     <roleManager enabled="true"
    3.                  defaultProvider="TableStorageRoleProvider" 
    4.                  cacheRolesInCookie="true" 
    5.                  cookieName=".ASPXROLES" 
    6.                  cookieTimeout="30" 
    7.                  cookiePath="/" 
    8.                  cookieRequireSSL="false" 
    9.                  cookieSlidingExpiration="true" 
    10.                  cookieProtection="All">
    11.       <providers>
    12.         <clear/>
    13.         <add name="TableStorageRoleProvider"
    14.              type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageRoleProvider"
    15.              description="Role provider using table storage"
    16.              applicationName="AzureStore" />
    17.       </providers>
    18.     </roleManager>
        ...
      </system.web>
      ...
    </configuration>
  8. Press F5 to build and run the application.
  9. In the log in page, click Register to access the user registration form. Notice that the registration wizard now displays a section to specify the role of the customer. Create a new user and assign it a Home customer profile.
    Figure 10Registration page showing role information
  10. Logged in as a Home user, proceed to the products page. Notice that the list of products only includes home products.
    Figure 11Products 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.
    Figure 12Products 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.
    Figure 13Check 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.
    Figure 14Suspending the service role instance
  18. Open a command window in elevated administrator mode, from Start | All Programs | Accessories | Command Prompt by right clicking the Command Prompt shortcut and choosing Run as Administrator. At the command prompt, type iisreset.
    Figure 15Restarting Internet Information Server
    Note:
    These two steps, recycling the role and restarting IIS, simulate what would happen in Windows Azure when a role instance is restarted.
  19. Go back to the Compute Emulator and wait until the service is destroyed as indicated by the instance icon turning purple. 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 4 – 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 Windows Azure session state provider.
  1. Configure the application to use the session provider in the AspProviders project. To do this, in the Web.config file of the AzureStore project, insert the following (highlighted) configuration block as an immediate child of the <system.web> element.(Code Snippet – Building ASP.NET Applications with Windows Azure - Ex03 TableStorageSessionStateProvider)
    XML
    <configuration>
      ...
      <system.web>
        ...
    1.     <!-- SessionState Provider Configuration -->
    2.     <sessionState mode="Custom"
    3.                   customProvider="TableStorageSessionStateProvider">
    4.       <providers>
    5.         <clear/>
    6.         <add name="TableStorageSessionStateProvider"
    7.              type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider"
    8.              applicationName="AzureStore" />
    9.       </providers>
    10.     </sessionState>
        ...
      </system.web>
      ...
    </configuration>
  2. Press F5 to build and run the application.
  3. Log in and navigate to the products page. Select one or more products from the list and click Add item to cart. Repeat the process to store additional items in the cart.
  4. Click the Check Out link to view the contents of the shopping cart. Verify that the items you selected appear on the list.
  5. Do not close the browser window or navigate away from the checkout page.
  6. In the task bar, right-click the compute emulator icon and select Show Compute Emulator UI.
  7. In the Compute Emulator, right-click the AzureStoreService node and choose Suspend. Wait until the service is destroyed as indicated by the instance icon turning purple.
  8. Open a command window in elevated administrator mode, from Start | All Programs | Accessories | Command Prompt by right clicking the Command Prompt shortcut and choosing Run as administrator. At the command prompt, type iisreset.
  9. Now, restart the service instance once again. To do this, right-click the AzureStoreService node and choose Run, then wait for the service to start.
  10. Switch back to the browser window showing the check out page and click Refresh. Notice that the order is intact. This confirms that the session state can persist through application restarts when using the Azure provider.
  11. Close the browser window to stop the application.

source:http://msdn.microsoft.com