How can I retrieve data from mysql database - c#

This code is from our user login profile for our SAD project. The account I register for user log in is working since it saved in the database but I can't log in because it says invalid.
private void btn_login_Click(object sender, EventArgs e)
{
conn = new MySqlConnection(myconn);
string query = "select * from southpoint_school.user where userUsername='" + textBox1.Text + "' and userPassword='" + textBox2.Text + "'";
conn.Open();
cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count++;
}
if (count == 1)
{
conn = new MySqlConnection(myconn);
string problem = "SELECT userAccountType from southpoint_school.user WHERE userUsername ='" + textBox1.Text + "'";
conn.Open();
cmd = new MySqlCommand(problem, conn);
string answer = cmd.ExecuteScalar().ToString();
conn.Close();
MessageBox.Show("Login successful!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (answer == "Administrator")
{
memorable = "Administrator";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
else
{
memorable = "Limited";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
}
else if (textBox1.Text == "" && textBox2.Text == "")
{
MessageBox.Show("No Username and/or Password Found!");
}
else
{
MessageBox.Show("Invalid Username And/Or Password!");
}
conn.Close();
}

The case
Invalid Username And/Or Password!
can only happen when you have 0 ore more than 1 search results in your southpoint_school.user database with your entered username + password. So I would inspect the data in your database.
Additionally I would
use parameters instead of string-concatenation for creating sql statements to avoid injection
save (salted)hashed passwords instead of plaintext in your database
use using statements for more effecient ressurce useage
query the user-table only once and use the result twice
e.g.:
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("No Username and/or Password Found!");
}
else
{
DataTable dtResult = new DataTable();
string Command = "select * from southpoint_school.user where userUsername=#un and userPassword=#up";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#un", textBox1.Text));
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#up", textBox2.Text));
myDataAdapter.Fill(dtResult);
}
}
if (dtResult.Rows.Count == 1)
{
MessageBox.Show("Login successful!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
if ((string)dtResult.Rows[0]["userAccountType"] == "Administrator")
{
memorable = "Administrator";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
else
{
memorable = "Limited";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
}
else if (dtResult.Rows.Count == 0)
{
MessageBox.Show("Invalid Username And/Or Password!");
}
else //TODO: treat the case for multiple results
{
}
}

Related

Change Password issues in ASP.Net

Hi i'm trying to changing the password so the user's password is update on the database. For example, i want the user Mary Tan's password to be changed from 12345 to 54321. But if affect the rest of the user's password. I really idk how to fix it.
Output:
click here
Table
database table
My Code:
protected void btnChangePassword_Click(object sender, EventArgs e)
{
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd";
if (Session["Username"] != null)
{
sql += " WHERE UserName='" + Session["Username"].ToString() + "'";
}
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
conn.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if(rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch(Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
Which means your Session["Username"] is null at this moment of execution. Hence the Where condition will skip and update all rows. And What is the Function of Reader There? It is not necessary, The ExecuteNonQuery is enough to do this Job and it will returns the number of rows affected. So you can do this in the following way:
string connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
if (Session["Username"] != null)
{
string sql = "UPDATE Staff Set Password=#NewPwd WHERE UserName=#Username";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#Username", Session["Username"]);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
}
}
else
{
// Show message that Session is Empty Can't Proceed
}
Important Note :- Don't save password as plain Text, Hash and salt them
Change your method like this (check Session in the start)
protected void btnChangePassword_Click(object sender, EventArgs e)
{
if (Session["Username"] == null)
{
//User is not logged-in. Display message or handle
return;
}
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd Where UserName = #UserName";
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#UserName", Session["Username"].ToString());
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}

Else doesn't work in reader using c#

When I enter user name and password, it logs in successfully and also opens desired field but when I enter wrong name or password (not saved in DB) it shows nothing actually it should encounter "else" this is the code
private void signin_button_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:/Student_Managment_System/SMS1.mdb";
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
string usrname = name_textBox.Text;
string passwd = pass_textBox.Text;
OleDbCommand cmd1 = new OleDbCommand("select * from Manager where Name='" + usrname + "' and Passwd='" + passwd + "'");
OleDbDataReader Reader = cmd1.ExecuteReader();
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
else
{
MessageBox.Show("Inviled User name or password");
}
}
myConnection.Close();
}
Your else statement isn't executed because there are no values to read when an invalid username or password is entered. You need to check if your reader has any rows. See here
Code
//Are there any rows
if(Reader.HasRows)
{
//If so read them
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
}
}
else
{
MessageBox.Show("Inviled User name or password");
}

how to add restrictions in login form?

i'm creating a login form for my system and want to add a User and Admin account. what i did in my database is to create a table for my users with a specific user type U_Type would be either 1 = admin or 2 = user.
i want to add an if statement that would call my column name U_Type and compare it either 1 or 2. below is my unfinished code. i'm using visual studio 2008 c# and ms sql 2005
here is my code:
float Outcome;
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
conn.Open();
String txtUser = textBox1.Text;
String txtPass = textBox2.Text;
string query = "SELECT * FROM tblUsers WHERE U_Name=#U_Name AND U_Pass=#U_Pass AND U_Type=#type";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(new SqlParameter("#U_Name", txtUser));
cmd.Parameters.Add(new SqlParameter("#U_Pass", txtPass));
cmd.Parameters.Add(new SqlParameter("#type", type));
SqlDataReader dr = cmd.ExecuteReader();
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
else if (textBox2.Text.Trim().Length == 0)
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
else if (dr.HasRows == true)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
if ()
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
}
i want the if statement to be here
else if (dr.HasRows == true)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
if ("#type"==1)
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
i really don't know the proper syntax for it. help me please i would really appreciate it. thank you
You have, roughly, the right idea, but your implementation is off.
You're validating the text boxes after you send the SQL query but before you check the results, and you're also passing in the type of the user.
The user type should be stored in the database along with the user, and you can return the type of user for the matching row (based on username and password). And your syntax is way off in some places.
A simplified approach based on what you appear to be doing would be something like this:
Do validation on the text boxes before executing the command. If validation passes, then select the row that matches the user name and password, and process the results accordingly:
private void button1_Click(object sender, EventArgs e)
{
bool validInput = false;
if (!String.IsNullOrWhitespace(textBox1.Text))
{
validInput = true;
}
else
{
MessageBox.Show("Please enter a user name.");
}
if (!String.IsNullOrWhitespace(textBox2.Text))
{
validInput = true;
}
else
{
MessageBox.Show("Please enter a password.");
}
if (validInput)
{
using (SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True"))
{
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE U_Name = #U_Name AND U_Pass = #U_Pass", conn);
command.Parameters.Add("#U_Name", SqlDbType.VarChar).Value = textBox1.Text;
command.Parameters.Add("#U_Pass", SqlDbType.VarChar).Value = textBox2.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
string userType = reader["U_type"].ToString();
if (userType == "1")
{
// Handle regular users
}
else if (userType == "2")
{
// Handle admin users
}
}
else
{
MessageBox.Show("Login failed.");
}
}
}
}
}
The above code illustrates the approach. If both text boxes have text in them, the validInput flag is set to true. The connection is then opened, the command and parameters are set, the command is executed and a reader returned. If the reader has rows (meaning 1 or more records that matched the username and password are found), the reader is advanced to the first record (there should be only one match for a given username/password combination).
The "U_type" column is interrogated to see if it's a regular user or an admin user, and the user is processed accordingly.
It's not clear from your posted code whether "U_type" is a string or an integer; if it's an integer you'll need to convert it like this:
int userType = Convert.ToInt32(reader["U_type"]);
And change the corresponding if checks:
if (userType == 1)
and
if (userType == 2)
If you want to authenticate user and compare the Type then return DataTable.
public DataTable ValidateUser(string username,string password)
{
DataTable dt = new DataTable();
SqlCommand cmd; SqlDataReader dr;
SqlConnection con = new SqlConnection(yourConnectionString);
try
{
cmd = new SqlCommand();
cmd.CommandText = "Select * from tblUsers where U_Name=#U_Name and U_Pass=#U_Pass";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#U_Name", username);
cmd.Parameters.AddWithValue("#U_Pass", password);
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
dr = cmd.ExecuteReader();
dt.Load(dr);
}
catch (Exception ex)
{
dt = null;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close(); con.Dispose();
}
}
return dt;
}
Calling ValidateUser Method:
DataTable dt=new DataTable();
dt=ValidateUser();
if(dt!=null && dt.Rows.Count>0)
{
if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==1)
{
//show form for user where utpe=1
}
else if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==2)
{
//show form for user where utype=1
}
else
{
//otherstuff
}
}
else
{
//invwalid user
}
hopethis helps

Different form opens when you login as admin c# mysql

So i've made a login form in c# working with MySql and i want to make it so when administrator login a different form pops up i've made on the mysql in the users database a column named permissions so if a user will have permission Admin i want a different form to open for him and not the same as for normal users but i don't really know how to do that
the code:
private void btn_Prijava_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from login.users where upIme='" + this.tB_upIme.Text + "' AND geslo='" + this.tB_geslo.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Uspešno ste se prijavili!");
this.Hide();
Form3 f3 = new Form3();
f3.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Dvojno uporabniško ime in geslo!");
this.Hide();
}
else
MessageBox.Show("Uporabniško ime ali geslo ni pravilno!");
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
if you have permissions column and have value Admin for admin users you can try thebelow code.
bool IsAdminUser=false;
while (myReader.Read())
{
count = count + 1;
IsAdminUser = myReader["permissions"].ToString().Equals("Admin");
}
if (count == 1 && IsAdminUser==true)
{
MessageBox.Show("User is Admin!");
this.Hide();
AdminForm adminForm = new AdminForm ();
adminForm.ShowDialog();
}
else if (count == 1)
{
MessageBox.Show("Uspešno ste se prijavili!");
this.Hide();
Form3 f3 = new Form3();
f3.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Dvojno uporabniško ime in geslo!");
this.Hide();
}
private void cmdEnter_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource=localhost;port=3306;username=root;password=1234";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from boardinghousedb.employee_table where username='" + this.txtUsername.Text + "' AND password='" + this.txtPassword.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
bool IsAdminUser = false;
while (myReader.Read())
{
count = count + 1;
IsAdminUser = myReader["username"].ToString().Equals("admin");
}
if (count == 1 && IsAdminUser == true)
{
MessageBox.Show("User is Admin!");
this.Hide();
AdminForm adminForm = new AdminForm();
adminForm.ShowDialog();
}
else if (count == 1)
{
this.Hide();
Menu f3 = new Menu();
f3.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and Password . . . Access Denied", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Username and Password is Not Correct . . . Please try again", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
myConn.Close();
}
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

using IF condition inside a while loop in C#

I have a problem with my C# code. I have created a login form in C# 2010. When I am validating the user name, I used an if-condition inside the while loop but the thing is that even when the username and password are correct, it executes the else-statement. Please help me to solve this.
Here is my code :
private void btnlogin_Click(object sender, EventArgs e) {
string connection=
#"Data Source=.\SQLEXPRESS;"
+" AttachDbFilename=|DataDirectory|ResturantDB.mdf;"
+" Integrated Security=True; User Instance=True";
SqlConnection cn=new SqlConnection(connection);
try {
cn.Open();
}
catch(Exception) {
// print the exception's message?
MessageBox.Show("Connection to Database failed; check Connection!");
}
SqlCommand cmd=new SqlCommand("SELECT * FROM [Login]", cn);
cmd.Connection=cn;
SqlDataReader reader=null;
reader=cmd.ExecuteReader();
while(reader.Read()) {
if(
txtuser.Text==(reader["Username"].ToString())
&&
txtpass.Text==(reader["Password"].ToString())
) {
//MessageBox.Show( "logged in!" );
Home newhome=new Home();
newhome.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect credentials!");
}
}
}
you should use a break, when a username is found in your if condition like
bool found = false;
while (reader.Read())
{
if (txtuser.Text == (reader["Username"].ToString()) && txtpass.Text == (reader["Password"].ToString()))
{
//MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
found = true;
break;
}
}
if (!found)
MessageBox.Show("Incorrect credentian..!");
you get into the else block because if any login is not correct, the messagebox appears and that is in n-1 cases in your code.
You're checking if all users have the same user name and password. You need to refine your SQL to select only that one user. Also, please read into password hashing for the sake of your users.
Because its in a loop.
create a bool variable. update its value in loop (if found same username and password) and check outside based on its value.
Do this
bool found;
while (reader.Read())
{
if (txtuser.Text == (reader["Username"].ToString()) &&
txtpass.Text == (reader["Password"].ToString()))
{
found = true;
break;
}
}
if (found)
{
MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
}
else
{
MessageBox.Show("Incorrect credentian..!");
}
I will solve it on this way:
private void btnlogin_Click(object sender, EventArgs e)
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ResturantDB.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
try
{
cn.Open();
}
catch (Exception)
{
MessageBox.Show("Conncetion to Database faild check Connection !");
}
while (true)
{
SqlCommand cmd = new SqlCommand("SELECT [Password] FROM [Login] WHERE [Username] = '" + txtuser.Text + "'", cn);
cmd.Connection = cn;
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
if (!reader.HasRows)
MessageBox.Show("User does not exist. Please, try again.");
else
{
//username should be unique, so only one row is possible to have
reader.Read();
if (txtpass.Text == (reader["Password"].ToString()))
{
//MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
return;
}
else
MessageBox.Show("Incorrect credentian..! Try again.");
}
}
}
Simplest and Secure method
SqlCommand cmd = new SqlCommand("Select uname, pswd from [Login] where uname =#uname and pswd =#ps", conn);
cmd.Parameters.Add(new SqlParameter("#uname", "username here"));
cmd.Parameters.Add(new SqlParameter("#ps", "pasword here"));
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
//MessageBox.Show( "logged in!" );
Home newhome = new Home();
newhome.Show();
this.Hide();
}
else
{
MessageBox.Show( "Incorrect credentials!" );
}
No need to loop thru the records for your case
use this query, compate username and password in the query:
"SELECT * FROM [Login] where Username='" + txtuser.Text "' and password = '" + txtpass.Text + "'"

Categories