Previous Page
Next Page

Using Personalization

Using personalization is pretty straightforward. You basically define personalization properties in Web.Config. ASP.NET will synthesize a class you may use to manage personalization settings. At that point, profile information is available in much the same way as session state is available.

Defining Profiles in Web.Config

Profile schema is defined within Web.Config as name/type pairs. Imagine that in the course of designing your site, you decided you'd like to track the following information about a particular user:

Defining these properties is a matter of populating them in Web.Config. A definition for the properties listed above might look like this Web.Config:

   <profile automaticSaveEnabled="true" >
         <add name="NumVisits" type="System.Int32"/>
         <add name="UserName" type="System.String"/>
         <add name="Gender" type="bool">
         <add name="Birthday" type="System.DateTime">

The personalization properties consist of name/type pairs and will basically become the schema under which the personalization data will be stored. Once defined in the Web.Config file, the profile may be used in the site through the Profile property found in the current HttpContext (and is also available via the Page).

Use Profile Information

To use the profile in the Web site, you access it in much the same way you might access session state. However, instead of being represented by name/value pairs accessed through an indexer, the ASP.NET compiler will synthesize a profile object based upon the scheme defined in the Web.Config file.

For example, given the schema listed above, ASP.NET will synthesize a class named ProfileCommon, based upon the ProfileBase class. The synthesized class will reflect the instructions written into the Web.Config by inserting properties, shown here in bold:

public class ProfileCommon : ProfileBase
   public  virtual  HttpProfile GetProfile(string username);
   public  object GetPropertyValue(string propertyName);
   public  void SetPropertyValue(string propertyName,
              object propertyValue);
   public  HttpProfileGroupBase GetProfileGroup(String groupName);
   public  void Initialize(String username,Boolean isAuthenticated);
   public  virtual void Save();
   public  void Initialize(SettingsContext context,
             SettingsPropertyCollection properties,
             SettingsProviderCollection providers);
   public string UserName{get; set;};
   public int NumVisits{get; set;};
   public bool Gender(get; set; );
   public DateTime Birthdate{get; set; };

To access the profile properties, simply use the Profile property within the page. The Profile property is an instance of the ProfileCommon class synthesized by ASP.NET. Just access the members of the Profile, like so:

protected void Page_Load(object sender, EventArgs e)
    if (Profile.Name != null)
        Response.Write("Hello " + Profile.Name);
        Response.Write("Your birthday is " +
Saving Profile Changes

The preceding code snippet assumes there's already personalization information associated with the user. To insert profile data for a particular user, simply set the properties of the Profile object. For example, imagine a page that includes a handler for saving the profile. It might look something like this:

protected void ProfileSaveClicked(object sender, EventArgs e)
    Profile.Name = this.TextBoxName.Text;
    Profile.Birthdate = this.Calendar1.SelectedDate;

The easiest way to ensure that the personalization properties persist is to set the automaticSaveEnabled to true. Personal profile data will be saved automatically by the provider. Alternatively, you may call Profile.Save as necessary to save the personalization properties. In addition to saving and loading profiles, you may also delete the profile for a specific user by calling Profile.DeleteProfile.

Profiles and Users

Profile information is associated with the current user based upon the identity of the user. By default, ASP.NET uses the User.Identity.Name within the current HttpContext as the key to store data. By default, profiles are available only for authenticated users.

ASP.NET supports anonymous profiles as well. Turn this on within Web.Config. The default tracking mechanism for anonymous profiles is to use cookies. However, as with tracking session state, you may tell ASP.NET to use a mangled URL.

The following exercise illustrates using personalization profiles based on the user's login ID.

Using Profiles
  1. Create a new project. Name the project MakeItPersonal.

  2. Add a Web.Config file to the project. Update Web.Config to include some profile properties. The example here includes a user name, a Theme, and a birthdate. Be sure to turn anonymousIdentification to true. The following example shows that you may group and nest profile structures using the <group> element.

          <properties >
            <add name="Theme" type="System.String"/>
            <add name="Name" type="String"/>
            <add name="Birthdate"" type="System.DateTime"/>
            <group name="Address">
                <add name="StreetAddress"/>
                <add name="City"/>
                <add name="State"/>
                <add name="ZipCode"/>
    Supporting Anonymous Personalization This example uses the authenticated user name as the key for locating personalization information. However, ASP.NET supports “anonymous” personalization. That is, ASP.NET supports personalization information for anonymous users—but tracks the users via a cookie. You may add support for anonymous personalization tracking by turning the anonymousIdentification element to “true” and specifying cookie parameters like this:
        <anonymousIdentification enabled="true" 
        cookieless="UseDeviceProfile" />

    By configuring the site this way, ASP.NET will store the personalization settings based on a cookie it generates when a user first hits the site.

  3. Borrow the Default and SeeingRed Themes from the MasterPagesSite project (Chapter 8). This will let the user pick the Theme.

  4. Borrow the UseThemes.aspx and .cs files from the MasterPagesSite project.

  5. Borrow the Banner.ascx file from the MasterPagesSite.

  6. Now update the Default.aspx page. This will be where users type profile information.

    Add text boxes for the name, address, city, state, and zip code.

    Add a drop-down list box populated with Default and SeeingRed items. This will be used for selecting the Theme.

    Also add a calendar control to pick the birthdate.

  7. Add a button the user may click to submit profile information. Add a handler to input these values into the profile. Double-click on the button to add the handler.

    The input screen should look something like this:

    Adding Users to Authenticate This example uses the authenticated user name as the key for storing personalization values. Use the ASP.NET Configuration Utility to apply Forms Authentication to this application (as described in chapter 10). Also add at least one user so that you have one to personalize. Add a Login.ASPX screen to the site and modify the site's access rules to enforce authentication. Then you will be able to see the personalization information being stored and retrieved.
  8. Update Page_Load to display profile information (if it's there). Grab the profile object and set each of the text boxes and the calendar control.

    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    public partial class _Default : System.Web.UI.Page
       protected void Page_Load(object sender, EventArgs e)
          if (!this.IsPostBack)
             ProfileCommon pc = this.Profile.GetProfile(Profile.UserName);
             if (pc != null)
                 this.TextBoxName.Text = pc.Name;
                 this.TextBoxAddress.Text = pc.Address.StreetAddress;
                 this.TextBoxCity.Text = pc.Address.City;
                 this.TextBoxState.Text = pc.Address.State;
                 this.TextBoxZipCode.Text = pc.Address.ZipCode;
                 this.DropDownList1.SelectedValue = pc.Theme;
                 this.Calendar1.SelectedDate = pc.Birthdate;
    //  …
  9. Update the profile submission handler to store the profile information.

    protected void ButtonSubmitProfile_Click(object sender, EventArgs e)
    ProfileCommon pc = this.Profile.GetProfile(Profile.UserName);
       if (pc != null)
          pc.Name = this.TextBoxName.Text;
          pc.Address.StreetAddress = this.TextBoxAddress.Text;
          pc.Address.City = this.TextBoxCity.Text;
          pc.Address.State = this.TextBoxState.Text;
          pc.Address.ZipCode = this.TextBoxZipCode.Text;
          pc.Theme = this.DropDownList1.SelectedValue;
          pc.Birthdate = this.Calendar1.SelectedDate;
  10. Finally, update the UseThemes.aspx page to use the Theme. Override the page's OnPreInit method. Have the code apply the Theme as specified by the profile.

    protected override void OnPreInit(EventArgs e)
       ProfileCommon pc = this.Profile.GetProfile(Profile.UserName);
          if (pc != null)
             String strTheme = pc.Theme.ToString();
             if (strTheme != null &&
                 strTheme.Length > 0)
                 this.Theme = strTheme;
  11. When you surf to the page, you should be able to enter the profile information and submit it. Following your initial visit, the profile will be available whenever you hit the site.

Previous Page
Next Page