Generate random password in asp.net using c# and save in database

Generate random password in asp.net using c# :-In this I going to show how to do registration and generate random password and save it in database. We will also send the mail to user's email for confirmation of UserID and password.

This is very pretty step to generate random password of 8-digits, you can generate any digit of password depends on you. Alright let's get start.


How to generate random password in asp.net using c# and save in databse



Create table

CREATE TABLE employee
(
      [id] [int] Primary key IDENTITY(1,1) NOT NULL,
      [username] [varchar](50) ,
      [email] [varchar](50) ,
      [password] [varchar](20)
)



First of all add the database connection within web.config file

<configuration>
  <connectionStrings>
    <add name="Mycon" connectionString="initial catalog =Test11718; data source=SANJAY\SQL2012; integrated security=true" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>

</configuration>



Add a asp.net webform which name will be user-registration.aspx In this take two text-box one label and one button to save a record in database.


     Read More: How to upload image in gridview in asp.net using c#


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="user-registration.aspx.cs" Inherits="user_registration" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>             
                    <b>Send Password to Email and save it in database</b>
                <tr>
                    <td class="style1">Username:</td>
                    <td>
                        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
                    </td>
                    <td></td>
                </tr>
                <tr>
                    <td class="style1">Email:</td>
                    <td>
                        <asp:TextBox ID="txt_Email" runat="server"></asp:TextBox>
                    </td>
                    <td></td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                    <td>
                     <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit"/>
                    </td>
                    <td></td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>





Now come on the user-registration.aspx.cs   and add each and every necessary namespaces.


using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;


public partial class user_registration : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateRandomPassword(8);
    }
    public static string CreateRandomPassword(int PasswordLength)
    {
        string _allowedChars = "0123456789";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;
        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
        }
        return new string(chars);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pwd = CreateRandomPassword(8);
        SqlCommand cmd = new SqlCommand("insert into employee(username,email,password) values (@username,@email,@password)", con);
        cmd.Parameters.AddWithValue("@username", txt_name.Text);
        cmd.Parameters.AddWithValue("@email", txt_Email.Text);
        cmd.Parameters.AddWithValue("@password", pwd);
        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();
        sendmail();
    }

    public void sendmail()
    {
        SqlCommand cmd_cus = new SqlCommand("select email from employee where email=@Email", con);
        cmd_cus.Parameters.AddWithValue("@Email", txt_Email.Text);
        con.Open();
        SqlDataReader dr = cmd_cus.ExecuteReader();
        if (dr.HasRows)
        {
            dr.Read();
        }
        string strNewPassword = CreateRandomPassword(8);
        string me = dr["email"].ToString();
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("[email protected]");
        msg.To.Add(txt_Email.Text);
        msg.Subject = "Job Portal:Login Detail for your Account";
        msg.Body = "Your password is:-" + strNewPassword + "<br />" + "Your user name same as you email:- " + me;
        msg.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "yourpassword");
        smtp.EnableSsl = true;
        smtp.Send(msg);
        lblMessage.Text = "Email Sent Successfully";
        lblMessage.ForeColor = System.Drawing.Color.ForestGreen;
    }
}



In above tutorial I explained "how to generate random password in asp.net using c# and save in database"  for the Gmail.com domain name. if you have another account like yahoo.com , outlook.com  then you may have to change port number and little bit code.


After done all these step , may you face a problem like this "Authentication the Server Response was 5.5.1 Authentication required in gmail" . In this case follow the given steps.


1. Login to your gmail account.
2. Visit this page https://accounts.google.com/DisplayUnlockCaptcha and click on button to allow access.
3. Visit this page https://www.google.com/settings/security/lesssecureapps and enable access for less secure apps.


Read our previous post

1 Comments

Post a Comment

Post a Comment

Previous Post Next Post