Go to DotNetFunda.com
 Online : 1747 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET > Password Reminder: Reset the password and send it to the user's provided mail address

  • Download the OOPS, ASP.NET and ADO.NET Training Videos for FREE, click here.

Submit Article | Articles Home | Search Articles |

Password Reminder: Reset the password and send it to the user's provided mail address

 Posted on: 9/14/2009 1:34:20 AM by Utsav | Views: 820 | Category: ASP.NET | Level: Intermediate | Print Article
After learning this tutorial, you will be able to generate a random password and send it to the user's requested mail address.

.NET Training Videos!
Buy online comprehensive training video pack just for $35.00 only, see what's inside it.

Introduction
This is a tutorial to how to make password reminder page in your application. It first takes the username and email address input from the User  and then checks whether the username exit or not then generates the random password and then mails the reset password to the user's mail address.

Database
Design the table named as Users and provide the following column as shown in the diagram.
 




Design Page Passwordreminder.aspx
Now its time to design your page which looks as:


..and the coding for the above output goes here:

PasswordReminder.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div style="left:15px; position:absolute; top:20px;">
Enter Your UserName and EmailID to reset your password..
</div>

<div style="left:15px; position:absolute; top:60px;">
<asp:Label ID="lblUserName" runat="server" Text="User Name"></asp:Label>
</div>

<div style="left:110px; position:absolute; top:60px;">
<asp:TextBox ID="txtuserName" runat="server"></asp:TextBox>
</div>

<div style="left:15px; position:absolute; top:100px;">
<asp:Label ID="lblEmail" runat="server" Text="Email Address"></asp:Label>
</div>

<div style="left:110px; position:absolute; top:100px;">
<asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
</div>

<div style="left:200px; position:absolute; top:140px;">
<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
Text="Submit" />
</div>

<div style="left:15px; position:absolute; top:200px;">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>



</form>
</body>
</html>




  Now the coding section for the PasswordReminder.aspx.cs :

public partial class PasswordReminder : System.Web.UI.Page
{
public char[] chars = new char[6]; // Stores the newly generated passwords.
public static bool flag = false;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{

checkUsername(); // Function checks whether the username exist or not
if (flag == true)
{
resetPass(); // Function resets the password of current username
sendMail(); // Function sends the newly generated password to the User's mail
// address
}
else
{
lblMessage.Text = "Please provide the correct Username !";
}

}

  Above we can see after the submit button is clicked it fires the btnSubmit_Click() function.

Now lets view the coding for the function checkUsername()

 protected void checkUsername()
{
string username = txtuserName.Text;
string connStr = ConfigurationManager.ConnectionStrings["UsersString"].ToString();

SqlConnection conn = new SqlConnection(connStr);
SqlCommand dCmd = new SqlCommand("SELECT * FROM Users", conn);

SqlDataReader reader;

try
{
conn.Open();

reader = dCmd.ExecuteReader();

while (reader.Read())
{
string dbusername = reader["UserName"].ToString();

if (username.Equals(dbusername))
{
flag = true;
break;
}


}
}
catch(Exception ee)
{
lblMessage.Text = ee.Message.ToString();

}
finally
{
dCmd.Dispose();
conn.Close();
}
}

       The above function checks whether the Username exist or not. If the Username exist then publicly defined boolean variable flag is set to true. but if not then the flag is still false. Afer this function executes then the flag is checked whether it is false or true.
If the flag is false then the Output: "Please provide the correct username !" is generated(cause username does not exist in the database)
       If Username exists then the resetPass() and sendMail() function executes which generates the 6 digit random password and sends to the user's mail address correspondingly.

Here the connectionstring for my database i used as : UsersString. My Webconfig files looks as below:

<connectionStrings>

  <add name="UsersString" connectionString="Data    Source=DataSource1 ;Initial Catalog=YourProjectName;Integrated Security=True;Pooling=False user id=SampleUser; password=SampleUser;"

   providerName="System.Data.SqlClient" />

</connectionStrings>

The remaining function resetPass() and sendMail() goes here:

resetPass() :

protected void resetPass()

    {

        string username = txtuserName.Text;

   string connStr = ConfigurationManager.ConnectionStrings["UsersString"].ToString();


        SqlConnection conn = new SqlConnection(connStr);

        SqlCommand dCmd = new SqlCommand("UPDATE Users SET Password = @passWord WHERE UserName = '" + username + "' ", conn);

        dCmd.CommandType = CommandType.Text;

        conn.Open();

        try

        {

            int PasswordLength = 6;

            string allowedchars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";

            Random randNum = new Random();

            int allowedCharCount = allowedchars.Length;



            for (int i = 0; i < PasswordLength; i++)

            {

                chars[i] = allowedchars[(int)((allowedchars.Length) * randNum.NextDouble())];



            }

           string newpass = new string(chars);

           dCmd.Parameters.AddWithValue("@passWord", newpass);

           dCmd.ExecuteNonQuery();

           

        }

        catch (Exception ee)

        {

            lblMessage.Text = ee.Message.ToString();

        }

        finally

        {

            dCmd.Dispose();

            conn.Close();

        }
  }

 

sendMail() : 

protected void sendMail()
{

string newpass = new string(chars);

string email = txtemail.Text;
string from = "Yourmail@serverdomain.com";

try
{

MailMessage mMailmessage = new MailMessage();

mMailmessage.From = new MailAddress(from);

mMailmessage.To.Add(new MailAddress(email));

mMailmessage.Subject = "noreply";

mMailmessage.Body = "Your Password is:" + newpass + "";


// Set the format of the mail message body as HTML

mMailmessage.IsBodyHtml = true;


mMailmessage.BodyEncoding = System.Text.Encoding.ASCII;


SmtpClient mSmtpClient = new SmtpClient();

mSmtpClient.Host = "YourMailserverName";



mSmtpClient.Port = 25;


mSmtpClient.Send(mMailmessage);

mMailmessage.Dispose();
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}

}

You have to set your mailsettings in webconfig file before using the mail function.

<system.net>
<mailSettings>
<smtp from="Yourmail@serverdomain.com">

<network host="YourMailserverName" port="25" userName="" password="" />
</smtp>

</mailSettings>

</system.net>
Conclusion:
Thus this tutorial teaches how to generate the password randomly and send it to the specified Username.



If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Interesting?   Share and Bookmark this kick it on DotNetKicks.com


Experience:1 year(s)
Home page:http://www.uts-chupakabras.blogspot.com
Member since:Wednesday, June 17, 2009
Level:Starter
Status: [Member]
Biography:I am working in the APCA Nepal as a Software Developer. Recently I am doing the project on asp.net with c# page language. My project tilte is "Event and contact management " in which different users working in their desk can make their events and entries, assign the task to others, upload their documents and share with others. You can find my same articles in http://www.uts-chupakabras.blogspot.com/ also.
 Latest post(s) from Utsav

   ◘ Password Reminder: Reset the password and send it to the user's provided mail address posted on 9/14/2009 1:34:20 AM
   ◘ Multiple Delete From a gridview in one click. posted on 8/10/2009 10:14:21 PM


Submit Article

About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)