form validation using c# and sql commands - c#

i am trying to make a windows form to log into another one,
i am using a database with users and passwords
the code is as follows:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXX.XX.XX;Initial Catalog=mmtXX-XXX;User ID=mmtXX-XXX;Password=mmtXX-XXX");
conn.Open();
SqlCommand mycommand = new SqlCommand("SELECT User, Password FROM UsersData WHERE User = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", conn);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader != null)
{
if(reader.Read())
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
else
{
label3.Text = "Invalid Username or Password !";
}
the problem that a getting is that no matter what i insert into the textboxes, right or wrong i am getting:
Invalid Username or Password !
is there anyway to fix my code?
regards;

I would do it this way, keeping to the method you are using:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conn_str);
conn.Open();
string sql = "SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password"
SqlCommand mycommand = new SqlCommand(sql, conn);
//parameterize your query!
mycommand.Parameters.AddWithValue("user", txtuser.text);
mycommand.Parameters.AddWithValuye("password", txtpassword.password);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader == null)
{
label3.Text = "Database query failed!";
}
else if(reader.HasRows)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}

Use parameterized queries as they will help you against sql injection as mentioned by SLaks.
Change your code to below
using (SqlCommand command = new SqlCommand("SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("user ", textbox1.text));
command.Parameters.Add(new SqlParameter("password", textbox2.text));
SqlDataReader reader = command.ExecuteReader();
if (reader == null)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}

Related

How can I update password using C#?

I can't find my problem. Can anyone help me to check it. I'm new in C#.
public void Btnchange_Click(object sender, EventArgs args)
MySqlConnection con = new MySqlConnection("server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234");
MySqlDataAdapter sda = new MySqlDataAdapter("select Password from user.register where Password='" + textoldpassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
if (textnewpassword.Text == textconfirmpassword.Text)
{
con.Open();
MySqlCommand cmd = new MySqlCommand("update user.register set Password ='" + textconfirmpassword.Text + "' where Password ='" + textoldpassword.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
lblmsg.Text = "Succesfully Updated";
lblmsg.ForeColor = Color.Green;
}
else
{
lblmsg.Text = "New password and confirm password should be same!";
}
I expect it can update and change my password.
There are many many (mostly) minor mistakes in your code:
use some kind of Id fields in your sql tables
never do an update like you did (update the field WHERE this field is equals to...)
create your own class and bind the query result to this class
when a class implements IDisposable interface, always use the keyword 'using'
never ever user string concatenation in sql queries!!! SQL INJECTION!!! always use parametrized sql queries
Here's a simple example for your form. Let's suppose your
user.register table has the following columns:
- Id
- Username
- Password
Now let's create your own class (maybe right under your button click
event, so it can be private this time):
private class MyUser
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Then your button click event should look like this:
private void Btnchange_Click(object sender, EventArgs e) {
if (!textnewpassword.Text.Trim().Equals(textconfirmpassword.Text.Trim()))
{
throw new ArgumentException("New password and confirm password should be same!");
}
List<MyUser> myUsers = new List<MyUser>();
using (MySqlConnection con =
new MySqlConnection(
"server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234"))
{
using (MySqlCommand cmd = new MySqlCommand("select * from user.register where Username=#user and Password=#pass", con))
{
cmd.Parameters.AddWithValue("#user", textusername.Text.Trim());
cmd.Parameters.AddWithValue("#pass", textoldpassword.Text.Trim());
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
myUsers.Add(new MyUser
{
Id = (int)dr["Id"],
Username = dr["Username"].ToString(),
Password = dr["Password"].ToString()
});
}
}
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
if (!myUsers.Any())
{
throw new ArgumentException("No users found with the given username/password pair!");
}
if (myUsers.Count != 1)
{
throw new ArgumentException("More than 1 user has the same username and password in the database!");
}
MyUser user = myUsers.First();
user.Password = textnewpassword.Text.Trim();
using (MySqlCommand cmd = new MySqlCommand("update user.register set Password=#pass where Id=#id"))
{
cmd.Parameters.AddWithValue("#pass", user.Password);
cmd.Parameters.AddWithValue("#id", user.Id);
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
cmd.ExecuteNonQuery();
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
} }
...and so on.

How can I make my Login Form Object-Oriented

My problem is I don't know how to call the textboxes and buttons to my class from my form login. So I decided to put my codes inside my btnLogin events. How can I make my codes oop style?
private void btnLogin_Click(object sender, EventArgs e)
{
int count = 0;
Connection connection = new Connection();
string sql = "SELECT * FROM tbl_Account WHERE Username='" + txtUserName.Text + "' and Password='" + txtPassword.Text + "'";
MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand(sql, conn);
conn.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
count++;
}
if (count == 1)
{
MessageBox.Show("Login Successfully!");
this.Hide();
main.showMeForm4(this);
}
else
{
txtPassword.Focus();
MessageBox.Show("Username or Password Is Incorrect");
txtUserName.Text = "";
txtPassword.Text = "";
}
conn.Close();
}
Put your business logic to a separate class:
Do not concat SQL query (SQL Injections).
BusinessLogic class
public bool Authorize(string userName, string userPassword)
{
Connection connection = new Connection();
string sql = "SELECT Count(*) FROM tbl_Account WHERE Username=#userName and Password=#userPassword";
MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#userName",userName);
cmd.Parameters.AddWithValue("#userPassword",userPassword);
int count = 0;
try
{
conn.Open();
int count = int.TryParse(cmd.ExecuteScalar().ToString());
}
finally
{
con.Close();
}
return count==1;
}
Call it:
BusinessLogic businessLogic = new BusinessLogic();
private void btnLogin_Click(object sender, EventArgs e)
{
if (businessLogic.Authorize(txtUserName.Text, txtPassword.Text)
{
MessageBox.Show("Login Successfully!");
this.Hide();
main.showMeForm4(this);
}
else
{
txtPassword.Focus();
MessageBox.Show("Username or Password Is Incorrect");
txtUserName.Text = "";
txtPassword.Text = "";
}
}

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

create a login page in vb.net by c# & mysql but it shows error message connection must be valid and open

private void admin_submit_button_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource= localhost;port=3306;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("select * from mws.login_info where login_id='" + this.admin_id_textbox + "'and login_password1='" + this.admin_password_textbox1 + "' and login_password2='" + this.admin_password_textbox2 + "'");
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("username and password is correct");
}
else
MessageBox.Show("username and password not correct");
myConn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
You have not associated the command with the connection. You code lacks of the following line
SelectCommand.Connection = myConn ;
Said that, imagine that I write in your admin_id_textbox the following text
' OR login_id like '%' --
what happen to your checks for the correct login?
It is called Sql Injection and it is a very dangerous situation for every kind of database access.
Use always a parameterized query to build sql commands, in particular when part of your command is built using user input text
private void admin_submit_button_Click(object sender, EventArgs e)
{
try
{
string cmdText = #"select * from mws.login_info
where login_id=#id and login_password1=#pwd
and login_password2=#pwd2";
string myConnection = "datasource= localhost;port=3306;username=root;password=root";
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand SelectCommand = new MySqlCommand(cmdText, myConnection))
{
myConn.Open();
SelectCommand.Parameters.AddWithValue("#id", this.admin_id_textbox);
SelectCommand.Parameters.AddWithValue("#pwd",this.admin_password_textbox1);
SelectCommand.Parameters.AddWithValue("#pwd2",this.admin_password_textbox2);
using(MySqlDataReader myReader = SelectCommand.ExecuteReader())
{
if(myReader.HasRows)
MessageBox.Show("username and password is correct");
else
MessageBox.Show("username and password not correct");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

C# Login screen using sql database not working

I have a simple login screen which, upon user clicking login button, should run the sql query to search for rows where the username == username text box, and password == password text box. This section of my code works fine.
However when I try to run an if statement, which will open a new form and close the login form, it errors, even though I have added some message boxes to check that the statement sting comparison is correct.
Any ideas?
Login Button:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DebenhamsProjectOfficeDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = txtUsername.Text;
string passText = txtPassword.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM Users WHERE Username='" + userText + "' and Password='" + passText + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
MessageBox.Show(userText + " / " + dr["Username"].ToString());
MessageBox.Show(passText + " / " + dr["Password"].ToString());
if (dr["Username"].ToString() == userText && dr["Password"].ToString() == passText)
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
dr.Close();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Login attempt:
With the advice taken from the Answers and Comments below the code has been corrected to the following (using sql parameters in the sql command):
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DebenhamsProjectOfficeDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = txtUsername.Text;
string passText = txtPassword.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM Users WHERE Username = #username and Password = #password", cn);
cmd.Parameters.Add(new SqlParameter("username", userText));
cmd.Parameters.Add(new SqlParameter("password", passText));
SqlDataReader dr = cmd.ExecuteReader();
try
{
dr.Read();
if (dr["Username"].ToString().Trim() == userText && dr["Password"].ToString().Trim() == passText)
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
}
catch
{
MessageBox.Show("Invalid Username or Password");
}
dr.Close();
cn.Close();
}
try adding a trim() on to the end of the sql return as you check them.
dr["Username"].ToString().trim() and dr["Password"].ToString().trim()
Sometimes the Database will store extra spaces you cant see.
Simply try this: I think it will work
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username='" + userText.toString() + "' and Password='" + passText.toString() + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show(username + " / " + usertext);
MessageBox.Show(password + " / " + passtext);
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Invalid Username or Password");
}

Categories