Introduction:
In this article I will explain how to create change password page/ form in
asp.net using both the C# and
VB.Net languages and using Stored procedure and SQL server as a back end database.
Description: Steps we follow in this article:
Description: Steps we follow in this article:
- Validate
username and password from the Sql server database
- Create change password form and update the password.
- Use
output parameter in stored procedure to return value. And read the
return output in the code behind.
- Use COLLATE Latin1_general_CS_AS
to check for case sensitive match.
Implementation: Let’s create an asp.net application to
understand the concept.
Create a
Sql server database and name it "Test" and create a table with the
following fields and name it "Login_Tb"
Column
Name
|
Data
Type
|
Id
|
Int( Primary Key. So set Is
Identity=True)
|
UserName
|
varchar(100)
|
Password
|
varchar(100)
|
- Add
dummy username e.g. admin and password e.g. demo in the table.
- Then create a Stored Procedure to validate existing username and password and change the passwordas:
CREATE PROCEDURE Change_Pwd_sp
(
@username VARCHAR(100),
@old_pwd VARCHAR(50),
@new_pwd VARCHAR(50),
@status int OUTPUT
)
AS
BEGIN
IF EXISTS(SELECT * FROM Login_Tb WHERE UserName COLLATE Latin1_general_CS_AS=@username AND[PASSWORD] COLLATE Latin1_general_CS_AS=@old_pwd)
BEGIN
UPDATE Login_Tb SET [PASSWORD]=@new_pwd WHERE UserName=@username
SET @status=1
END
ELSE
BEGIN
SET @status=0
END
END
RETURN @status
In the above stored procedure,
first of all we validate the username
and password against database values.If matched
then the new password will overwrite the old password otherwise "Wrong Username/Password" message
will be displayed. We used Output parameter to return the status i.e. 1 for success and 0 for failure.
I have also used the COLLATE Latin1_general_CS_AS
to check case sensitive. e.g. Demo and demo will not same in if we use this. It
will find exact match.
Create
Connection string in Web.Config file
<connectionStrings>
<add name="Empcon" connectionString="Data Source=localhost;Initial
Catalog=Test;Integrated Security=True"/>
</connectionStrings>
Note: Replace
the Data Source and the Initial Catalog(database name) as per your application.
Source Code:
Design Section:
<div>
<fieldset
style="width:350px;">
<legend><strong>Change password
in asp.net</strong></legend>
<table>
<tr>
<td>User Name: * </td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvuserName" runat="server"
ErrorMessage="Please enter User Name" ControlToValidate="txtUserName"
Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Old Password: * </td>
<td>
<asp:TextBox ID="txtOldPwd" runat="server" TextMode="Password"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvOldPwd" runat="server"
ErrorMessage="Please enter old password" ControlToValidate="txtOldPwd"
Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>New Password: * </td>
<td>
<asp:TextBox ID="txtNewPwd" runat="server" TextMode="Password"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvNewPwd" runat="server"
ErrorMessage="Please
enter new password" ControlToValidate="txtNewPwd"
Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Confirm Password: * </td>
<td>
<asp:TextBox ID="txtConfirmPwd" runat="server" TextMode="Password"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvConfirmPwd" runat="server"
ErrorMessage="Please re-enter password to confirm"
ControlToValidate="txtConfirmPwd" Display="Dynamic" ForeColor="Red"
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cmvConfirmPwd" runat="server"
ControlToCompare="txtNewPwd" ControlToValidate="txtConfirmPwd"
Display="Dynamic" ErrorMessage="New and confirm password didn't match"
ForeColor="Red" SetFocusOnError="True"></asp:CompareValidator>
</td>
</tr>
<tr>
<td>
</td><td>
<asp:Button ID="btnSubmit" runat="server" Text="Change Password"
onclick="btnSubmit_Click" /></td>
</tr>
<tr>
<td
colspan="2">
<asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</fieldset>
</div>
C#.Net code to create Change password form/page
In the code behind file (.aspx.cs) write the
following code on change password as:
Include the following namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
write the
code as:
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["Empcon"].ConnectionString);
SqlCommand cmd = new SqlCommand("Change_Pwd_sp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@username", txtUserName.Text.Trim());
cmd.Parameters.AddWithValue("@old_pwd", txtOldPwd.Text.Trim());
cmd.Parameters.AddWithValue("@new_pwd", txtNewPwd.Text.Trim());
cmd.Parameters.Add("@Status", SqlDbType.Int);
cmd.Parameters["@Status"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
//read the return value (i.e status) from the
stored procedure
int retVal= Convert.ToInt32(cmd.Parameters["@Status"].Value);
int retVal= Convert.ToInt32(cmd.Parameters["@Status"].Value);
if (retVal == 1)
{
lblStatus.Text = "Password has been changed successfully";
// Or show in messagebox using:
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Password has been
changed successfully');", true);
}
else
{
lblStatus.Text = "Wrong old
username/password. Please re-enter.";
// Or show in messagebox using:
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Wrong username/password. Please re-enter.');", true);
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
// Response.Write("Oops!!
following error occured: "
+ex.Message.ToString());
}
}
VB.Net Code to create Change password form/page
- In the code behind file (.aspx.vb) write the
following code on change pass word as:
First of
all import the following namespaces:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Then
write the code as:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
Try
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Empcon").ConnectionString)
Dim cmd As New SqlCommand("Change_Pwd_sp", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@username", txtUserName.Text.Trim())
cmd.Parameters.AddWithValue("@old_pwd", txtOldPwd.Text.Trim())
cmd.Parameters.AddWithValue("@new_pwd", txtNewPwd.Text.Trim())
cmd.Parameters.Add("@Status", SqlDbType.Int)
cmd.Parameters("@Status").Direction = ParameterDirection.Output
con.Open()
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
'read the return value (i.e
status) from the stored procedure
Dim retVal As Integer = Convert.ToInt32(cmd.Parameters("@Status").Value)
Dim retVal As Integer = Convert.ToInt32(cmd.Parameters("@Status").Value)
If retVal = 1 Then
lblStatus.Text = "Password has been changed successfully"
' Or show in messagebox using:
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Password has been
changed successfully');", true);
Else
lblStatus.Text = "Wrong old
username/password. Please re-enter."
' Or show in messagebox using:
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Wrong username/password. Please re-enter.');", true);
End If
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Oops!! following error occured : " & ex.Message.ToString() & "');", True)
' Response.Write("Oops!!
following error occured: " +ex.Message.ToString());
End Try
End Sub
0 comments:
Post a Comment