ASP.Net Profile Provider = Freaking Cool!
I've been playing with the ASP.Net controls lately getting my head around them and last night in my little project it came time to implement profile data for the users using my website.
How many times have you gone through figuring out what you wanted to save for each user, designing a database structure for it (normalized probably) and then setting up the object model and code to do it all and implementing it in all the places you want it?
Hopefully you were smarter than me and found an easier way of doing it in the past, but it's soooo much easier with ASP.Net 2.0. Last night I spent two minutes figuring it out - and another minute implementing it.
To start with I'm using SQL Express and I'm manaing my database from within Visual Studio so if you are running a seperate SQL database you'll need to run "aspnet_regsql.exe -A p" to set up the database, otherwise Visual Studio will do the work for you.
Make sure you have a connection string in your Web.Config file and then in the <system.web> section add the following XML:
<profile defaultProvider="SqlProvider">
<providers>
<clear />
<add name="SqlProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="SqlServices"
applicationName="SampleApplication"
description="SqlProfileProvider for SampleApplication" />
</providers>
<properties>
<add name="ZipCode" />
<add name="CityAndState" />
</properties>
</profile>
This XML tells ASP.Net to use a SQL to store te profile information that you want to use. You can change the Connection String to any database (I got it to use the one I was already using for the membership and role providers). The properties at the bottom of the XML are the data fields you want to store data for your users.
Having done that - build your project.
Now all you need to do is reference the Profile Object and the properties you specified will be there to reference. ASP.Net will extend the Profile object for you adding the properties that you specified. Thus in your code you can work with the profile and the properties you added as follows:
void PopulateTextBox()
{ TextBox1.Text = Profile.ZipCode;
}
ASP.Net will also figure out who the user is that's logged in and get the profile details specific to them.
This means that what used to take ages, is now really insanely fast! Thats freaking cool!