Sql Query Convert to Linq query with Reader Object - c#

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 .

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

c# how to get printout info from sql server query

DECLARE #message VARCHAR(10)
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')
BEGIN
SET #message = '{1}'
END
ELSE
BEGIN
SET #message = 'NOT_OK'
END
PRINT(#message)
I execute above command from c# app.
How can I get print message?
Im trying like this:
if(connection.State.ToString() == "Closed")
{
connection.Open();
}
SqlCommand newCmd = connection.CreateCommand();
newCmd.Connection = connection;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = string.Format(queriesMgr.getQuery(SqlQueriesID.IS_TABLE_EXISTS), "student", "OK");
SqlDataReader reader = newCmd.ExecuteReader();
if (reader.Read())
{
//not enter here(no data to read)
}
Anyone could tell me what Im doing wrong?
If you use the following query your reader will see the output select.
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')
BEGIN
SELECT '{1}'
END
ELSE
BEGIN
SELECT 'NOT_OK'
END

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");
}
}

Changing Password using if and else block

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();
}
}

Load stored procedure results into data table

I've been searching the net for answers but have come up empty again and again.
What I'm trying to do:
Load the results from a stored procedure into a DataTable.
What's going wrong:
I'm not getting any rows returned.
Here is my stored proc (SQL Server 2012). It gets the next auto incremented ID of a table you input and returns it.
ALTER procedure [dbo].[GET_NEXT_AUTO_ID_OF_TABLE]
#TABLE_NAME nvarchar(128),
#NEXT_ID int output
as
declare #latest_id int, #row_count int
begin
set #latest_id = (select IDENT_CURRENT(#TABLE_NAME))
end
if #latest_id = 1
begin
declare #lRowCountSql nvarchar(1000)
set #lRowCountSql = N'select #row_count = count(*) from ' + #TABLE_NAME
exec sp_executesql #lRowCountSql, N'#row_count int out', #row_count out
if #row_count > 0
set #next_id = #latest_id + 1
else
set #next_id = #latest_id
end
else
set #next_id = #latest_id + 1
return
Is the problem my proc (I'm not good with sql)? When I test the proc in SQL Server I get the result I expect.
But not from my C# code:
List<SqlParameter> aSqlParams = new List<SqlParameter>();
aSqlParams.Add(new SqlParameter("#TABLE_NAME", "your table name") { Direction = System.Data.ParameterDirection.Input, SqlDbType = System.Data.SqlDbType.NVarChar });
aSqlParams.Add(new SqlParameter() { ParameterName = "#NEXT_ID", Direction = System.Data.ParameterDirection.Output, SqlDbType = SqlDbType.Int });
DataTable lDt = SQLServerUtils.ExecuteStoredProc("GET_NEXT_AUTO_ID_OF_TABLE", aSqlParams);
int lNextID = lDt.Rows[0].Field<int>("NEXT_ID");
public static DataTable ExecuteStoredProc(string aProcName, List<SqlParameter> aSqlParams)
{
DataTable lResults = new DataTable();
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(aProcName, conn);
cmd.CommandType = CommandType.StoredProcedure;
if (aSqlParams != null)
foreach (SqlParameter lP in aSqlParams)
cmd.Parameters.Add(lP);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(lResults);
}
return lResults;
}
An output parameter is returned by itself, not included in a datatable.
I think you need a different procedure that executes these kind of query,
public static int ExecuteOutputIntParam(string aProcName, string outputParamName, List<SqlParameter> aSqlParams)
{
int outValue = -1;
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(aProcName, conn);
cmd.CommandType = CommandType.StoredProcedure;
if (aSqlParams != null)
foreach (SqlParameter lP in aSqlParams)
cmd.Parameters.Add(lP);
int result = cmd.ExecuteNonQuery();
if (aSqlParams != null)
{
outValue = Convert.ToInt32(aSqlParams[outputParamName].Value);
}
}
return outValue;
}
EDIT
I have copy/pasted your example and I haven't noticed that you rely on the SqlDataAdapter to open/close the connection. In my example the connection should be explicitly opened
The trick here is that the value I want comes back inside the out parameter.
The fixed code looks like this...
SQL proc:
ALTER procedure [dbo].[GET_NEXT_AUTO_ID_OF_TABLE]
#TABLE_NAME nvarchar(128),
#NEXT_ID int output
as
declare #latest_id int, #row_count int
begin
set #latest_id = (select IDENT_CURRENT(''+#TABLE_NAME+''))
end
if #latest_id = 1
begin
declare #lRowCountSql nvarchar(1000)
set #lRowCountSql = N'select #row_count = count(*) from ' + #TABLE_NAME
exec sp_executesql #lRowCountSql, N'#row_count int out', #row_count out
if #row_count > 0
set #next_id = #latest_id + 1
else
set #next_id = #latest_id
end
else
set #next_id = #latest_id + 1
return
C#:
public static int GetNextIdOfTable(string aTableName)
{
int lNextID = 0;
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand("GET_NEXT_AUTO_ID_OF_TABLE", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#TABLE_NAME", aTableName) { Direction = System.Data.ParameterDirection.Input, SqlDbType = System.Data.SqlDbType.NVarChar });
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#NEXT_ID", Direction = System.Data.ParameterDirection.Output, SqlDbType = SqlDbType.Int });
conn.Open();
cmd.ExecuteReader();
if (cmd.Parameters["#NEXT_ID"] != null && cmd.Parameters["#NEXT_ID"].Value != DBNull.Value)
return int.Parse(cmd.Parameters["#NEXT_ID"].Value.ToString());
}
return lNextID;
}

Categories