Changing Password using if and else block - c#

I am the admin who wants to change the password for anyone by entering their email address and the new password in textbox.The stored procedure is as below:
Alter proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS (SELECT * FROM tblRegister WHERE Email=#Email)
begin
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
Select 0
end
ELSE
BEGIN
Select -1
end
end
and the code-behind is as below:
private void ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
cmd.ExecuteNonQuery();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ChangePassword();
}
But i want to check if the email exists in the table using if and else statements.If the email exists then change password else throw an exception.What can i do?

You could simply change a bit the code of your procedure and have it to return a value.
0 would mean that the password updated and -1 that there is not an email like the one provided.
ALTER proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
AS
BEGIN
IF EXISTS (SELECT * FROM Users WHERE Email=#Email) THEN
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
SELECT 0 AS Result
END
ELSE
BEGIN
SELECT -1 AS Result
END
END
Then you have to read the result of the stored procedure and act correspondingly. So your server side code must be changed to the following:
var reader = cmd.ExecuteReader();
while (reader.Read())
{
if(int.Parse(reader["Result"].ToString())==0)
{
// success
}
else
{
// failure
}
};
update In the if statement, you could also use this one:
Convert.ToInt32(reader["Result"])==0
I think it will work like a charm.

Inside your Stored procedure add this
Begin
DECLARE #id AS INT
SELECT #id = tblRegisterId FROM tblRegisterWHERE Email =#Email
IF #id IS not NULL
Begin
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
Select 1
End
Else
Begin
Select 0
End
End

Try this :-
private bool ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
return true;
else
return false;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool success = ChangePassword(); //Use this success variable to show a message.
}
You can also change your stored procedure, but it wont throw any exception, only it will check. If the Email exists, it will execute the update query :-
Create proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS ( SELECT * FROM tblRegister WHERE Email = #Email)
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
END
end

SQL
Create proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS ( SELECT * FROM tblRegister WHERE Email = #Email)
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
END
ELSE
BEGIN
RAISEERROR('Email does not exists',0,1)
END
end
c#
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
try{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
cmd.ExecuteNonQuery();
}
catch(SqlException ee)
{
...
}
}

Try this Store Procedure ( Please use IF EXISTS)
CREATE PROCEDURE InsertName
(
#Email varchar(25),
#Passwordd varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM tblRegister WHERE Email = #Email)
BEGIN
--This means it exists,update
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
SELECT 'Changed successfully'
END
ELSE
BEGIN
--This means the record isn't in there already
SELECT 'Does Not Exist'
END
private string ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
return cmd.ExecuteNonQuery().ToString();
}
}

Related

GridView Row Update SQL Server parameter not defined

Below is my method to update the row once the update button is clicked. My SQL Server stored procedure is expecting the existing company name before it has been updated, the new company name and whether it exists or not. The bold part is where it is breaking. When I select edit, I want to parse in the current value in the company name row before I hit update.
protected void CompanyTable_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand("[updateCompanyName]", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
GridViewRow row = CompanyTable.SelectedRow;
cmd.Parameters.AddWithValue("#CurrentCompanyName", CompanyTable.Rows[e.RowIndex].Cells[0].Controls[0]);
cmd.Parameters.AddWithValue("#NewCompanyName", CompanyInputTextBox.Text).Direction = ParameterDirection.Input;
SqlParameter objisExists = new SqlParameter("#isExists", SqlDbType.Int);
objisExists.Direction = ParameterDirection.Output;
cmd.Parameters.Add(objisExists);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
int isExists = Convert.ToInt32(cmd.Parameters["#isExists"].Value.ToString());
if (isExists == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "111", "AddCompanySuccess();", true);
}
else if (isExists == 1)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "111", "CompanyExistsValidation();", true);
}
}
}
Stored procedure parameters:
ALTER PROCEDURE [dbo].[updateCompanyName]
#CurrentCompanyName VARCHAR(50),
#NewCompanyName VARCHAR(50),
#IsExists INT = 0 OUT
My update in SQL:
DECLARE #CompanyID INT
SELECT #CompanyID = CompanyID
FROM company
WHERE companyname = #CurrentCompanyName
BEGIN
IF EXISTS (SELECT CompanyName FROM company
WHERE companyname = #NewCompanyName )
BEGIN
SET #IsExists = 1
END
ELSE
BEGIN
UPDATE COMPANY
SET CompanyName = #NewCompanyName
WHERE companyid = #CompanyID
SET #IsExists = 0
END
END
PRINT #isexists

Sql Query Convert to Linq query with Reader Object

I currently working on Linq to Sql. I have some knowledge write the linq query and how to convert it but with this query I am facing some problems . Any one can help me what will this linq query for this following sql query.
Here is store procedure .The name of procedure is spAuthenticateUser..
CREATE proc [dbo].[spAuthenticateUser]
#UserName nvarchar(100),
#Password nvarchar(200)
as
Begin
Declare #AccountLocked bit
Declare #Count int
Declare #RetryCount int
Select #AccountLocked = IsLocked
from tblUsers where UserName = #UserName
--If the account is already locked
if(#AccountLocked = 1)
Begin
Select 1 as AccountLocked, 0 as Authenticated, 0 as RetryAttempts
End
Else
Begin
-- Check if the username and password match
Select #Count = COUNT(UserName) from tblUsers
where [UserName] = #UserName and [Password] = #Password
-- If match found
if(#Count = 1)
Begin
-- Reset RetryAttempts
Update tblUsers set RetryAttempts = 0
where UserName = #UserName
Select 0 as AccountLocked, 1 as Authenticated, 0 as RetryAttempts
End
Else
Begin
-- If a match is not found
Select #RetryCount = IsNULL(RetryAttempts, 0)
from tblUsers
where UserName = #UserName
Set #RetryCount = #RetryCount + 1
if(#RetryCount <= 3)
Begin
-- If re-try attempts are not completed
Update tblUsers set RetryAttempts = #RetryCount
where UserName = #UserName
Select 0 as AccountLocked, 0 as Authenticated, #RetryCount as RetryAttempts
End
Else
Begin
-- If re-try attempts are completed
Update tblUsers set RetryAttempts = #RetryCount,
IsLocked = 1, LockedDateTime = GETDATE()
where UserName = #UserName
Select 1 as AccountLocked, 0 as Authenticated, 0 as RetryAttempts
End
End
End
End
GO
Here is ADO.NET CODE ..
public bool AuthenticateUser(UserLogin userLogin)
{
// ConfigurationManager class is in System.Configuration namespace
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
// SqlConnection is in System.Data.SqlClient namespace
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spAuthenticateUser", con);
cmd.CommandType = CommandType.StoredProcedure;
//Formsauthentication is in system.web.security
string encryptedpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(userLogin.Password, "SHA1");
//sqlparameter is in System.Data namespace
SqlParameter paramUsername = new SqlParameter("#UserName", userLogin.Username);
SqlParameter paramPassword = new SqlParameter("#Password", encryptedpassword);
cmd.Parameters.Add(paramUsername);
cmd.Parameters.Add(paramPassword);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int RetryAttempts = Convert.ToInt32(rdr["RetryAttempts"]);
if (Convert.ToBoolean(rdr["AccountLocked"]))
{
return true;
}
else if (RetryAttempts > 0)
{
int AttemptsLeft = (4 - RetryAttempts);
//lblMessage.Text = "Invalid user name and/or password. " +
// AttemptsLeft.ToString() + "attempt(s) left";
}
else if (Convert.ToBoolean(rdr["Authenticated"]))
{
return true;
}
}
return false;
}
}
Thanks .

Executescalar receives wrong value when stored procedure returns value

I am trying to return a single value to c# using the executescalar method.
When I execute the below stored procedure in SQL Server, the if..blocks are working fine but executescalar in c# always returns 0.
Please refer to the below code:
USE [xx]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[prcAddress]
#ID int,
#Name varchar(50),
#Designation varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #count as Integer -- To count records
Declare #Result int -- To return result
SELECT #Result=0
SELECT #count = (SELECT count(*) FROM dbo.Address)
IF #ID >0
BEGIN
--Update the current entry
SELECT #Result=1
END
ELSE IF #ID =0 AND #count=0
BEGIN
-----do something
SELECT #Result=2
END
ELSE IF #ID=0 AND #count>0
BEGIN
----do something
SELECT #Result=3
END
ELSE
BEGIN
SELECT #Result=4
END
SELECT #Result As Result
END
GO
SqlConnection sqlCon = new SqlConnection(ConnectionString);
SqlCommand sqlCom = new SqlCommand();
try
{
sqlCom = new SqlCommand("prcAddress", sqlCon);
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCom.CommandTimeout = 15;
sqlCom.Connection = sqlCon;
foreach (KeyValuePair<Object, Object> parmater in parameters)
{
if (parmater.GetType() == typeof(DateTime))
{
sqlCom.Parameters.Add("#" + parmater.Key, SqlDbType.DateTime).Value = parmater.Value;
}
else
{
sqlCom.Parameters.AddWithValue("#" + parmater.Key, parmater.Value);
}
}
if (sqlCon.State != ConnectionState.Closed)
{
sqlCon.Close();
}
sqlCon.Open();
if (sqlCom.ExecuteScalar() != null)
{
result = sqlCom.ExecuteScalar().ToString();
}
else
{
result = "";
}
}
catch (SqlException sqlEx)
{
System.Web.HttpContext.Current.Response.Redirect("~/Error.aspx", false);
}
finally
{
sqlCon.Close();
sqlCom = null;
}
You're probably seeing the result of the first select, 'SELECT #Result=0'. Either comment out all the selects prior to the last select in your stored procedure or change it to a scalar function that returns the result.

Check stored procedure parameter to check the user role

I need to check in C# if the user has a particular role from the database and in windows form my login code is
SqlCommand cmd = new SqlCommand("SELECT UserName,Password FROM EMP_Info WHERE UserName='" + txt_Username.Text + "' and Password='" + txt_password.Text + "'", sqlcon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Cursor.Current = Cursors.WaitCursor;
// I need to make if here to check the role if the user is admin or not
// if admin do something
MessageBox.Show("Welcome " + txt_Username.Text);
}
else
{
MessageBox.Show("The Username or Password you entered is incorrect. Please try again");
sqlcon.Close();
}
My database code
create proc Check_role
#EMP_Role varchar (10),
as
begin
if (exists(select EMP_Role from EMP_Info where EMP_Role ='Admin' ))
return 1
else
return 2
end
so i need to solve this problem
To avoid SQL Inject Attack use parametrized query something like this.....
SqlCommand cmd = new SqlCommand("SELECT [UserName] , [Password] FROM EMP_Info WHERE [UserName] = #UserName and [Password] = #Password", sqlcon);
cmd.Parameters.AddWithValue("#UserName" , txt_Username.Text);
cmd.Parameters.AddWithValue("#Password" , txt_password.Text);
//rest of the code
Anyway I would create a procedure to make just one call to database to verify the user logging in. A stored procedure can look something like ....
CREATE PROCEDURE Check_role
#UserName VARCHAR(100)
,#Password VARCHAR(100)
,#IsValid INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Emp_Role VARCHAR(10);
DECLARE #UserName_check VARCHAR(10);
DECLARE #PassWord_check VARCHAR(10);
SELECT TOP 1 #Emp_Role = EMP_Role
,#UserName_check = [UserName]
,#PassWord_check = [Password]
FROM EMP_Info
WHERE [UserName] = #UserName
AND [Password] = #Password
IF ((#UserName_check = #UserName) AND (#PassWord_check = #Password))
BEGIN
SET #IsValid = 1;
IF (#Emp_Role = 'Admin')
BEGIN
SET #IsValid = 2;
END
END
ELSE
BEGIN
SET #IsValid = 0;
END
END
C# Code
using(SqlConnection Sqlcon = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("dbo.Check_role", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#UserName", txt_Username.Text);
cmd.Parameters.AddWithValue("#Password", txt_password.Text);
cmd.Parameters.Add("#IsValid", SqlDbType.Int);
cmd.Parameters["#IsValid"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
string LoginStatus = cmd.Parameters["#IsValid"].Value.ToString();
if (LoginStatus == 1 || LoginStatus == 2)
{
if(LoginStatus == 2)
{
// if a user is admin do stuff here
}
else
{
// if a user is NOT admin do stuff here
}
MessageBox.Show("Welcome " + txt_Username.Text);
}
else
{
MessageBox.Show("The Username or Password you entered is incorrect. Please try again");
}
}

returning int value from stored procedure and check it in asp.net code to validate login form [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
returning int value from stored procedure and check it in asp.net code to validate login form
hello all please i need help in this code as it is stored procedure validate username and password , the problem here is that form validate any data even it doesn't stored in database and i tried to fix code many times but really i haven't any more thing to do in it , any one can help me to solve this problem
this is stored procedure
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[login_procedure] #username Varchar =50, #password varchar=50, #result int OUTPUT
as
Declare #user_name varchar , #pass_word varchar
Set #user_name = #username
Set #pass_word = #password
if EXISTS (select #username , #password from data where username= #user_name and password=#pass_word)
select #result=1
else
select #result=0
and this is asp.net code
SqlConnection conn = new SqlConnection ("Data Source=ANAGUIB-LAPNEW\\SQLEXPRESS;Initial Catalog=account;Integrated Security=True");
SqlCommand cmd = new SqlCommand("login_procedure", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramReturnValue = new SqlParameter();
paramReturnValue.ParameterName = "#result";
paramReturnValue.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(paramReturnValue);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
conn.Open();
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
int resultID = Convert.ToInt32(cmd.ExecuteScalar());
if (Convert.ToInt32(resultID) == 0)
{
Response.Redirect("hello.aspx");
}
else
{
Response.Write("error");
}
conn.Close();
}
Your stored-procedure has OUTPUT parameter and it is good practice to access value of output parameter after closing the connection.
I've changed proc.
ALTER PROCEDURE login_procedure
#username Varchar(50),
#password varchar(50),
#result int OUTPUT
AS
IF EXISTS (select username from data where username= #username and password=#password)
set #result=1
else
set #result=0
Demo: How to pass parameters (IN and OUT)?
SqlConnection cn = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "login_procedure";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param1 = new SqlParameter("#username", System.Data.SqlDbType.VarChar, 50);
SqlParameter param2 = new SqlParameter("#password", System.Data.SqlDbType.VarChar, 50);
SqlParameter resultParam= new SqlParameter("#result", System.Data.SqlDbType.Int);
resultParam.Direction = System.Data.ParameterDirection.Output;
param1.Value = TextBox1.Text;
param2.Value = TextBox2.Text;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
cmd.Parameters.Add(resultParam);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
int retVal;
int.TryParse(resultParam.Value.ToString(),out retVal);
if(retVal==1)
//
else
//
In this code
if EXISTS (select #username ,
#password
from data
where username= #user_name and password=#pass_word)
select #result=1
else
select #result=0
You are returning 1 if the given input is validated in your C# code you are giving error when the return value is not 0, that is why every input even which does not exist in your table is validated.Try this;
if (resultID == 1)
{
Response.Redirect("hello.aspx");
}
else
{
Response.Write("error");
}
And you do not have to Convert the return value of stored procedure twice, once is enough.

Categories