I am trying to validate user data and when it is correct navigate to another xaml page. what I have, it and show the MainPage which is the Login window but when I enter data and click the button it closes the window, it's not checking the user input.
Here is what I have:
private void Login_Click(object sender, RoutedEventArgs e)
{
Connection.Open();
// sda = new MySqlDataAdapter("select count(*) from customers where Name = '" + loginName.Text + "' and Password = " + password.Password +"", Connection);
string query = "SELECT * FROM customers WHERE Name = '" + loginName.Text + "' and Password = '" + password.Password + "'";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
MySqlDataAdapter sda = new MySqlDataAdapter(query, Connection);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Frame.Navigate(typeof(BlankPage1));
/* BlankPage1 main = new BlankPage1();
main.Show();
this.Hide();
Connection.Close(); */
}
else
{
message.Text = "Wrong Name or Password! Please, try again!";
/* var messageDialog = new MessageDialog("Wrong Name or Password");
await messageDialog.ShowAsync(); */
}
Connection.Close();
}
The commented statements are different things that I was trying.
Please, I need help to find out the problem, I will really appreciate any help.
Thank you in advance!
Good day
I am working on login page where the user will be able to login if a value is shown in the database table and if it is not shown it will displays for him a change password page.
What I want is, how can I write an if statement to retrieve username and password if that value is exiting or not ?
what I have tried is the following
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = ("select count (*) from log_sup where ENTITY_DIVISION_CODE = '" + textBox1.Text + "'and DX_NUMBER = '" + textBox2.Text + "'" );
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.ExecuteNonQuery();
if (dt.Rows[0][0].ToString() == "1" )
{
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
else
{
MessageBox.Show("THE USERNAME OR PASSWORD IS INVALID. THIS IS YOUR " , MessageBoxButtons.OK);
Form3 F3 = new Form3();
F3.Show();
this.Hide();
}
con.Close();
COUNT() is a scalar function so use cmd.ExecuteScalar(); to get result as an Object. No need to take DataTable and do other complex things.
Following is simple solution. Kindly modify accordingly as its just a help how to use ExecuteScalar.
int result = Convert.ToInt32(cmd.ExecuteScalar());
if(result > 0)
{
//SUCCESS
}
else
{
//FAIL
}
Currently, I have a name and password column in my table. However, I want to add a "UserRights" column, with admin and user rights. If an admin logs in, he should see a different form compared to the user.
Currently, I have an if statement to check if the login details are right. If yes, it goes to a home winform. Else, there is an error message to check details. However, if I had this new column, there would be two checks one for details and one for user rights and then the error if details do not match, how could this be done?
private void check_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(#"");
string query = "select * from dbo.users where name= '" + name.Text+ "' and password = '" + dbo.users where pword= '" + pword.Text+ "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
...
}
Add your userrights column to your select query and then add an additional check for their privileges.
It should look similar to this
SqlConnection sqlcon = new SqlConnection(#"");
string query = "select * from dbo.users where name= '" + name.Text+ "' and password = '" + dbo.users where pword= '" + pword.Text+ "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
string userRights = dtbl.Rows[0]["userrights"].ToType<string>();
switch (userRights)
{
case "admin":
*do something*
break;
case "user":
*do something else*
break;
}
}
I'm creating a simple web service to authenticate a user.
I have a problem filling the datatable(used to store the results of a select statement) properly, 'dt.rows.count' (dt is the name of the datatable) always returns 0 even if the select statement returns nothing. I've tried clearing the datatable before filling it, and after the if condition as well, but to no avail, I get the same result.
Would really appreciate any advice on how to proceed.
[WebMethod]
public string Authen(string a, string b)
{
var con = new SqlConnection("Data Source=SERVER-SQL;Initial Catalog=DECA-DB;Persist Security Info=True;User ID=sa;Password=*****");
var sda = new SqlDataAdapter("SELECT * FROM Login_Matrix WHERE Username = ' " + a + " ' AND Password = ' " + b + " '", con);
var dt = new DataTable();
con.Open();
dt.Clear();
sda.Fill(dt);
con.Close();
int x = dt.Rows.Count;
//return (x);
if ( x >0)
{
dt.Clear();
return ("In");
}
else
{
dt.Clear();
return ("out");
}
}
}
Adding a space after and before the single quotes makes your query search for inexistant user names and passords (like " Steve ") and it return no records
A quick fix could be
var sda = new SqlDataAdapter(#"SELECT * FROM Login_Matrix
WHERE Username = '" + a + "'
AND Password = '" + b + "'", con);
but this is very dangerous.
This code is vulnerable to Sql Injection attacks.
You should use parameters
var sda = new SqlDataAdapter(#"SELECT * FROM Login_Matrix
WHERE Username = #uname
AND Password = #pwd", con);
sda.SelectCommand.Parameters.Add("#uname", SqlDbType.NVarChar).Value = a;
sda.SelectCommand.Parameters.Add("#pwd", SqlDbType.NVarChar).Value = b;
And on the same line about security, another thing to consider as soon as possible, is that storing plain text password in your database is a really big security risk. You should search how to salt and store an hash of the password
There are other parts of this code to improve.
First you need to have using statements around the disposable objects
like the connection or the command.
Second, there is no need to have a full SqlDataAdapter and a
DataTable to just check if the user exists or not.
So you can rewrite your code as:
string cmdText = #"IF EXISTS(SELECT 1 FROM Login_Matrix
WHERE Username = #uname AND Password = #pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection con = new SqlConnection("....."))
using(SqlCommand cmd = new SqlCommand(cmdText, con))
{
con.Open();
int result = (int)cmd.ExecuteScalar();
return ( result == 1 ? "In" : "out");
}
I'm trying to implement a password change feature but it doesn't seem to want to work.
private void button3_Click(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb"))
{
DataTable dt = new DataTable();
con.Open();
errorProvider1.Clear();
if (dt.Rows[0][0].ToString() == "1")
{
if (textBox3.Text == textBox4.Text)
{
OleDbDataAdapter da = new OleDbDataAdapter(" COUNT (*) FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ", con);
OleDbCommand com = new OleDbCommand("UPDATE login SET [password] = '" + textBox3.Text + "' WHERE username = '" + textBox2.Text + "'", con);
com.ExecuteNonQuery();
MessageBox.Show("password successfully changed", "success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
errorProvider1.SetError(textBox3, "passwords dont match");
errorProvider1.SetError(textBox4, "passwords dont match");
}
}
else
{
errorProvider1.SetError(textBox1, "wrong username");
errorProvider1.SetError(textBox2, "wrong pasword");
}
}
}
there is an error in the line if (dt.Rows[0][0].ToString() == "1") where it states that no data was found at that position, yet there are 5 rows in the data table.
when the code is run without the above line, as in //if (dt.Rows[0][0].ToString() == "1")
the code runs but no data is being updated in the table.
updated code again and still recived the same error:
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Open();
errorProvider1.Clear();
if (dt.Rows[0][0].ToString() == "1")
Try filling your DataTable as following -
string cmdString = "SELECT * FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ";
OleDbCommand cmd = new OleDbCommand(cmdString,con);
con.Open();
var dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
con.Close()
Now you should get your data in table, provided that your select query is correct. Make sure you use using blocks on connection and command objects to dispose these when they are out of scope.
you are just declaring data table,not assigning any data
DataTable dt = new DataTable();
thats why when you try to get dt.Rows[0][0].ToString() it gives error
As you can try this:
OleDbDataAdapter custDA = new OleDbDataAdapter();
DataSet custDS = new DataSet();
DataTable custTable = new DataTable("Customers");
custTable.Columns.Add("CustomerID", typeof(String));
custTable.Columns.Add("CompanyName", typeof(String));
custDS.Tables.Add(custTable);
//Use ADO objects from ADO library (msado15.dll) imported
// as.NET library ADODB.dll using TlbImp.exe
ADODB.Connection adoConn = new ADODB.Connection();
ADODB.Recordset adoRS = new ADODB.Recordset();
adoConn.Open("Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;", "", "", -1);
adoRS.Open("SELECT CustomerID, CompanyName FROM Customers", adoConn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
custDA.Fill(custTable, adoRS);
adoRS.Close();
adoConn.Close();
You can follow this reference
As noted by another, you never assign a value to the data table, that is why it is choking. Your query itself, by string concatenation will open you to SQL-Injection. Parameterize it. Finally, for your query, I would query all records for a given user ID, but get the user and password values based on only qualifying the user ID, not the password. This way, if you have more than 1 row returned, it will indicate duplicate user accounts and should get special attention. If it returns NO rows, then no such user. If it returns ONE row, then you can compare to the password entered and if matched, you have your correct user ID to run with.
starting with your
using( OleDbConnection con = ...)
{
// create command first.. Parameterize it. In this case "#" is parameter indicator
// for Access. parmUserName is the parameter name to be applied. I explicitly added
// "parm" in front to ensure differentiation between the parameter and actual column.
var cmd = new OleDbCommand(
#"select password from login where username = #parmUserName", con);
// Now, add the parameter of proper data type. The name of the parameter and it's value
cmd.Parameters.AddWithValue("parmUserName", textBox1.Text);
// create your data adapter now based on the command above
var da = new OleDbDataAdapter(cmd);
// NOW, create your data table object and have data adapter query and fill with rows.
var dt = new DataTable();
da.Fill(dt);
// NOW, check results.
if (dt.Rows.Count == 0)
MessageBox.Show("No such user account");
else if( dt.Rows.Count > 1)
MessageBox.Show("Duplicate user account");
else
{
// valid single record. Do the passwords match?
if (textBox3.Text.Equals(dt.Rows[0]["password"].ToString()))
{
MessageBox.Show("Valid login, allow to continue");
// Now, since it appears you are trying to UPDATE the password for the user,
// build new UPDATE command and parameterize it in a similar fashion
var cmdUpd = new OleDbCommand(
#"update login set password = #parmNewPwd where username = #parmUserName", con);
// Now, add the parameter of proper data type. The name of the parameter and it's value
cmd.Parameters.AddWithValue("parmNewPwd", textBox3.Text);
cmd.Parameters.AddWithValue("parmUserName", textBox1.Text);
if (cmd.ExecuteNonQuery() == 1)
MessageBox.Show("Password updated");
else
MessageBox.Show("Failed updating password");
}
else
MessageBox.Show("Invalid password");
}
}
FINAL NOTE. You should also look into cleaning data especially before building SQL commands. Never concatenate strings where users can manually enter data for SQL-Injection, parameterize them.