I am trying to reset a password to an employee number on a database through a ASP.Net application. The trouble is that it is not actually resetting the password on DB even though I am getting a confirmation message that the password has been reset.
Here is my current code
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlCmd = new SqlCommand();
string empNo = "";
empNo = txtEmpNo.Text;
empReset = txtEmpNo.Text;
// sql statement to check if employee number exists in DB
SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM tbl_Login WHERE (Emp_ID = #user)", sqlcon);
check_User_Name.Parameters.AddWithValue("#user", empNo);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
//EmpNo exists
sqlCmd = new SqlCommand("update tbl_Login set Emp_Pass=#Pass where Emp_ID=#EmpID", sqlcon);
sqlCmd.Parameters.AddWithValue("#EmpID", empNo);
sqlCmd.Parameters.AddWithValue("#Pass", "1234");
lblExists.Text = "Password reset!";
}// end if
else
{
//EmpNo doesnt exist
lblExists.Text = "Employee doesnt exists";
}//end else
you need to execute your second statement in the if:
if (UserExist > 0)
{
//EmpNo exists
sqlCmd = new SqlCommand("update tbl_Login set Emp_Pass=#Pass where Emp_ID=#EmpID", sqlcon);
sqlCmd.Parameters.AddWithValue("#EmpID", empNo);
sqlCmd.Parameters.AddWithValue("#Pass", "1234");
sqlCmd.ExecuteNonQuery(); // <- execute update
lblExists.Text = "Password reset!";
}// e
you missed
sqlCmd.ExecuteNonQuery();
Related
I'm creating a validation for form data coming from database and then comparing it with data entered in textboxes. It always executes else part whether I enter correct or incorrect data in textboxes, please help with this.
c.Uname = Text1.Value.ToString();
c.Cnic = Text2.Value.ToString();
c.pass = Text3.Value.ToString();
SqlConnection sqlConn = new SqlConnection(#"Data Source=DESKTOP-Q4AAHCG;Initial Catalog=practise;User ID=;Password=;Trusted_Connection=True");
SqlCommand sqlComm = new SqlCommand("select Uname , Cnic, password from carregister", sqlConn);
sqlConn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
while (dr.Read())
{
name = dr["Uname"].ToString();
cnic = dr["Cnic"].ToString();
passs = dr["password"].ToString();
if (name.Equals(c.Uname) && cnic.Equals(c.Cnic) && passs.Equals(c.pass))
{
Session["Uname"] = Text1.Value.ToString();
Session["cnic"] = Text2.Value.ToString();
Response.Redirect("Carloby.aspx");
}
else
{
Response.Redirect("wrongidpass.aspx");
}
}
You are reading ALL rows of your usertable and start comparing with the first received row. If this doesn't match, you are already redirecting ...
You could count only the matching rows from your database, and if that returns anything other than 1, there is an error with username or password (or your database).
c.Uname = Text1.Value.ToString();
c.Cnic = Text2.Value.ToString();
//you don't store plaintext passwords in your db, do you?
c.pass = hash_the_password(Text3.Value.ToString());
SqlConnection sqlConn = new SqlConnection(#"Data Source=DESKTOP-Q4AAHCG;Initial Catalog=practise;User ID=;Password=;Trusted_Connection=True");
SqlCommand sqlComm = new SqlCommand("SELECT COUNT(*) FROM carregister WHERE uname = #uname and cnic = #cnic and password = #hashedpassword", sqlConn);
sqlComm.Parameters.Add("#uname", SqlDbType.NVarchar).Value = c.Uname;
sqlComm.Parameters.Add("#cnic", SqlDbType.NVarchar).Value = c.Cnic;
sqlComm.Parameters.Add("#hashedpassword", SqlDbType.NVarchar).Value = c.pass;
sqlConn.Open();
if (Convert.ToInt32(sqlComm.ExecuteScalar()) == 1) {
//you have exactly one row where uname, cnic and password match the entered values
Session["Uname"] = Text1.Value.ToString();
Session["cnic"] = Text2.Value.ToString();
Response.Redirect("Carloby.aspx");
}
else
{
//no row matched
//(or more than one which is an error in the database, because uname should probably be unique)
Response.Redirect("wrongidpass.aspx");
}
I started to learn ASP.NET. I create a register system, and when I try to check if the username or email already exists in the database, it's not checked and creates the user even when you have it already.
try
{
conn.Open();
bool exists = false;
string checkuser = "SELECT count(*) FROM accounts WHERE username='" + username.Text + "'";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("username", username.Text);
exists = (int)cmd2.ExecuteScalar() > 0;
if (exists)
{
Response.Write("User already exists");
}
string command = "INSERT INTO accounts (username, email, password) VALUES (#username, #email, #password)";
SqlCommand cmd = new SqlCommand(command, conn);
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#email", email.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
cmd.ExecuteNonQuery();
}
catch(Exception)
{
label_msg.Visible = true;
label_msg.Text = "Something went wrong....";
throw;
}
finally
{
Response.Redirect("/layout.aspx");
conn.Close();
}
Thanks !
string checkuser = "if exists (select 1 from accounts where username=#username) select 1 else select 0 end";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("#username", username.Text);
bool exists = (int)cmd2.ExecuteScalar() > 0;
Having SQL Server check for the existence of matches will stop at the first match instead of potentially returning a set of matches and then it is simply returning a value accordingly. This will minimize data transferred between the server and your software plus avoid performing a count when we really just care if there are any matches.
whenever you want to find TRUE/FALSE value or counting the no records always use COUNT(1).
bool exists = false;
string checkuser = "SELECT count(*) FROM accounts WHERE username=#username;";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("#username", username.Text);
object result = cmd2.ExecuteScalar();
if (result != null)
exists = (Convert.ToInt32(result) == 1) ? true : exists;
if (exists)
{
Response.Write("User already exists");
}
Check if user Exist already
int exists = 0;
string checkuser = "SELECT count(*) FROM accounts WHERE username='" +username.Text + "'";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("username", username.Text);
exists = (int)cmd2.ExecuteScalar();
if (exists>0)
{
Response.Write("User already exists");
}
I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}
Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed
string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message
I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}
I am trying to run a SQL query based on who's logged in which gets the Team_ID and assigns it to the session variable. I am having trouble assigning the result to the variable.
protected void ButtonLogin_Click(object sender, EventArgs e)
{
//check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Team_User where Email = #username and Password_1 = #password", con);
cmd.Parameters.AddWithValue("#username", UserName.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
SqlCommand cmdID = new SqlCommand("select Team_ID from Team_User where Email = #username and Password_1 = #password", con);
cmdID.Parameters.AddWithValue("#username", UserName.Text);
cmdID.Parameters.AddWithValue("#password", Password.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
SqlDataReader reader = cmdID.ExecuteReader();
int Team_ID = reader.GetInt32(1);
Session["Team_ID"] = Team_ID;
Response.Redirect("AddPlayer.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
Your code doesn't make a whole lot of sense....
If you only want the Team_ID - why are you loading the whole row first, and then call the database again to get just the Team_ID???
I tried to simplify your code a good bit:
protected void ButtonLogin_Click(object sender, EventArgs e)
{
// check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
// define connection string and SQL query as strings
string connectionString = ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString;
string query = "SELECT Team_ID FROM dbo.Team_User WHERE Email = #username AND Password_1 = #password";
// set up SqlConnection and SqlCommand in "using" blocks
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// define and fill parameters - DO NOT use .AddWithValue!
cmd.Parameters.Add("#username", SqlDbType.VarChar, 100).Value = UserName.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 100).Value = Password.Text;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
// if we got back a result ....
if(result != null)
{
int teamID = Convert.ToInt32(result.ToString());
Session["Team_ID"] = teamID;
Response.Redirect("AddPlayer.aspx");
}
else
{
// if result is NULL, then the username+password
// were NOT found - do what needs to be done in that case here
}
}
}
}
I have the below code, that connects to a Sql database and insert's data into a table :
string firstNameV = txtFname.Text;
string surnameV = txtSname.Text;
string emailV = txtEmail.Text;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (#Title,#FirstName,#Surname,#Email,#EstablishmentType,#Interests)";
cmd.Parameters.Add("#Title", SqlDbType.NVarChar).Value = title;
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = firstNameV;
cmd.Parameters.Add("#Surname", SqlDbType.NVarChar).Value = surnameV;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = emailV;
cmd.Parameters.Add("#EstablishmentType", SqlDbType.NVarChar).Value = eType;
cmd.Parameters.Add("#Interests", SqlDbType.NVarChar).Value = ins;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
How do I check if an email being entered in the "txtEmail" text box already exists in my database, in the email column and then alert message saying email already exists so it doesn't get inserted into my database?
Call this method in required textbox or area
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
Try this
cmd.CommandText = "IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email = '"
+ txtEmail.Text + "')
BEGIN
INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (#Title,#FirstName,#Surname,#Email,#EstablishmentType,#Interests)
END";
Call a stored Procedure and inside the stored procedure you can check
before insert
IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email =#email)
Begin
insert query here
end
In another way you can check it in text changed event also
Create a procedure on SQL server and check whether the name exists or not
CREATE PROCEDURE Procedure_Name
#mystring varchar(100),
#isExist bit out
AS
BEGIN
if exists(select column1 from tblTable1 where column1=#mystring)
begin
select #isExist=1
end
else
begin
select #isExist=0
end
END
GO
This is a sample procedure. If #isExist=1 that means the value exist.otherwise not. create a method to call this procedure and go on...
Happy Coding
This works for me:
Create a function Called CheckMail(string email)
public bool CheckMail(string email)
{
SqlConnection con = new SqlConnection("Data Source=*******; Initial Catalog=Your Database Name; Persist Security Info=True;User ID=****; Password=******");
SqlCommand cmd = new SqlCommand("select email from Table Name where email='"+email+ "'",con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
return false;
}
else
{
return true;
}
}
Then Implement in Button Click as
Pass Textbox value in function that were created..
if (CheckMail(EmailTxt.Text))
{
Write Your insert code to database
}
else
{
Error Message or Alert to Show Already Exists in database
}