After completing this tutorial, you will be able to
Use ASP.NET personalization
Apply personalization to a Web site
This tutorial covers ASP.NET's built-in personalization features. A major Theme throughout ASP.NET 2.0 is to provide frameworks and support for implementing features most Web sites need. For example, we saw the support ASP.NET 2.0 provides for making a common look and feel throughout a site in Tutorial 8. We saw the new login controls in Tutorial 10. The new login controls are there so you don't have to hash out yet one more login control.
Personalizing Web sites is another feature that often makes for a great Web site. Up until ASP.NET 2.0, it was up to you to provide any personalization support for your site. Now these features are rolled into ASP.NET 2.0.
Let's take a look at Web personalization.
When the Internet and the Web first began coming into prominence, most of the sites you could surf to contained only static content. That is, they offered only text, graphics, and perhaps links to other pages. The early Web surfing community consisted of a host of anonymous voyeurs peering into the contents of those early Web servers.
Until the Web began exploding with interactive sites, there was really no need for the Web site to care who was looking at it. However, any businessperson worth his or her salt will tell you that tailoring and targeting content toward specific individuals is good for business.
The next time you go online to shop or visit a subscription-type site, take note of how much the site knows about you. Very often (if you've provided login information) the site will greet you with your name. It may point you to information or products that might interest you. This demonstrates the notion of personalizing a Web site.
In the past, any personalization of your site resulted from code you wrote, such as code to manage user preferences in cookies or code to store personal information in back-end databases. In addition to simply storing and managing the personal information, you had to integrate the personal information management with whatever authentication and authorization scheme you decided to use.
ASP.NET 2.0 now includes services for personalizing a Web site to suit a particular client's taste. There's no reason you couldn't write your own database and services to provide this functionality. However, as with all these services provided by ASP.NET, they bring with them some consistency and prevent your having to write all the code yourself.
ASP.NET 2.0 provides specific support for personalizing Web sites. The support ASP.NET provides for personalization service greatly simplifies the whole management and storage of personal information. Defining a Web site's personalization facilities begins with defining User Profiles.
User Profiles
The heart of the new ASP.NET personalization service is the User Profile. A User Profile defines what kind of personal information your Web site needs. For example, you may want to know personal data about users of your Web site, such as name, gender, number of visits to the site, and so forth. User Profiles are also handy for storing user preferences for your site. For example, you might include a Theme as part of a personal profile so that users can tailor the pages to their particular tastes.
Once the personalization properties are defined in Web.Config, a component within .NET has to be able to read it and use it. That job is handled by ASP.NET personalization providers.
Personalization Providers
In Tutorial 11 on databinding, we saw that .NET includes a new provider pattern. Providers hide the coding differences involved in creating the necessary objects for connecting to various databases. Just pick a provider (for example, SQL Server or Access), and the provider does the dirty work of manufacturing connections and such. ASP.NET includes two personalization providers out of the box: a profile provider for custom user data and a personalization provider for Web Parts as we saw in Tutorial 7.
ASP.NET defines the fundamental provider capabilities in an abstract class named PersonalizationProvider. Those capabilities include such things as loading and saving personalization properties and managing their relationship to any Web Parts used within a site. ASP.NET provides a default implementation of these capabilities in a concrete class named SqlPersonalizationProvider, which is derived from PersonalizationProvider.
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:
User name
Gender
Visit count
Birthday
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:
<system.web>
<profile automaticSaveEnabled="true" >
<properties>
<add name="NumVisits" type="System.Int32"/>
<add name="UserName" type="System.String"/>
<add name="Gender" type="bool">
<add name="Birthday" type="System.DateTime">
</properties>
</profile>
</system.webThe 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 " +
Profile.Birthdate);
}
}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
Create a new project. Name the project MakeItPersonal.
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.
<system.web> <profile> <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"/> </group> </properties> </profile> </system.web>NOTE
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" cookieName=".ASPXANONYMOUSUSER" cookieTimeout="120000" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="Encryption" 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.
Borrow the Default and SeeingRed Themes from the MasterPagesSite project (Tutorial 8). This will let the user pick the Theme.
Borrow the UseThemes.aspx and .cs files from the MasterPagesSite project.
Borrow the Banner.ascx file from the MasterPagesSite.
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.
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:
NOTE
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 tutorial 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.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; } } } // ¡ }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; pc.Save(); } }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; } } base.OnPreInit(e) }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.
Profiles represent an effective way to add personalization to your site. The profile scheme in the Web.Config defines the profiles available to the application. ASP.NET will synthesize a ProfileCommon class that includes support for the properties defined in Web.Config. To access the properties, grab the Profile object from the Page for the current HttpContext. ASP.NET will take care of the details of serializing the property data and tracking it either anonymously or by using the identity of the logged in user.
To | Do This |
Define personalization profile settings | Use the <profile> element in Web.Config. Define name/type pairs to create the profiles schema |
Access the profile properties | Profile properties are available through the page and through the current HttpContext |
Track the profiles with cookies | Enable anonymousIdentification in Web.Config |
discuss this topic to forum
