top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to implement forgot password functionality in ASP.NET?

+1 vote
381 views
How to implement forgot password functionality in ASP.NET?
posted Feb 5, 2016 by Latha

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Table Name: Account
Column Names: AccountID, FirstName, LastName, Email, Password, ConfirmPassword and CreateDate

Add a link of Forgot Password in Login page and redirects it to retrieve password page

Add code below in aspx page

<table>
       <tr>
            <td colspan="3" style="height: 21px; text-align: left">
                <span style="font-size: 12pt">Please provide following information to retrieve password
              </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"
                 ForeColor="Red" 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"
                   ForeColor="Red" ControlToValidate="txtLastName" Display="Dynamic"
                   ErrorMessage="Last Name Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
            </td>
        tr>
        <tr>
            <td style="width: 71px" valign="top">
                     <asp:Label ID="lblEmail" runat="server" Text="Email:">asp:Label>td>
            <td style="width: 150px; text-align: left;" valign="top">
                <asp:TextBox ID="txtEmail" runat="server" Width="225px" >asp:TextBox>td>
            <td style="width: 37px" valign="top">
                    <asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server"
                     ControlToValidate="txtEmail" Display="Dynamic" ForeColor="Red"
                     ErrorMessage="Email Required" SetFocusOnError="True</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server"
                       ForeColor="Red" ControlToValidate="txtEmail" Display="Dynamic"
                       ErrorMessage="Provide Valid Email Address"
                               ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*
                    </asp:RegularExpressionValidator></td>
        </tr>
        <tr>
            <td style="width: 71px; height: 27px;"></td>
            <td style="width: 178px; text-align: right; height: 27px;">
                <asp:Button ID="btnRetrievePassword" runat="server" Style="position: relative"
                     Text="Retrieve Password" onclick="btnRetrievePassword_Click" /></td>
            <td style="width: 37px; height: 27px; text-align: right">
            </td>
        </tr>
        <tr>
            <td colspan="3" style="height: 27px; text-align: center">
                <asp:ValidationSummary ID="ValidationSummary" ForeColor="Red" runat="server" />
            </td>
        </tr>
</table>
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>

Write below stored procedure to get password from database

CREATE PROCEDURE dbo.GetPassword
       (
       @FirstName           varchar(100),
       @LastName           varchar(100),
       @Email                  varchar(100)
       )
AS    
BEGIN

  DECLARE @RecordCount INT

  SELECT Password
  FROM     Account
 WHERE  FirstName = @FirstName
 AND        LastName = @LastName
 AND       Email = @Email


END

Add following namespaces in your code behind file

C#

using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;
using System.Net;

VB.NET

Imports System.Data.SqlClient
Imports System.Data
Imports System.Net.Mail
Imports System.Net

Now write code below in code behind file

C#

protected void btnRetrievePassword_Click(object sender, EventArgs e)
{
    string password = GetPassword(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim());

    if (password != "")
    {
        try
        {
            SendEmail(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim(), password);
            lblMessage.Text = "Your password is sent to your email";
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Sorry! an error occured while sending email, please try again";
        } 
    }
    else
    {
        lblMessage.Text = "Please provide correct information";
    }
}

public string GetPassword(string firstName, string lastName, string email)
{
    string password = "";

    string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";
    SqlConnection conn = new SqlConnection(connstring);

    SqlCommand cmd = new SqlCommand("GetPassword", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = firstName;
    cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 100).Value = lastName;
    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;

    try
    {
        conn.Open();
        cmd.ExecuteNonQuery();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adapter.Fill(dt);


        foreach (DataRow dr in dt.Rows)
        {
            if (dr["Password"] != DBNull.Value)
            {
                password = dr["Password"].ToString();
            }
            break;
        }
    }
    catch (Exception ex)
    {
        password = "";
    }
    conn.Close();
    return password;
}

public void SendEmail(string firstname, string lastname, string email, string password)
{
    MailMessage emailMessage = new MailMessage("YourEmail@gmail.com", email);
    emailMessage.Subject = "Password Recovery";

    string body = "Dear " + firstname + " " + lastname + ",<br/><br/>";
    body += "Here is your password '" + password + "'. <br/>";
    body += "Please login using your email and password. <br/><br/>";
    body += "Thank You";

    emailMessage.Body = body;
    emailMessage.IsBodyHtml = true;

    SmtpClient client = new SmtpClient();
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    NetworkCredential NetworkCred = new NetworkCredential("YourEmail", "YourPassword");
    client.UseDefaultCredentials = true;
    client.Credentials = NetworkCred;
    client.Port = 587;
    client.Send(emailMessage);
}

VB.NET

Protected Sub btnRetrievePassword_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRetrievePassword.Click
    Dim password As String = GetPassword(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim())

    If password <> "" Then
        Try
            SendEmail(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim(), password)
            lblMessage.Text = "Your password is sent to your email"
        Catch ex As Exception
            lblMessage.Text = "Sorry! an error occured while sending email, please try again"
        End Try
    Else
        lblMessage.Text = "Please provide correct information"
    End If
End Sub

Public Function GetPassword(ByVal firstName As String, ByVal lastName As String, ByVal email As String) As String
    Dim password As String = ""

    Dim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"
    Dim conn As New SqlConnection(connstring)

    Dim cmd As New SqlCommand("GetPassword", conn)
    cmd.CommandType = CommandType.StoredProcedure

    cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = firstName
    cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 100).Value = lastName
    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email

    Try
        conn.Open()
        cmd.ExecuteNonQuery()
        Dim adapter As New SqlDataAdapter(cmd)
        Dim dt As New DataTable()
        adapter.Fill(dt)


        For Each dr As DataRow In dt.Rows
           If IsDBNull(dr("Password") = False) Then
                password = dr("Password").ToString()
           End If
           Exit For
        Next
    Catch ex As Exception
        password = ""
    End Try
    conn.Close()
    Return password
End Function

Public Sub SendEmail(ByVal firstname As String, ByVal lastname As String, ByVal email As String, ByVal password As String)
    Dim emailMessage As New MailMessage("YourEmail@gmail.com", email)
    emailMessage.Subject = "Password Recovery"

    Dim body As String = "Dear " & firstname & " " & lastname & ",<br/><br/>"
    body += "Here is your password '" & password & "'. <br/>"
    body += "Please login using your email and password. <br/><br/>"
    body += "Thank You"

    emailMessage.Body = body
    emailMessage.IsBodyHtml = True

    Dim client As New SmtpClient()
    client.Host = "smtp.gmail.com"
    client.EnableSsl = True
    Dim NetworkCred As New NetworkCredential("YourEmail", "YourPassword")
    client.UseDefaultCredentials = True
    client.Credentials = NetworkCred
    client.Port = 587
    client.Send(emailMessage)
End Sub
answer Feb 5, 2016 by Shivaranjini
...