Com And Hosting

In ASP.NET you can use default membership provider and use the aspnet_Profile table to store additional information of a user at the time of registration. If you don’t know how to install Membership Schema then read my previous article Installing Membership Schema in ASP.NET.

You can mess around to store additional information in the user table but it is not recommended as you might end up with broken schema or unexpected issues as  the default membership schema has dependencies with lot of stored procedures and views. One of the most amazing features I like about ASP.NET is the default membership provider. It gives you a full functional user management package out of the box without writing any code. This is simply amazing! User can signup, login, change password, reset password etc. In my other websites I have used separate table to store user’s personal information by linking the userid key as a foreign key from aspnet_user table.

Now this involves a bit of coding and logical process, because you want to check first whether user is created then get the inserted userid and insert into another table along with other information. So you have to hold the additional information either in session or cookies and wait until the user is created then you can execute the script to enter additional information. The other problem with using additional table is, every time you want to access this information from  any page you will require datasource and reader to retrieve the data from the table which I found a bit annoying but you can create a custom class to use globally. Anyway at the end of the day it is your choice which way you prefer.

Some developers like to do easy task in complicated way and others seek for easier way.

But it can be done much simpler way now using aspnet_profile table, you can store additional information into the profile table without writing lot of codes.

Let’s start this example, say I want to store some personal information e.g. First Name, Last Name, Address and contact of a user during the registration. First of all to store the information in user profile table, we have to enable the user profile feature and add the parameters in web.config file. Add the following code in the web.config file –

<profile enabled="true" >
      <properties>
        <add name="FirstName" type="string" />
        <add name="LastName" type="string" />
        <add name="Address" type="string" />
        <add name="Contact" type="string" />
      </properties>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LocalSqlServer" applicationName="/"/>
      </providers>
    </profile>

Once you enabled the user profile, you can access the parameters from any page with couple of lines of code. Now I am going to use the CreateUserWizard template to signup in the website and ask for additional information before the user enters the username and password. Here is an example of CreateUserWizard placed in aspx page.

  <asp:ValidationSummary ID="RegisterUserValidationSummary" runat="server" CssClass="alert alert-error"
        Width="400" ValidationGroup="CreateUserWizard1" />
    <asp:CreateUserWizard ID="CreateUserWizard1" runat="server" CreateUserButtonText="Register"
        OnCreatedUser="CreateUserWizard1_CreatedUser">
        <ValidatorTextStyle CssClass="failureNotification" />
        <WizardSteps>
            <asp:WizardStep runat="server" Title="Profile Info">
                <asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="alert alert-error"
                    Width="400" />
                <table class="form-horizontal" cellpadding="3" cellspacing="3">
                    <tr>
                        <td>
                            First Name:
                        </td>
                        <td>
                            <asp:TextBox runat="server" ID="txtFirstName" />
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter your first name."
                                ControlToValidate="txtFirstName" SetFocusOnError="true">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            Last Name:
                        </td>
                        <td>
                            <asp:TextBox runat="server" ID="txtLastName" />
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter your first name."
                                ControlToValidate="txtLastName" SetFocusOnError="true">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            Address:
                        </td>
                        <td>
                            <asp:TextBox runat="server" ID="txtAddress" />
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            Contact:
                        </td>
                        <td>
                            <asp:TextBox runat="server" ID="txtContact" />
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please enter your first name."
                                ControlToValidate="txtContact" SetFocusOnError="true">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                </table>
            </asp:WizardStep>
            <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server" Title="">
            </asp:CreateUserWizardStep>
            <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
                <ContentTemplate>
                    <p>
                        You have been successfully registered.</p>
                </ContentTemplate>
            </asp:CompleteWizardStep>
        </WizardSteps>
        <FinishPreviousButtonStyle CssClass="btn btn-primary" />
        <NavigationButtonStyle CssClass="btn btn-primary" />
    </asp:CreateUserWizard>

In the first Wizard step I am asking to enter First Name, Last Name, Address and Contact details then goes to next screen to enter the remaining information e.g. username and password etc. You will notice I have used item validation to force user to enter information before they can navigate to next screen. When the page renders it looks like below –

User Registration
User Registration

To get the user input from the CreateUserWizard use the following code in the c# code page. If you examine the code, this event will take place once user account has been created successfully. First create and profile for the current user and update the profile information according to the information provided in the text boxes.

protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {

        ProfileCommon userProfile = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true);

       //get the user information from the wizard
        userProfile.FirstName = ((TextBox)CreateUserWizard1.FindControl("txtFirstName")).Text;
        userProfile.LastName =( (TextBox)CreateUserWizard1.FindControl("txtLastName")).Text;
        userProfile.Address= ((TextBox)CreateUserWizard1.FindControl("txtAddress")).Text;
        userProfile.Contact = ((TextBox)CreateUserWizard1.FindControl("txtContact")).Text;

        //save data into profile
        userProfile.Save();

    }

If you are using VB then use the following code –

 

Protected Sub CreateUserWizard1_CreatedUser(sender As Object, e As EventArgs)

	Dim userProfile As ProfileCommon = DirectCast(ProfileCommon.Create(CreateUserWizard1.UserName, True), ProfileCommon)

	'get the user information from the wizard
	userProfile.FirstName = DirectCast(CreateUserWizard1.FindControl("txtFirstName"), TextBox).Text
	userProfile.LastName = DirectCast(CreateUserWizard1.FindControl("txtLastName"), TextBox).Text
	userProfile.Address = DirectCast(CreateUserWizard1.FindControl("txtAddress"), TextBox).Text
	userProfile.Contact = DirectCast(CreateUserWizard1.FindControl("txtContact"), TextBox).Text

	'save data into profile
	userProfile.Save()

End Sub

Now let’s test the page and create a new user with the profile information. To check the profile information, I have opened the MS SQL Express database using MS SQL Server management tool and view the table data of aspnet_profile table. I can see the profile information has been saved successfully –

ASPNET_PROFILE Table
ASPNET_PROFILE Table

Now if you want to access any particular user profile information, you can easily do so by using following code from any page. To access to user profile and membership schema first make sure you add the class reference in the code page –

using System.Data;
using System.Data.SqlClient;
using System.Security;
using System.Configuration;
using System.Web.Security;
using System.IO;

These are some of the common library used in asp.net websites.

In this example, the website offers a free assessment but user need to be registered and login to take the assessment. In the assessment page, I probably want to display logged in user information e.g. first name, last name etc. which looks nice and I  also want to include the user’s personal information in the assessment result page. Instead of asking to provide the information again, I can quickly access the user profile information and use them. This might reduce the user frustration and save time too. Use the following code to access the profile information –

In c#

string fname = "";
       string lname = "";
       string email ="";
       string address = "";
       string username = Membership.GetUser().UserName;
       string contact = "";

       if (User.Identity.IsAuthenticated)
       {
           ProfileCommon p = Profile.GetProfile(username);
           fname = p.FirstName;
           lname = p.LastName;
           email = Membership.GetUser().Email;
           address = p.Address;
           contact = p.Contact;

       }

In VB –

Dim fname As String = ""
Dim lname As String = ""
Dim email As String = ""
Dim address As String = ""
Dim username As String = Membership.GetUser().UserName
Dim contact As String = ""

If User.Identity.IsAuthenticated Then
	Dim p As ProfileCommon = Profile.GetProfile(username)
	fname = p.FirstName
	lname = p.LastName
	email = Membership.GetUser().Email
	address = p.Address

	contact = p.Contact
End If

I have implemented this code in a button click event along with other codes (omitted) to store information in the database.

Now these variables can be used anywhere in the page with very minimal code and less efforts.

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *