Nearly all developers who’re developing web applications have been working with sessions, cookies, etc.
For example, when you want to authenticate your users you store you user’s authentication information in sessions and cookies. Previously, I posted about ASP.NET Form Authentication which most of ASP.NET developer are working with it because it’s one of the most stable ways for user authentications.
ASP.NET 3.5 provides a new feature named “Personalization” that has very flexible infrastructure enables you to store user’s information in server not client (Cookies store information on client computers). In this post, I’m going to show you how you can use profiles and I’m sure you’ll love it.
ASP.NET has a deep focus on web.config file. You can do lots of things in your configuration file. In order to work with profiles you need to let ASP.NET what user data you want to store. So you have to add some elements to you web.config file:
<add name="Age" type="System.Int32"/>
When you added your custom properties you can see them in code-behind so you can get or set you profile information.
Notice that “Age” property in the above code snippet, I just assigned a type attribute for it. It means that you can also specify the type of a property for example:
· string: System.String
· bool: System.Boolean
· int: System.Int32
You can also assign your custom type. For example, imaging you want to store user’s cart information. You can store information in a class and then set the type of your profile property to that class. Here is an example:
Public Class Cart
Private _ProductName As String
Private _Price As Decimal
Private _Quantity As Int16
Public Property ProductName() As String
Set(ByVal value As String)
_ProductName = value
Public Property Price() As Decimal
Set(ByVal value As Decimal)
_Price = value
Public Property Quantity() As Int16
Set(ByVal value As Int16)
_Quantity = value
Note that the class must be Serializable.
Now you can add your property with your custom type:
<add name="Cart" type="Cart" serializeAs="Binary" />
You can also provide default values for your properties. It means if you leave your property with no value, a default value will be replace with null:
<add name="Active" type="System.Boolean" defaultValue="false"/>
It possible to make your properties read-only:
<add name="Active" type="System.Boolean" readOnly="true"/>
I the next part, I’ll show you how to store profile information in a data source such as SQL Server, XML, etc.