textBox3 specific key to make accounts - c#

I am coding an Application with my friend and I am having some trouble figuring out how to make the 3rd textbox contain a certain word/key to continue in order to make the account
Here is what the form looks like
Then here is the entire code for the database part of where it creates the account.
private void button5_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Equals("") && !textBox2.Text.Equals("") && textBox2.Text.Equals(textBox3.Text))
{
StringBuilder sb = new StringBuilder();
using (SHA256 hash = SHA256Managed.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(textBox2.Text));
foreach (Byte b in result)
{
sb.Append(b.ToString("x2"));
}
}
string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=majorpayne;";
string query = "INSERT INTO staff(USERNAME, PASSWORD) VALUES('" + textBox1.Text + "', '" + sb.ToString() + "')";
string query2 = "SELECT * FROM staff WHERE username='" + textBox1.Text + "' AND password='" + sb.ToString() + "'";
MySqlConnection con = new MySqlConnection(connectionString);
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand insertCommand = new MySqlCommand(query, databaseConnection);
MySqlCommand checkCommand = new MySqlCommand(query2, databaseConnection);
MySqlDataReader reader;
try
{
databaseConnection.Open();
reader = insertCommand.ExecuteReader();
reader.Close();
reader = checkCommand.ExecuteReader();
if (reader.HasRows)
{
MessageBox.Show("Successfully Created Account.");
{
Login main = new Login();
main.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Database Error (404)");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
If anyone can help make a way where the textBox3 equals a specific word thanks in advance.
And for a short explanation, I want the textBox3 to have a "key" in it that checks if the key is the exact key and if the correct key is there, it goes on and creates the account with the user/pass that was entered.

you can add label Under textBox3 Then on textBox3_KeyUp Event Write your Code Like This
private void textBox3_KeyUp(object sender, KeyEventArgs e)
{
if (textBox1.Text == "Your Key")
{
label1.Text = "correct key";
label1.ForeColor = System.Drawing.Color.Green;
}
else
{
label1.Text = "wrong key";
label1.ForeColor = System.Drawing.Color.Red;
}
}

Related

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

C# Syntax Error in INSERT INTO statement C#

if (txtUsername.Text != "")
{
string q = "insert into info(Username) values ('" + txtUsername.Text.ToString() + "')";
dosomething(q);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
if (txtPassword.Text != "")
{
string a = "insert into info(Password) values ('" + txtPassword.Text.ToString() + "')";
dosomething(a);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Every time I run this it always show that error. I dont know how to fix it.
The code should record the data i put in a textbox to ms access database. plz helpp
Presumably, you've initialized cn somewhere by doing something like
cn = new SqlConnection();
You need to pass the connection string for the database to the constructor:
cn = new SqlConnection("your connection string here");
or set it sometime later, before you connect:
cn.ConnectionString = "your connection string here";

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

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 + "'"

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