Saturday 31 August 2013

Create registration form and send confirmation email to new registered users in asp.net | Activate or approve user account by activation link in email address.

Create registration form and send confirmation email to new registered users in asp.net | Activate or approve user account by activation link in email address. 

 

Introduction: In this article I am going to explain with example How to create registration form and approve newly registered user by sending them account activation link on their email address in asp.net with both C#.Net and VB.Net languages.

Activate user account using activate link in email address using asp.net

Description: The concept is simple as mentioned below.
  • First user will fill the form having Name, Email Id, Address and Contact Number field. This information will be stored in the Sql server database table where a field “Is_Approved” is set to 0 i.e. false by default.
  • Also email id, and the user id based on email id is set in the query string parameters and sent to the email address of the newly registered user as an activation link.
  • When user check his email and click on the activation link then he will be redirected to the "ActivateAccount.aspx" page where User id and email Id from the query string will be verified and the “Is_Approved” field in the sql server table is set to 1 i.e. True.
  • Now he is an approved user and authorized to log in.

 

Implementation: let’s create an asp.net web application to understand the concept.
Click on the image  to enlarge
First of all create a database e.g. “MyDataBase” in Sql server and create a table with the column and the data type as shown and name it “Tb_Registration”
Note: I have set the data type of the Is_Approved field to bit and set its default value to 0 i.e. false. It means whenever a new record is inserted in the table the “Is_Approved” will be 0. So the new users need to get their account approved by clicking on the activation link in their email address.
  • In the web.config file create the connection string to connect your asp.net application to the Sql server database as:
<connectionStrings>
    <add name="conStr" connectionString="Data Source=lalit;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>
Note: Replace the Data Source and Initial Catalog(i.e. DataBase Name) as per your application.
Source Code:
  • Add a page and name it “Registration.aspx” and design the page as:
<div>
    <fieldset style="width:350px;">
    <legend>Registeration page</legend>   
    <table>
    <tr>
    <td>Name *: </td><td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br /><asp:RequiredFieldValidator
            ID="rfvName" runat="server" ErrorMessage="Please enter Name"
            ControlToValidate="txtName" Display="Dynamic" ForeColor="#FF3300"
            SetFocusOnError="True"></asp:RequiredFieldValidator></td>
    </tr>
    <tr>
    <td>Email Id: * </td><td>
        <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox><br />
        <asp:RequiredFieldValidator ID="rfvEmailId" runat="server"
            ControlToValidate="txtEmailId" Display="Dynamic"
            ErrorMessage="Please enter Email Id" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="rgeEmailId" runat="server"
            ControlToValidate="txtEmailId" Display="Dynamic"
            ErrorMessage="Please enter valid email id format" ForeColor="Red"
            SetFocusOnError="True"
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
        </td>
    </tr>
    <tr>
    <td>Address : </td><td>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Contact No.</td><td>
        <asp:TextBox ID="txtContactNo" runat="server"></asp:TextBox></td>
    </tr>
        <tr>
    <td>&nbsp;</td><td>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
                onclick="btnSubmit_Click" /></td>
    </tr>
    </table>
    </fieldset>
    </div>
Note: I have also implemented the validation on Name and the Email Id field to ensure they are not left blank using RequiredFieldValidator validation control and also used RegularExpressionValidator to check for the valid email address on the Email Id field.
C#.Net Code for Registration.aspx
  • In the code behind file (Registration.aspx.cs) write the code as:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        MailMessage msg;     
        SqlCommand cmd = new SqlCommand();
        string ActivationUrl = string.Empty;
        string emailId = string.Empty;
        try
        {
            cmd = new SqlCommand("insert into Tb_Registration (Name,EmailId,Address,ContactNo) values (@Name,@EmailId,@Address,@ContactNo) ", con);
            cmd.Parameters.AddWithValue("Name", txtName.Text.Trim());
            cmd.Parameters.AddWithValue("EmailId", txtEmailId.Text.Trim());
            cmd.Parameters.AddWithValue("Address", txtAddress.Text.Trim());
            cmd.Parameters.AddWithValue("ContactNo", txtContactNo.Text.Trim());
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd.ExecuteNonQuery();
        //Sending activation link in the email
            msg = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            emailId = txtEmailId.Text.Trim();
            //sender email address
            msg.From = new MailAddress("YourGmailEmailId@gmail.com");          
            //Receiver email address
            msg.To.Add(emailId);
            msg.Subject = "Confirmation email for account activation";
            //For testing replace the local host path with your lost host path and while making online replace with your website domain name
            ActivationUrl = Server.HtmlEncode("http://localhost:8665/MySampleApplication/ActivateAccount.aspx?UserID=" + FetchUserId(emailId) + "&EmailId=" + emailId);
            msg.Body = "Hi " + txtName.Text.Trim() + "!\n" +
                  "Thanks for showing interest and registring in <a href='http://www.webcodeexpert.com'> webcodeexpert.com<a> " +
                  " Please <a href='" + ActivationUrl + "'>click here to activate</a>  your account and enjoy our services. \nThanks!";
            msg.IsBodyHtml = true;
            smtp.Credentials = new NetworkCredential("YourGmailEmailId@gmail.com", "YourGmailPassword");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            smtp.Send(msg);
            clear_controls();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Confirmation Link to activate your account has been sent to your email address');", true);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
            return;
        }
        finally
        {
            ActivationUrl = string.Empty;
            emailId = string.Empty;
            con.Close();
            cmd.Dispose();
        }
    }  
    private string FetchUserId(string emailId)
    {
        SqlCommand cmd = new SqlCommand();
        cmd = new SqlCommand("SELECT UserId FROM Tb_Registration WHERE EmailId=@EmailId", con);
            cmd.Parameters.AddWithValue("@EmailId", emailId);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            string UserID = Convert.ToString(cmd.ExecuteScalar());
            con.Close();
            cmd.Dispose();
            return UserID;
        }
    private void clear_controls()
    {
        txtName.Text = string.Empty;
        txtEmailId.Text = string.Empty;
        txtAddress.Text = string.Empty;
        txtContactNo.Text = string.Empty;
        txtName.Focus();
    }
  • Add a new page and name it “ActivateAccount.aspx”. This page will be opened when new registered user click on the activate account link in his email. On the page load it will check email id and user id from the query string and then update the "Is_Approved" column to 1 i.e. True. Then you can redirect him to your login page to log in.
Code for ActivateAccount.aspx page
  • In the code behind file (ActivateAccount.aspx.cs) write the code as:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ActivateMyAccount();
        }
    }
    private void ActivateMyAccount()
    {
        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        try
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
            if ((!string.IsNullOrEmpty(Request.QueryString["UserID"])) & (!string.IsNullOrEmpty(Request.QueryString["EmailId"])))
            {   //approve account by setting Is_Approved to 1 i.e. True in the sql server table
                cmd = new SqlCommand("UPDATE Tb_Registration SET Is_Approved=1 WHERE UserID=@UserID AND EmailId=@EmailId", con);
                cmd.Parameters.AddWithValue("@UserID", Request.QueryString["UserID"]);
                cmd.Parameters.AddWithValue("@EmailId", Request.QueryString["EmailId"]);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                cmd.ExecuteNonQuery();
                Response.Write("You account has been activated. You can <a href='Login.aspx'>Login</a> now! ");
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
            return;
        }
        finally
        {
            con.Close();
            cmd.Dispose();
        }
    }

No comments:

Post a Comment