How to access Personalization Profile properties in your custom classes in ASP.NET?
Copyright © 2007-2012 www.AspDotNetFaq.com
When you enable Personalization in your ASP.NET 2.0 website you can set up a collection of properties that will be maintained for each user of your website (even for the anonymous visitors).
Personalization Profiles are often used to store personal data of website users, their personal preferences, visual themes, language settings etc.
Here is a sample Profile setup in web.config:
<system.web>
...
<anonymousIdentification enabled="true" />
<profile>
<properties>
<add name="UserCulture" defaultValue="en-US"></add>
<add name="UserUICulture" defaultValue="en"></add>
</properties>
</profile>
...
</system.web>
So we have added two properties to be stored for each user (to keep their language preferences) and here is how we can access them in our WebForm code:
this.Culture = this.Profile.UserCulture;
As you can see its fairly easy to access Profile properties because our Page class exposes public
Profile property that is in fact a dynamically generated object of type ProfileCommon.
ProfileCommon is dynamically generated wrapper class (generated on each application run) that inherits from
ProfileBase class and exposes public Profile properties that we have specified in our web.config file.
Here is how ASP.NET enables this functionality for us in the dynamically generated partial Page class:
protected ProfileCommon Profile {
get {
return ((ProfileCommon)(this.Context.Profile));
}
}
So this solves our problem: in order to use our Personalization properties in our custom classes all we need to do is to cast the
HttpContext.Current.Profile object into
ProfileCommon type and thats it.
Here is an example of custom Page class that uses Personalization properties to set the current Culture of the page:
public class BasePage : System.Web.UI.Page
{
public BasePage()
{
//
// TODO: Add constructor logic here
//
}
protected override void InitializeCulture()
{
Culture = (HttpContext.Current.Profile as ProfileCommon).UserCulture;
}
}
Copyright © 2007-2012 www.AspDotNetFaq.com