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.
http://www.theserverside.net/tt/articles/showarticle.tss?id=CreatingProfileProvider

This MSDN article is also handy: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/profile/default.aspx

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

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.web>
<profile>
<properties>
<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"
type="System.Collections.Specialized.StringCollection"
serializeAs="Xml"/>
</properties>
</profile>
</system.web>
</configuration>


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
{
get
{
return ((short)(this.GetPropertyValue("Age")));
}
set
{
this.SetPropertyValue("Age", value);
}
}

// other properties ...
}



See http://www.odetocode.com/Articles/440.aspx 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
Regards,
Jack
http://db2examples.googlepages.com/