Good day
I am working on login page where the user will be able to login and then change password after first login.Then, the user will be able to login to the system with the new password.
I found out that ExecuteScalar will help me to make the codes working perfectly. But, I am facing now that ExecuteScalar is returning wrong values where the user will be able to change the password but it will not allow him to redirect to the main page.
I have tried to change in if statement but still it showing me wrong results
SqlConnection con = new SqlConnection(#"Data Source=TOWELL\XPEDEON;User ID=xplive;Password=xplive");
try {
con.Open();
if (attemp < 3)
{
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);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
Form3 F3 = new Form3();
F3.Show();
this.Hide();
}
else if(result == 0)
{
recby = textBox1.Text;
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
else
{
MessageBox.Show("WRONG PASSWORD, THIS IS YOUR " + attemp + " ATTEMPT ");
}
}
else if (attemp == 3)
{
MessageBox.Show("LOGIN EXCEED , PLEASE CONTACT THE ADMIN TO RESET YOUR ACCOUNT LOGIN");
textBox1.Enabled = false;
textBox2.Enabled = false;
label2.Enabled = false;
}
attemp++;
}
catch (Exception) {
}
con.Close();
the table query
where the user after changing the password, it will marks as 1 in order to check that the password has changed
I suggest changing the query:
Count(*) can be expensive (you may want to scan the entire table), when all you want is an answer for "if there any record such that..." - you can well stop early.
Let's parametrize the query (just imagine that I put "123'; delete from log_sup; --" into textBox1.Text)
Code:
...
cmd.CommandText =
#"select 1
from log_sup
where ENTITY_DIVISION_CODE = #prm_ENTITY_DIVISION_CODE
and DX_NUMBER = #prm_DX_NUMBER";
//TODO: cmd.Parameters.Add("param_name", RDMBS_TYPE) is a better choice
cmd.Parameters.AddWithValue("#prm_ENTITY_DIVISION_CODE", textBox1.Text);
cmd.Parameters.AddWithValue("#prm_DX_NUMBER", textBox2.Text);
using (var reader = cmd.ExecuteReader()) {
if (reader.Read()) { // We've succeeded in reading (at least) one record
Form3 F3 = new Form3();
F3.Show();
this.Hide();
}
else { // the cursor is empty
recby = textBox1.Text;
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
}
...
Related
I have searched everywhere and I really cannot explain it, I have made a project which starts with a login form at the size I have set, after I put login data and press the button next forms or even the login form shrinking in size as you can see from the image and I cannot understand if it is a bug or something else (I have tried everything about properties, autosize, windowstate etc but nothing).
private void btnLogIn_Click(object sender, EventArgs e)
{
mycon.Open();
//string cmdstr = "SELECT Password FROM admin WHERE ID ='" + textBox1.Text + "' ";
string cmdstr = "SELECT Password FROM admin WHERE ID =" + textBox1.Text;
cmd = new OleDbCommand(cmdstr, mycon);
dr = cmd.ExecuteReader();
string[] login = new string[3];
while (dr.Read())
{
login[1] = (dr["Password"].ToString());
}
dr.Close();
mycon.Close();
if (maskedTextBox1.Text == login[1])
{
MessageBox.Show("LOG-IN SUCCESSFUL!", "Confirmation Message");
Form control = new Form2();
control.Show();
this.Hide();
}
else
{
MessageBox.Show("LOG-IN FAILED!", "Confirmation Message");
}
}
}
}
I made a login page that checks the database for the username and password but it's just allowing any username and password it's not rejecting them not sure why I'm new to this, below is the form, I've entered data into the database with user_name and password so it's deffo not that must be something in the code but when I close out of the program it also says password incorrect which is strange it only shows that once I've actually clicked close on the program tho it's weird
namespace LoginApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
PassTextBox.PasswordChar = '•';
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string MyConnection = "datasource=localhost;port=3306;username=user;password=pass";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand("select * from etool.login where user_name='" + this.UserTextBox.Text + "' and password='" + this.PassTextBox.Text + "' ;", MyConn);
MySqlDataReader MyReader;
MyConn.Open();
MyReader = MyCommand.ExecuteReader();
int count = 0;
while (MyReader.Read())
{
Console.WriteLine(MyReader[count]);
count++;
}
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
if (count == 1)
{
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and passwor.\nAccess denied.");
}
else
{
MessageBox.Show("Username and password is incorrect.\nPleas try again.");
}
MyConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
First, you REALLY should use parameters instead of construct your command with the variables like you did.
Second, you shouldn't put here your user and pass for root.
Third, you will ALWAYS show the message "Username and password is correct", as nothing is preventing this from happening.
Actually, your code is like this:
while (MyReader.Read())
{
Console.WriteLine(MyReader[count]);
count++;
}
//This block of code will ALWAYS be executed,
//no matter the value of count.
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
//This IF block is doing nothing.
if (count == 1)
{
}
As you can see, the code that should be executed ONLY in case the counter had a value of 1 is executed no matter what.
You need to put the part of your code that must be executed only if count is equal to 1 INSIDE the IF that checks if count is equal to 1:
if (count == 1)
{
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
try
{
if (!(ComboBoxut.Text == string.Empty))
{
if (!(ComboBoxut.Text == string.Empty))
{
String str = "server=RAVI;database=sampledb;Integrated Security=SSPI";
String query = "select * from DentalLogin where usertype = '" + this.ComboBoxut.Text + "'and password = '" + this.TextBoxPwd.Text + "'";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dbr;
con.Open();
dbr = cmd.ExecuteReader();
while (dbr.Read())
{
string ut = dbr.GetString(0);
if (ut == "Doctor")
{
this.Visible = false;
DoctorHome Dochome = new DoctorHome();
Dochome.Show();
}
else if (ut == "Staff")
{
this.Visible = false;
StaffHome staffhome = new StaffHome();
staffhome.Show();
}
else
{
MessageBox.Show(" username and password incorrect", "login page");
}
}
}
Can you please tell me whats wrong with this code with a drop down button.
I have 2 user types in my form one is doctor another one is staff.
If the user selected doctor i want to show a doctorhome Form.
If the user selected staff i want to show a staffhome Form.
I got error username and pwd incorrect.
But in db everything is correct username & pwd.
Please help me out this problem.
Try This
dbr = cmd.ExecuteReader();
while(dbr.read())
{
string value = dbr["Column Index"].toString();
if(value == "Doctor" ){
this.Visible = false;
DoctorHome Dochome = new DoctorHome();
Dochome.Show();
}
}
So i have a login system and when the user logins a new form opens and i want the form to display the user Name. When user register he have to put his name and surname and that 2 things i want to be displayed in the new form that opens. So is there any easy way to put the logined user name into listbox?
so here is the registration code:
MySqlConnection dataConnection = new MySqlConnection();
dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
dataConnection.Open();
MySqlTransaction transakcija = dataConnection.BeginTransaction();
MySqlCommand dataCommand = new MySqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.Transaction = transakcija;
try
{
dataCommand.CommandText = "Insert INTO login.users (ime,upIme,geslo,dovoljenja) VALUES ('" + this.tB_Ime.Text + "','" + this.tB_upIme.Text + "','" + this.tB_geslo.Text + "', 'Navaden uporabnik')";
dataCommand.CommandType = CommandType.Text;
dataCommand.ExecuteNonQuery();
transakcija.Commit();
MessageBox.Show("Registracija uspešna!");
this.Hide();
}
catch (Exception eks)
{
transakcija.Rollback();
MessageBox.Show("Napaka pri registraciji\n" + eks.Message);
}
finally
{
dataCommand.Connection.Close();
}
Form1 f1 = new Form1();
f1.ShowDialog();
this.Close();
and login:
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;
bool IsAdminUser = false;
while (myReader.Read())
{
count = count + 1;
IsAdminUser = myReader["dovoljenja"].Equals("Admin");
}
if (count == 1 && IsAdminUser == true)
{
MessageBox.Show("Prijavljeni ste kot administrator!");
this.Hide();
Form4 f4 = new Form4();
f4.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();
}
else
MessageBox.Show("Uporabniško ime ali geslo ni pravilno!");
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
you can send the LoggedIn UserName to the UserForm constructor and from there you can add it to the required control.
Try This:
Login Form:
string LoggedInUserName = String.Empty;
while (myReader.Read())
{
count = count + 1;
IsAdminUser = myReader["dovoljenja"].Equals("Admin");
LoggedInUserName = myReader["FirstName"].ToString()+
myReader["LastName"].ToString();
}
if (count == 1 && IsAdminUser == true)
{
MessageBox.Show("Prijavljeni ste kot administrator!");
this.Hide();
Form4 f4 = new Form4(LoggedInUserName);
f4.ShowDialog();
}
else if (count == 1)
{
MessageBox.Show("Uspešno ste se prijavili!");
this.Hide();
Form3 f3 = new Form3(LoggedInUserName);
f3.ShowDialog();
}
Now change the both admin form(Form4) and UserForm (Form3)
//now change the Admin Form Form4 constructor to take 1 argument
public Form4(string username)
{
InitializeComponent();
myListBox.Items.Add(username);//Label1.Text= username;
}
//now change the UserForm Form3 constructor to take 1 argument
public Form3(string username)
{
InitializeComponent();
myListBox.Items.Add(username);//Label1.Text= username;
}
I'm trying to get my login system to work. Currently I think I have everything in place for it to work except the if statement conditions (if row is returned, then if statement is true, else login unsuccessful). I'm not sure how to read in the number of rows returned, I did attempt to use the ExecuteReader Method but couldn't get it to work.
Appreciate any help, thanks.
Code:
private void btn_login_Click(object sender, EventArgs e)
{
SqlCeConnection connection = new SqlCeConnection(#"Data Source=C:\\temp\\Project\\WindowsFormsApplication2\\Database.sdf");
connection.Open();
SqlCeCommand command = new SqlCeCommand("SELECT * FROM Technician WHERE Name = '" + txt_username.Text + "' AND Password = '" + txt_password.Text + "' ");
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
if ()
{
MessageBox.Show("Login Successful");
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(MainMenuForm));
t.Start();
this.Close();
}
else
{
MessageBox.Show("Login Unsuccessful");
return;
}
connection.Close();
}
I have changed your code to use a simpler ExecuteScalar that returns the first column of the first row obtained by your query
Of course, it is of extreme importance that you don't write your sql commands concatenating strings because this could fail in spectacular ways. (What if your textboxes contains a single quote and what if your user writes malicious text like this
using(SqlCeConnection connection = new SqlCeConnection(.....))
{
connection.Open();
string sqlText = "SELECT Count(*) FROM Technician WHERE Name = #name AND Password=#pwd"
SqlCeCommand command = new SqlCeCommand(sqlText, connection);
command.Parameters.AddWithValue("#name", txt_username.Text);
command.Parameters.AddWithValue("#pwd", txt_password.Text);
int result = (int)command.ExecuteScalar();
if (result > 0)
{
MessageBox.Show("Login Successful");
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(MainMenuForm));
t.Start();
this.Close();
}
else
{
MessageBox.Show("Login Unsuccessful");
return;
}
}
Notice also the using statement, in your previous code you exit from the procedure if no login is found but you forget to close the connection. This could become a big problem during lifetime of your application. The Using statement prevents this
Now I should start talking about the weakness of storing and trasmitting passwords in clear text, but that is another matter
The method ExecuteNonQuery will return the number of rows affected.
int rowsAffected = command.ExecuteNonQuery();
bool userExists = rowsAffected > 0;
if (userExists) // The user exists
{
}
Note: However your application is vulnerable to SQL Injection. I.e. I could enter ;DROP TABLE Technician into the txt_password text box.
You should use a parameterized query instead or another authentication method which is more secure (ASP.NET membership for instance).
To use paramertised queries you can change the CommandText to:
SqlCeCommand command = new SqlCeCommand("SELECT * FROM Technician WHERE Name=#username AND password=#password";
And then add the parameters in via:
command.Parameters.AddWithValue("#username", txt_username.Text);
command.Parameters.AddWithValue("#password", txt_password.Text);
http://johnhforrest.com/2010/10/parameterized-sql-queries-in-c/
private void btn_login_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=C:\\temp\\Project\\WindowsFormsApplication2\\Database.sdf");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Technician WHERE Name = '" + txt_username.Text + "' AND Password = '" + txt_password.Text + "' ");
int row=command.ExecuteNonQuery();
if (row>0)
{
MessageBox.Show("Login Successful");
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(MainMenuForm));
t.Start();
this.Close();
}
else
{
MessageBox.Show("Login Unsuccessful");
return;
}
connection.Close();
}
a=1;
b=1;
if a=b
{
a=c;
}
else
{
a=b;
}
else if
{
MessageBox.Show("Login Unsuccessful");
return i;