Wednesday 2 January 2008

ASP.NET 2.0 + Profiles

I had some questions today about the Profile Provider and why it was not working in a particular setup. It was a problem with their settings in the web.config. Here is one of the clearer explanations of how to set up the config.

This MSDN article is also handy:

All you have to do is add settings like below to the web.config:

<?xml version="1.0"?>
<configuration xmlns="">
<add name="BirthDate" type="DateTime"/>
<add name="FavoriteNumber" type="int"/>
<add name="Comment" type="string"/>
<add name="FavoriteColor" type="string" defaultValue="Blue"/>
<add name="FavoriteAlbums"

Then use HttpContext.Current.Profile like this (no additional classes required):

// BirthDate is DateTime
textDob.Text = Profile.BirthDate.ToShortDateString();

// FavoriteNumber is Int32
textFavNumber.Text = Profile.FavoriteNumber.ToString();

// Comment is String
textComment.Text = Profile.Comment;

// FavoriteColor is String
dropDownFavColor.SelectedValue = Profile.FavoriteColor;

// FavoriteAlbums is StringCollection
foreach (string album in Profile.FavoriteAlbums)
listBoxFavAlbums.Items.FindByText(album).Selected = true;

The real question is: where does the strongly typed Profile come from? The ASP.NET compiler parses web.config to uncover the profile schema defined inside, and then code-generates a class in the Temporary ASP.NET Files directory. This is the class that is created when you add these elements to the web.config:

public class ProfileCommon : System.Web.Profile.ProfileBase {

public virtual short Age
return ((short)(this.GetPropertyValue("Age")));
this.SetPropertyValue("Age", value);

// other properties ...

See for a sample of this code and a more detailed walkthrough of how the httpmodules and proxy classes created by .NET are created and used.

1 comment:

Anonymous said...

Thanks for the nice info