Export (0) Print
Expand All

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.

  • Set and retrieve Profile values in your application.

  • Use Profile properties that have both anonymous and logged-on users.

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

  • Microsoft Visual Web Developer.

  • The Microsoft .NET Framework.

  • Microsoft SQL Server Standard Edition.

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

  • Cookies enabled on your browser.

    NoteNote

    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.

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

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 Visual Studio installed templates, click ASP.NET Web Site.

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

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

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

  7. Click OK.

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

Before you work with ASP.NET Profile properties, you will configure your application to enable and define the Profile properties that you want to track for each user. To start, you will create a single PostalCode property that the Web site will track for users. You will also configure the PostalCode property so that your site can track it for both anonymous and logged-on users.

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

To configure Profile properties in the Web site

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

    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. Under Visual Studio installed templates, click Web Configuration File.

    4. Click Add.

      A new file 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>
    
    NoteNote

    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.

      NoteNote

      By default, user profile information is stored in a SQL Server Standard Edition 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 Microsoft SQL Server database. For more information, see "Next Steps," later in this walkthrough.

After you have configured the Web site to track a Profile property, you can set and get the Profile property as you would ordinary component properties. 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 to set and get the PostalCode property

  1. Add a new Web page to your site named Profiles.aspx.

  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 = textPostalCode

    Button

    ID = SetPostalCode

    Text = Set Postal Code

    Label

    ID = labelPostalCode

    Text = (empty)

  4. Switch to Source view, and then add the following attribute to the SetPostalCode button, if the attribute does not exist.

    OnClick="SetPostalCode_Click"
    
  5. Create a Click handler for Set Postal Code, and then add the following highlighted code.

    Sub SetPostalCode_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        Profile.PostalCode = Server.HtmlEncode(textPostalCode.Text)
        labelPostalCode.Text = Profile.PostalCode
    End Sub
    

    void SetPostalCode_Click(object sender, System.EventArgs e)
    {
        Profile.PostalCode = Server.HtmlEncode(textPostalCode.Text);
        labelPostalCode.Text = Profile.PostalCode;
    }
    

    When the user profile is 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. Create a Page_Load handler, and then add the following highlighted code.

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        labelPostalCode.Text = Profile.PostalCode
    End Sub
    

    void Page_Load(object sender, System.EventArgs e)
    {
        labelPostalCode.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.

NoteNote

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. Press CTRL+F5 to run the Profiles.aspx page.

    NoteNote

    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.

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

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

  3. Close the browser to close your current session.

  4. Reopen the browser, and then request the Profiles.aspx page.

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

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

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 the Profile property.

To define the FavoriteURLs property

  1. Open the Web.config file.

  2. Add the following highlighted element to the profile element that you created in "Configuring Profile Properties," earlier in this walkthrough:

    <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 then close the Web.config file.

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 also 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 = textFavoriteURL

    Button

    ID = AddURL

    Text = Add URL

    ListBox

    ID = listFavoriteURLs

  2. Switch to Source view, and then add the following attribute to the Add URL button, if the attribute does not exist.

    OnClick="AddURL_Click"
    
  3. Create a Click handler for Add URL, and then add the following highlighted code.

    Sub AddURL_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        Dim urlString As String = _
            Server.HtmlEncode(textFavoriteURL.Text)
        If Profile.FavoriteURLs Is Nothing Then
            Profile.FavoriteURLs = New _
                System.Collections.Specialized.StringCollection
        End If
        Profile.FavoriteURLs.Add(urlString)
        DisplayFavoriteURLs()
    End Sub
    

    void AddURL_Click(object sender, System.EventArgs e)
    {    
        String urlString = Server.HtmlEncode(textFavoriteURL.Text);
        if(Profile.FavoriteURLs == null)
        {
            Profile.FavoriteURLs = new 
                System.Collections.Specialized.StringCollection();
        }
        Profile.FavoriteURLs.Add(urlString);
        DisplayFavoriteURLs();
    }
    
    
  4. In the Page_Load handler, add the following highlighted line of code.

    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()
        listFavoriteURLs.DataSource = Profile.FavoriteURLs
        listFavoriteURLs.DataBind()
    End Sub
    

    void DisplayFavoriteURLs()
    {    
        listFavoriteURLs.DataSource = Profile.FavoriteURLs;
        listFavoriteURLs.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. Reopen the browser, and then open the Profiles.aspx page.

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

If a user first visits your site as an anonymous user, but then logs on, you might want to preserve the property settings that the user established when 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. Click Security, and then under Users, click Select authentication type.

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

    The From 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. 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. Under Visual Studio installed 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.

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:

Community Additions

ADD
Show:
© 2014 Microsoft