Introduction
It is easy to customize profile by adding entries in web.config. But the custom-entries added are available only in the codebeside classes and not in any other class.
The situation worsens if the profile entries need to be made available in custom web-control that may reside in another assembly. As such, the entries must be available at the compile time of the control-assembly and not of the website.
This article descibes a way out to the problem...
Solution
Let us say that we need three entries in profile - name, age and city - of which name and city are string while age is int.
First step is to create a class, say, EdujiniProfile as given below:
using System.Web.Profile;
namespace Edujini.Tutorials.ASPNet
{
public class EdujiniProfile : ProfileBase
{
#region Fields
private string name;
private int age;
private string city;
#endregion
public EdujiniProfile()
{
}
#region Properties
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
#endregion
}
}
The next step is to customize web.config to ensure that the <profile> entry look similar to that as given below:
<profile enabled="true"
defaultProvider="MyProfileProvider"
inherits="Edujini.Tutorials.ASPNet.EdujiniProfile">
<providers>
<add name="MyProfileProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ASPNetAuthDB"/>
</providers>
<properties>
<add name="Country" type="System.String"/>
</properties>
</profile>
I have added yet another field called Country of type string.
Let us say that we need to refer to the profile in a class ProfileManipulator. Here's how it can get reference to the profile for a specific user:
namespace Edujini.Tutorials.ASPNet
{
public static class ProfileManipulator
{
public static EdujiniProfile GetProfileDetails(string username)
{
HttpContext context = HttpContext.Current;
if(context.Request.IsAuthenticated)
{
ProfileBase baseProfile = ProfileBase.Create(username);
EdujiniProfile profile = baseProfile as EdujiniProfile;
return profile;
}
return null;
}
}
}
All we need to ensure that the user is logged in. Note that the most popular method used in the codebeside in the Page derived class to get access to the profile is
ProfileCommon profile = base.Profile.GetProfile(username);
In the new system, i.e., the backend class - ProfileManipulator, we cannot type-cast to ProfileCommon since it does not exist yet!
Proceed ahead and use the new profile!