Tuesday, 26 March 2013

How to create a Signup page in ASP.NET

How to create a Signup page in ASP.NET
Download Source Code : 1388_SignupPage.zip

Signup or register is used to create a user account in websites. You can use CreateUserWizard or you can define your own layout and logic to create a signup or register page.


I will not use CreateUserWizard in this article to create a signup or register page for new user registration. I will use TextBox and different validation controls to create a simple signup or register page. I will use RequiredFieldValidator for all entries and RegularExpressionValidator and CompareValidator for email and confirm password respectively.   I will also insert values in database and check duplicate entries in database table on the basis of email. You can check user name or all values to prevent double entry. I have created a SQL Server database (SampleApplicationDatabase) and a table (Account) for this article. Table (Account) has six columns (AccountID, FirstName, LastName, Email, Password, ConfirmPassword and CreateDate). AccountID is primary key and set to auto increment. I have also written two stored procedures in database and two functions to check double entry and insert values in database.
 
 
Let’s see what we have to do to create a signup or register page. You can download source code. 
 
  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual C# or Visual Basic > ASP.NET Empty Web Site > Click Ok
  4. Website > Add New Item > Web Form > Click Add
  5. Add code below in your Web Form

    <table>
            <tr>
                <td colspan="3">
                    <span style="font-size: 14pt">Please provide following information and Signup</span>
                </td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:Label ID="lblFirstName" runat="server" Text="First Name:" Width="80px"></asp:Label>
                </td>
                <td style="width: 116px">
                    <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                </td>
                <td style="width: 100px">
                    <asp:RequiredFieldValidator ID="FirstNameRequiredFieldValidator" runat="server" ControlToValidate="txtFirstName"
                        Display="Dynamic" ErrorMessage="First Name Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:Label ID="lblLastName" runat="server" Text="Last Name:" Width="80px"></asp:Label>
                </td>
                <td style="width: 116px">
                    <asp:TextBox ID="txtLastName" runat="server" ></asp:TextBox>
                </td>
                <td style="width: 100px">
                    <asp:RequiredFieldValidator ID="LastNameRequiredFieldValidator" runat="server" ControlToValidate="txtLastName"
                        Display="Dynamic" ErrorMessage="Last Name Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:Label ID="lblEmail" runat="server" Text="Email:" Width="45px"></asp:Label>
                </td>
                <td style="width: 116px">
                    <asp:TextBox ID="txtEmail" runat="server" ></asp:TextBox>
                </td>
                <td style="width: 100px">
                    <asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ControlToValidate="txtEmail"
                        Display="Dynamic" ErrorMessage="Email Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server"
                        ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="Provide valid email address"
                        SetFocusOnError="True" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td style="width: 100px; height: 26px;">
                    <asp:Label ID="lblPassword" runat="server" Text="Password:" Width="71px"></asp:Label>
                </td>
                <td style="width: 116px; height: 26px;">
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
                </td>
                <td style="width: 100px; height: 26px">
                    <asp:RequiredFieldValidator ID="PasswordRequiredFieldValidator" runat="server" ControlToValidate="txtPassword"
                        Display="Dynamic" ErrorMessage="Password Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td style="width: 100px; height: 26px;">
                    <asp:Label ID="lblConfirmPassword" runat="server" Text="Confirm Password:" Width="128px"></asp:Label>
                </td>
                <td style="width: 116px; height: 26px;">
                    <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
                </td>
                <td style="width: 100px; height: 26px">
                    <asp:RequiredFieldValidator ID="ConfirmPasswordRequiredFieldValidator" runat="server"
                        ControlToValidate="txtConfirmPassword" Display="Dynamic" ErrorMessage="Confirm Password Required"
                        SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="ConfirmPasswordCompareValidator" runat="server" ControlToCompare="txtPassword"
                        ControlToValidate="txtConfirmPassword" Display="Dynamic" ErrorMessage="Password missmatch"
                        SetFocusOnError="True">*</asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td style="width: 100px; height: 26px;">
                </td>
                <td style="width: 116px; height: 26px;">
                    <asp:Button ID="btnSignup" runat="server" Text="Signup"
                        onclick="btnSignup_Click" onprerender="btnSignup_PreRender" />
                </td>
                <td style="width: 100px; height: 26px">
                </td>
            </tr>
            <tr>
                <td colspan="3" style="height: 26px">
                    <asp:ValidationSummary ID="SigupValidationSummary" runat="server" />
                    <asp:Label ID="lblMessage" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
     
     
    Add TextBox controls for first name, last name, email, password and confirm password values. You can add more TextBox controls if you want more information from user. Add RequiredFieldValidor for all values or for those values which you need to add in database. Add a RegularExpressionValidator for email and a CompareValidator for confirm password or re-password input field. Set ControlTovalidate property for all TextBox controls accordingly. You can also add ValidationSummary control to show all validation controls. 
     
  6. Write below stored procedures to insert values into Account table and to check valid entry of email.

    Stored procedure to insert values into table
     
    CREATE PROCEDURE dbo.AddAccount
           (
           @FirstName nvarchar(50),
           @LastName nvarchar(50),
           @Email varchar(100),
           @Password nvarchar(50),
           @CreateDate datetime
           )
    AS
           INSERT Account
                  (
                  FirstName,
                  LastName,
                  Email,
                  Password,
                  CreateDate
                  )
           VALUES
                  (
                  @FirstName,
                  @LastName,
                  @Email,
                  @Password,
                  @CreateDate
                  )            
     
           RETURN
     
    Stored Procedure to check valid or duplicate entry of email
     
    CREATE PROCEDURE dbo.IsValidUser
           (
           @Email varchar(100),
           @IsValid bit OUTPUT
           )
    AS    
    BEGIN
     
      DECLARE @RecordCount INT
     
      SELECT @RecordCount = Count(*) FROM Account WHERE Email = @Email
     
      IF @RecordCount <= 0
      BEGIN
        SET @IsValid = 1
      END
      ELSE
      BEGIN
       SET @IsValid = 0
      END
     
    END
     
    AddAccount stored procedure will insert values into Account table. IsValidUser stored procedure count number of accounts for entered email. If there is any account created for this email, the count will be 1. This stored procedure will check if count is equal to zero then it will return true otherwise it will return false.
     
  7. Open code behind file and include following namespace.

    C#
     
    using System.Data;
    using System.Data.SqlClient;
     
    VB.NET
     
    Imports System.Data
    Imports System.Data.SqlClient
     
  8. Write two functions in code behind file to insert values into database and to check valid or duplicate email.

    C#
     
    public bool IsValidUser(string email)
    {
        bool result;
     
        string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connstring);
     
        SqlCommand cmd = new SqlCommand("IsValidUser", conn);
        cmd.CommandType = CommandType.StoredProcedure;
     
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;
        cmd.Parameters.Add("@IsValid", SqlDbType.Bit).Value = DBNull.Value;
        cmd.Parameters["@IsValid"].Direction = ParameterDirection.Output;
     
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            result = (bool)cmd.Parameters["@IsValid"].Value;
        }
        catch (Exception ex)
        {
            return false;
        }
        finally
        {
            conn.Close();
        }
        return result;
    }
     
    public bool AddAccount(string firstName, string lastName, string email, string password, DateTime createDate)
    {
        bool result;
     
        string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connstring);
     
        SqlCommand cmd = new SqlCommand("AddAccount", conn);
        cmd.CommandType = CommandType.StoredProcedure;
     
        cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = firstName;
        cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = lastName;
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;
        cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50).Value = password;
        cmd.Parameters.Add("@CreateDate", SqlDbType.DateTime).Value = createDate;
     
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            result = true;
        }
        catch (Exception ex)
        {
            result = false;
        }
        finally
        {
            conn.Close();
        }
     
        return result;
    }
     
     
    VB.NET
     
    Public Function IsValidUser(ByVal email As String) As Boolean
        Dim result As Boolean
     
        Dim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"
        Dim conn As New SqlConnection(connstring)
     
        Dim cmd As New SqlCommand("IsValidUser", conn)
        cmd.CommandType = CommandType.StoredProcedure
     
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email
        cmd.Parameters.Add("@IsValid", SqlDbType.Bit).Value = DBNull.Value
        cmd.Parameters("@IsValid").Direction = ParameterDirection.Output
     
        Try
            conn.Open()
            cmd.ExecuteNonQuery()
            result = CBool(cmd.Parameters("@IsValid").Value)
        Catch ex As Exception
            Return False
        Finally
            conn.Close()
        End Try
     
        Return result
    End Function
     
     
    Public Function AddAccount(ByVal firstName As String, ByVal lastName As String, ByVal email As String, ByVal password As String, ByVal createDate As DateTime) As Boolean
        Dim result As Boolean
     
        Dim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"
        Dim conn As New SqlConnection(connstring)
     
        Dim cmd As New SqlCommand("AddAccount", conn)
        cmd.CommandType = CommandType.StoredProcedure
     
        cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = firstName
        cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = lastName
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email
        cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50).Value = password
        cmd.Parameters.Add("@CreateDate", SqlDbType.DateTime).Value = createDate
     
        Try
            conn.Open()
            cmd.ExecuteNonQuery()
            result = True
        Catch ex As Exception
            result = False
        Finally
            conn.Close()
        End Try
     
        Return result
    End Function
     
    In IsValidUser() function, set connection to your server and call the IsValidUser stored procedure. Add parameters and their values and set the direction for output parameter. Call ExecuteNonQuery() method and get the true/false value in Boolean variable.
     
    AddAccount() function is simple. Set connection to your server and call the AddAccount stored procedure. Add parameters and their values to SqlCommand object. call ExecuteNonQuery() method and set value to true in try block and false in catch block.
     
  9. Write code below in button click event

    C#
     
    protected void btnSignup_Click(object sender, EventArgs e)
    {
        if (IsValidUser(txtEmail.Text) == true)
        {
            bool result = AddAccount(txtFirstName.Text, txtLastName.Text, txtEmail.Text, txtPassword.Text, DateTime.Now);
     
            if (result == true)
            {
                lblMessage.Text = "Account created successfully";
            }
            else
            {
                lblMessage.Text = "Cannot create account, please try again later.";
            }
        }
        else
        {
            lblMessage.Text = "Email already exist. Please use another email address";
        }
    }
     
    VB.NET
     
    Protected Sub btnSignup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSignup.Click
        If IsValidUser(txtEmail.Text) = True Then
            Dim result As Boolean = AddAccount(txtFirstName.Text, txtLastName.Text, txtEmail.Text, txtPassword.Text, DateTime.Now)
     
            If result = True Then
                lblMessage.Text = "Account created successfully"
            Else
                lblMessage.Text = "Cannot create account, please try again later."
            End If
        Else
            lblMessage.Text = "Email already exist. Please use another email address"
        End If
    End Sub
     
    First call IsValidUser() function and get the Boolean value. If it is not true, simply display the message and if it is true then call the AddAccount() function by providing all parameter values to it. 
     
  10. Signup page is ready. Press F5, enter values and click signup button.

No comments:

Post a Comment