Partager via


Walkthrough: Maintaining Web Site User Information with Profile Properties

ASP.NET profile properties allow your application to track and permanently store user-specific information. For example, users can specify a postal code or a favorite color scheme, and your application can store that information and retrieve it from anywhere in the application. ASP.NET automatically matches the current user — whether the user is anonymous or logged on — with the personal information that is stored for their user account.

This walkthrough shows you how to add profile properties to your application and use the profile properties to create a personalized experience for visitors to the Web site.

During this walkthrough, you will learn how to do the following:

  • Configure an application to use profile properties.

  • Define simple and complex profile properties that you want to maintain for users.

  • Maintain profile properties for both anonymous and logged-on users.

  • Set and retrieve profile values in your application.

Prerequisites

In order to complete this walkthrough, you will need the following:

  • Microsoft Visual Studio.

  • The Microsoft .NET Framework.

  • Microsoft SQL Server Standard or SQL Server Express.

    The profile property information that you create in the walkthrough will be stored in a SQL Server database.

  • Cookies enabled on your browser.

    Note

    ASP.NET profile properties can work without cookies, if the application is configured to work without cookies. However, for this walkthrough you will use the default configuration settings for profile properties, which use cookies.

Creating and Configuring the Web Site

If you have already created a Web site in Microsoft Visual Studio by completing Walkthrough: Creating a Basic Web Forms Page in Visual Studio, you can use that Web site and go to the next section. Otherwise, create a new Web site.

Note

This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio.

To create a file system Web site

  1. Open Visual Studio.

  2. On the File menu, point to New, and then click Web Site (or on the File menu, click New Web Site).

    The New Web Site dialog box appears.

  3. Under Installed templates, click the language that you want to work with.

  4. In the list of templates, select ASP.NET Empty Web Site.

  5. In the left-most Location list, click File System.

  6. In the right-most Location list, enter the name of the folder where you want to keep the pages of the Web site.

    For example, type the folder name C:\WebSites.

  7. In the Language list, click the programming language that you prefer to work in.

  8. Click OK.

    Visual Studio creates the folder and a new page named Default.aspx.

Configuring Profile Properties

You will begin by configuring your application to enable profile properties. You will then define the first property that you want to track for each user. This property is named PostalCode and will be tracked for both anonymous and logged-on users.

To configure the Web site for the PostalCode property

  1. In Solution Explorer, determine whether the Web site already has a Web.config file.

    If the Web site has a Web.config file, open it. If the Web site does not have a Web.config file, follow these steps:

    1. Right-click the name of the Web site.

    2. Click Add New Item.

    3. In the list of templates, click Web Configuration File.

    4. Click Add.

      A new file that is named Web.config is added to the site and is opened in the editor.

  2. Add the following profile element to the Web.config file as a child of the system.web element:

    <system.web>
    
      <anonymousIdentification enabled="true" />
      <profile>
        <properties>
          <add name="PostalCode" 
            type="System.String" 
            allowAnonymous="true" />
        </properties>
      </profile>
    
    <!-- other Web.config settings here -->
    </system.web>
    

    Note

    Elements in the Web.config file are case sensitive. Therefore, make sure that you copy or type the elements exactly as shown.

    You have added the following elements:

    • The anonymousIdentification element, which specifies whether profile properties work only with logged-on (authenticated) users or with both logged-on and anonymous users.

      In this case, you have set enabled to true. Therefore, profile property information will be tracked for both logged-on and anonymous users.

    • The properties element, which contains all profile properties that you are defining.

    • The add element, which defines a new profile element.

      In this case, you have defined a single profile property named PostalCode.

      When you define a profile property, you specify its data type using a .NET Framework–type class name. You also specify whether the profile property will be tracked for anonymous users. After enabling anonymous identification, you can additionally specify whether to track profile properties individually for anonymous users.

      You would create a new add element for each additional profile property that you wanted to define.

      Note

      By default, user profile information is stored in a SQL Server database in the Application_Data subdirectory of the Web site. This walkthrough uses the default configuration. In production applications that will support a significant number of users, it is better to store profile property data in a server-based (rather than file-based) Microsoft SQL Server database. For more information, see "Next Steps" later in this walkthrough.

Setting and Getting the PostalCode Property

In this section, you will create a page that shows how to set and get the PostalCode value that you defined in the preceding section.

To create a page that sets and gets the PostalCode property

  1. Add a new Web page to your site named Profiles.aspx. Make sure that the Place code in separate file check box is selected.

  2. Open Profiles.aspx and switch to Design view.

  3. From the Standard group in the Toolbox, drag the controls listed in the following table onto the page, and then set their properties as noted.

    Control

    Property settings

    TextBox

    ID = PostalCodeTextBox

    Button

    ID = SetPostalCodeButton

    Text = Set Postal Code

    Label

    ID = PostalCodeLabel

    Text = (empty)

  4. Double-click the Set Postal Code button to add a handler for the button's Click event.

  5. In the SetPostalCodeButton_Click handler, add code that sets the PostalCode profile property, as shown in the following example:

    Protected Sub SetPostalCode_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        Profile.PostalCode = Server.HtmlEncode(PostalCodeTextBox.Text)
        PostalCodeLabel.Text = Profile.PostalCode
    End Sub
    
    protected void SetPostalCode_Click(object sender, System.EventArgs e)
    {
        Profile.PostalCode = Server.HtmlEncode(PostalCodeTextBox.Text);
        PostalCodeLabel.Text = Profile.PostalCode;
    }
    

    When user profile properties are enabled, ASP.NET dynamically creates a property named Profile that adds the user profile to the current context. The individual profile properties are then available through Profile.PostalCode.

  6. Add code that displays the Profile.PostalCode to the Page_Load handler, as shown in the following example:

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        PostalCodeLabel.Text = Profile.PostalCode
    End Sub
    
    void Page_Load(object sender, System.EventArgs e)
    {
        PostalCodeLabel.Text = Profile.PostalCode;
    }
    

    This code will display the Profile.PostalCode value every time that the page is requested.

Testing the PostalCode Profile Property

You can now test the PostalCode property that you defined in the preceding section. You will at first work as an anonymous user. Behind the scenes, ASP.NET will assign you a unique, anonymous ID that is stored in a cookie on the computer. ASP.NET can use this anonymous ID to set and get values that are unique to you.

Note

If you are working with an existing Web site that has membership enabled, make sure that you are logged off.

To test the PostalCode property

  1. Right-click Profiles.aspx and click Set as Start Page.

  2. Press CTRL+F5 to run the Profiles.aspx page.

    It might take a while for the page to display the first time you make a page request to the site, because ASP.NET is creating the SQL Server database that it uses to store profile information in.

    Note

    If the browser displays a 502 error or an error indicating that the page cannot be displayed, you might need to configure your browser to bypass proxy servers for local requests. For detailed information, see How to: Bypass a Proxy Server for Local Web Requests.

  3. In the box, type a postal code, and then click Set Postal Code.

    The postal code that you entered appears in the Label control.

  4. Close the browser to close your current session.

  5. Press CTRL+F5 to run the Profiles.aspx page again.

    The postal code that you entered earlier appears in the Label control.

The last step in the preceding procedure illustrated that ASP.NET stores the PostalCode value. When you visit the page again, ASP.NET reads the PostalCode value based on your unique anonymous ID.

Defining Complex Properties

In "Setting and Getting the PostalCode Property," earlier in this walkthrough, you created a simple property named PostalCode that was stored as a string. In this section, you will define a property named FavoriteURLs that is a collection. ASP.NET can store profile properties of any type, but you must provide additional information when you are defining complex profile properties.

To define the FavoriteURLs property

  1. Open the Web.config file.

  2. Add a new property named "FavoriteURLs" element to the profile element that you created in "Configuring Profile Properties," earlier in this walkthrough, as shown in the following example:

    <anonymousIdentification enabled="true" />
      <profile>
        <properties>
        <add name="PostalCode" 
          type="System.String" 
          allowAnonymous="true" />
        <add name="FavoriteURLs" 
          type="System.Collections.Specialized.StringCollection"
          allowAnonymous="true" />
        </properties>
      </profile>
    

    You have added a new profile property named FavoriteURLs. For profile properties that are not simple types (such as string or integer), you must specify the fully qualified type. Here, you are specifying that the profile property will be a collection that will hold strings.

  3. Save and close the Web.config file.

Setting and Getting the FavoriteURLs Property

Working with the FavoriteURLs property, which is a collection, is much like working with a collection in any context. In this part of the walkthrough, you will update the Profiles.aspx page that you created in "Setting and Getting the PostalCode Property," earlier in this walkthrough, by adding a TextBox control in which users can type a URL. When the user clicks Add, the URL is added to the FavoriteURLs property. You will display the current list of favorite URLs in a drop-down list box.

To set and get the FavoriteURLs property

  1. On the Profiles.aspx page, add the following controls and set their properties as noted in the following table.

    Control

    Property settings

    TextBox

    ID = FavoriteURLTextBox

    Button

    ID = AddURLButton

    Text = Add URL

    ListBox

    ID = FavoriteURLsListBox

  2. Double-click the Add URL button to add a handler for the button's Click event.

  3. In the AddURLButton_Click handler, add code to add a URL to the list, as shown in the following example:

    Protected Sub AddURL_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        Dim urlString As String = _
            Server.HtmlEncode(FavoriteURLTextBox.Text)
        If Profile.FavoriteURLs Is Nothing Then
            Profile.FavoriteURLs = New _
                System.Collections.Specialized.StringCollection
        End If
        Profile.FavoriteURLs.Add(urlString)
        DisplayFavoriteURLs()
    End Sub
    
    protected void AddURL_Click(object sender, System.EventArgs e)
    {    
        String urlString = Server.HtmlEncode(FavoriteURLTextBox.Text);
        if(Profile.FavoriteURLs == null)
        {
            Profile.FavoriteURLs = new 
                System.Collections.Specialized.StringCollection();
        }
        Profile.FavoriteURLs.Add(urlString);
        DisplayFavoriteURLs();
    }
    
  4. In the Page_Load handler, add code to display the URL list, as shown in the following example:

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        labelPostalCode.Text = Profile.PostalCode
        DisplayFavoriteURLs()
    End Sub
    
    void Page_Load(object sender, System.EventArgs e)
    {
        labelPostalCode.Text = Profile.PostalCode;
        DisplayFavoriteURLs();
    }
    
  5. Add the following subroutine to update the display of the URLs in the ListBox control.

    Sub DisplayFavoriteURLs()
        FavoriteURLsListBox.DataSource = Profile.FavoriteURLs
        FavoriteURLsListBox.DataBind()
    End Sub
    
    void DisplayFavoriteURLs()
    {    
        FavoriteURLsListBox.DataSource = Profile.FavoriteURLs;
        FavoriteURLsListBox.DataBind();
    }
    

Testing the FavoriteURLs Profile Property

You can now test the FavoriteURLs property.

To test the FavoriteURLs property

  1. To run the Profiles.aspx page, press CTRL+F5.

    At first there are no values in the ListBox control.

  2. In the box, type a URL, and then click Add.

    The URL is added to the ListBox control.

  3. Repeat the preceding step to add another URL.

  4. Close the browser.

  5. To run the Profiles.aspx page again, press CTRL+F5.

    Notice that the ListBox control is populated with the URLs that you entered before closing the browser.

Migrating Profile Properties During Log On

If a user first visits your site as an anonymous user, but then logs on, you might want to preserve the property settings that were established when the user was anonymous. A typical example is a shopping site where the user might browse and add items to a shopping cart as an anonymous user, but then log on to check out. To preserve a user's values when they log on, you migrate the user from the current anonymous user profile to the user profile that they have as a logged-on user (authenticated).

In this section, you will migrate the user's PostalCode setting. You must have a Web site that is already configured to use user identities and that has a logon page. If the Web site that you are working with has not already been configured for membership, use the following procedure to enable it. If your site already supports membership, you can go to the next section.

To configure the Web site for membership

  1. In Visual Studio, on the Website menu, click ASP.NET Configuration.

    The Web Site Administration Tool appears.

  2. Click the Security tab.

  3. Under Users, click Select authentication type.

  4. Select From the internet, and then click Done.

    TheFrom the internet option specifies that your application will use Forms authentication, where users will log on to the application by using a logon page.

  5. On the Security tab, under Users, click Create user, and then create a user account.

    You can use any name and password, but make sure that you remember the name and password. For the e-mail address, use your own. (You will not be sending e-mail messages in this walkthrough.)

  6. After finishing the user account definition, close the Web Site Administration Tool.

  7. Open the Profiles.aspx page.

  8. From the Login group in the Toolbox, drag a Login control and a LoginName control onto the page.

    The LoginName control is not required for log on, but will help you see that you are logged on.

Creating a Migrating Handler

To migrate the settings for an anonymous user to the settings for a logged-on user, you must perform the migration when the user's identity is changing. ASP.NET provides the MigrateAnonymous event for exactly this purpose; in the handler for the MigrateAnonymous event, you can transfer the settings that you want to preserve.

To create a migration handler

  1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.

  2. In the list of templates, click Global Application Class, and then click Add.

    You do not have to enter a name, because the file is always named Global.asax.

  3. Type the following code to create a new handler for the MigrateAnonymous event.

    Sub Profile_MigrateAnonymous(ByVal sender As Object, _
        ByVal e As ProfileMigrateEventArgs)
        If Profile.GetProfile(e.AnonymousID).PostalCode <> "" Then
            Profile.PostalCode = _
                Profile.GetProfile(e.AnonymousID).PostalCode
        End If
    End Sub
    
    void Profile_MigrateAnonymous(Object sender, 
            ProfileMigrateEventArgs e)
    {
        if(Profile.GetProfile(e.AnonymousID).PostalCode != String.Empty)
        {
            Profile.PostalCode = 
                Profile.GetProfile(e.AnonymousID).PostalCode;
        }
    }
    

    The code gets the user profile for the anonymous user and extracts the PostalCode value. Then, it gets the profile for the new user identity and sets the equivalent value for that identity.

Testing Migration

In order to test migration, you will first make some settings as an anonymous user. Then, you will log on and see that the values are preserved.

To test migration

  1. Open the Profiles.aspx page, and then press CTRL+F5 to run it.

    The LoginName control does not display anything, because you have not yet logged on.

  2. If a postal code is not displayed on the page, type a new postal code, and then click Set Postal Code.

    The postal code for your current anonymous identity is displayed on the page.

  3. Log on, using the user name and password that you created in "Migrating Profile Properties During Log On," earlier in this walkthrough.

    The LoginName control displays your user name. The postal code that you entered as an anonymous user is still displayed, because the postal code settings have been migrated to your logged-on user profile.

Next Steps

This walkthrough has illustrated the basic procedures for configuring and using profile properties in Web applications. You can use profile properties for many purposes in your applications. The following list suggests additional areas where you might want to work with profile properties:

See Also

Reference

System.Web.Profile

ProfileModule

Concepts

ASP.NET Profile Properties Overview

ASP.NET Profile Providers