Explanation:
Ist thing which is must to do is telling the Web Application that what extra information we need to keep in our Database. These informations come in the Web.config
For example we want to add information about "Age" and "Gender" of our users. We will Add these lines of code to our Web.config.
<profile enabled="true">
<properties>
<add name="Age" allowAnonymous="true" type="System.Int16"/>
<add name="Gender" allowAnonymous="true"/>
properties>
profile>
Now we will see how to retrive and add information in our Page ( .aspx )
Accessing Logged-In User Profile:
<%@ Page Language="C#" %> <script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gTextBox.Text = Profile.Gender;
ageTextBox.Text = Profile.Age.ToString();
}
}
protected void updateProfileButton_Click(object sender, EventArgs e)
{
Profile.Gender = gTextBox.Text;
Profile.Age = Int16.Parse(ageTextBox.Text);
Profile.Save(); //this line is must to save the Data }
script>
<asp:Content ID="Content1" ContentPlaceHolderID="main" runat="Server"> <asp:TextBox runat="server" ID="gTextBox" />
<asp:TextBox runat="server" ID="ageTextBox" />
<asp:Button runat="server" ID="updateProfileButton" Text="Save Preferences"
OnClick="updateProfileButton_Click" />
asp:Content >
Accessing User Profile Which is not Logged-in:
<%@ Page Language="C#" %> <script runat="server">
ProfileCommon Prof = Profile.GetProfile(UserName);
//UserName Can be accessed through QureyString, SessionState or other any suitble method
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ gTextBox.Text = Prof.Gender;
ageTextBox.Text = Prof.Age.ToString();
}
}
protected void updateProfileButton_Click(object sender, EventArgs e)
{
Prof.Gender = gTextBox.Text;
Prof.Age = Int16.Parse(ageTextBox.Text);
Prof.Save(); // this is must to save the Data }
script>
<asp:Content ID="Content1" ContentPlaceHolderID="main" runat="Server"> <asp:TextBox runat="server" ID="gTextBox" />
<asp:TextBox runat="server" ID="ageTextBox" />
<asp:Button runat="server" ID="updateProfileButton" Text="Save Preferences"
OnClick="updateProfileButton_Click" />
asp:Content >
How to Create an Ananymous User Profile:
protected void btnSave_Click(object sender, EventArgs e) {
ProfileCommon userProfile =
(ProfileCommon) ProfileCommon.Create(txtUserName1.Text, false);
userProfile.Street = txtStreet.Text;
userProfile.Save();
}
But one thing have to be keep in mind that this Ananymous Profile must be unique and different then what your Users "UserName" else you will distroy some one profile or new users can delete your Data.
You noticed that default Property of a Profile Field is "string" otherwise one have to define one explicitly. In Our case we Defined "Age" as an "Integer"
To create Proile in the Registration Page see Create a User Profile in Regisration Page.
|