Only one message box is popped up after validating the 2 validations - c#

abstract class User
{
public string Username;
public string Password;
public virtual bool Validate(string username, string password)
{
Username = "";
Password = "";
if (password == Password && username == Username)
{
MessageBox.Show("Incorrect password or username");
return true;
}
else
{
return false;
}
}
form code:
private void btnSubmit_Click(object sender, EventArgs e)
{
UserAdmin admin = new UserAdmin();
UserEmployee empp = new UserEmployee();
bool validateAdmin = admin.Validate(txtUsername.Text, txtPassword.Text);
bool validateEmpp = empp.Validate(txtUsername.Text, txtPassword.Text);
if (validateAdmin==true || validateEmpp == true )
{
this.Hide();
// Create a new instance of the options class
Options opt = new Options();
opt.Closed += (s, args) => this.Close();
// Show the settings form
opt.Show();
}
When the first validation is false it keeps checking the second validation as well.By doing so 2 message boxes are being popped up.
EDIT:
Can you show only one message box instead of 2? it only shows the message box if the username or password is incorrect

You can combine validations in conditional expression:
if(admin.Validate(txtUsername.Text, txtPassword.Text) && empp.Validate(txtUsername.Text, txtPassword.Text))
{
... // is ok
}
else
{
... // when either Validate from left to right is not ok
}
This way if admin.Validate return false, then empp is not validated.

I would say that the standard way to stop execution of the code - is throwing an exception. So what You could do - is throw a 'ValidationExceptio' and implement appropriate ex handlers

To stop showing two message boxes, Remove the message box from method and include it into the click event. So the method will be like this:
public virtual bool Validate(string username, string password)
{
if (password == Password && username == Username)
{
return true;
}
else
{
return false;
}
}
And the click event will be like :
private void btnSubmit_Click(object sender, EventArgs e)
{
UserAdmin admin = new UserAdmin();
UserEmployee empp = new UserEmployee();
bool validateAdmin = admin.Validate(txtUsername.Text, txtPassword.Text);
bool validateEmpp = empp.Validate(txtUsername.Text, txtPassword.Text);
if (validateAdmin)
{
MessageBox.Show("Successfylly login as Admin");
//operation here
}
else if (validateEmpp)
{
MessageBox.Show("Successfylly login as " + txtUsername.Text);
//operation here
}
else { MessageBox.Show("Incorrect password or username"); }
}

Related

Need to make a login window with username and password in C# but when i introduce an incorrect username or password i get an error

when i introduce an incorrect username or password i get this error:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
private void button1_Click(object sender, EventArgs e)
{
string inserteduser = textBox1.Text;
string insertedpassword = textBox2.Text;
List<User> user = new List<User>();
user.Add(new User { username = "Michael", password = "1990" });
user.Add(new User { username = "Diana", password = "1234" });
int userlenght = user.Capacity/2;
for (int i = 0; i <= userlenght; i++)
{
if (user[i].username == inserteduser && user[i].password == insertedpassword)
MessageBox.Show("Login succesfull");
if (i == userlenght)
MessageBox.Show("Username or password is incorrect");**It never get's here**
}
}
As I said in my comments:
Do not use i <= userlenght instead use i < user.Count in your for loop. Capacity is not the same as Length or Count The List collection is a zero index based collection. The first entry has an index of "0". You have a count of two entries in the List so the last index is List.Count - 1.
But to make this all less verbose and easy to understand you could simply use LINQ and do this:
var success = user.Any(x => x.username == inserteduser && x. password == insertedpassword);
var message = success ? "Login succesfull" : "Username or password is incorrect";
MessageBox.Show(message);
Several things you could be doing differently:
Move the List out to class level so that it only gets populated once.
Use user.Count and < (less than) in your loop.
Declare a bool to determine if login was successful.
All together, that might look more like:
private List<User> user = new List<User>();
private void Form1_Load(object sender, EventArgs e)
{
user.Add(new User { username = "Michael", password = "1990" });
user.Add(new User { username = "Diana", password = "1234" });
}
private void button1_Click(object sender, EventArgs e)
{
string inserteduser = textBox1.Text;
string insertedpassword = textBox2.Text;
bool success = false;
for (int i = 0; i <user.Count; i++)
{
if (user[i].username == inserteduser && user[i].password == insertedpassword)
{
success = true;
break;
}
}
if (success)
{
label1.Text = "Passed!";
}
else
{
label1.Text = "Username or password is incorrect";
}
}

C# winform - equivalent of InputScope

Is there a property in Winform (.Net 4.0) that is equivalent to InputScope in UWP?
No I do not believe so. You need to use the Validating event
Such as if you want to assure the textbox contains an email you would do something like this:
private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
string errorMsg;
if(!ValidEmailAddress(textBox1.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(textBox1, errorMsg);
}
}
private void textBox1_Validated(object sender, System.EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(textBox1, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
// Confirm that the email address string is not empty.
if(emailAddress.Length == 0)
{
errorMessage = "email address is required.";
return false;
}
// Confirm that there is an "#" and a "." in the email address, and in the correct order.
if(emailAddress.IndexOf("#") > -1)
{
if(emailAddress.IndexOf(".", emailAddress.IndexOf("#") ) > emailAddress.IndexOf("#") )
{
errorMessage = "";
return true;
}
}
errorMessage = "email address must be valid email address format.\n" +
"For example 'someone#example.com' ";
return false;
}

Login using class C# in main form [duplicate]

I have a login screen and I need to pass username to my main form (for getting permissions etc.). Here is my code:
//Login
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtUser.Text))
{
//Show warning
}
else if (string.IsNullOrEmpty(txtPass.Text))
{
//Show warning
}
using (DataTable dt = LookupUser(txtUser.Text)) //Look into SQL data table for username and password
{
if (dt.Rows.Count == 0)
{
//Show warning
}
else
{
string dbPassword = Convert.ToString(dt.Rows[0]["pass"]);
string appPassword = Encrypt(txtPass.Text);
if (string.Compare(dbPassword, appPassword) == 0)
{
//I need to pass username value to myForm...
DialogResult = DialogResult.OK;
}
else
{
//Show warning
}
}
}
//Program.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
DialogResult result;
using (var loginForm = new Login())
result = loginForm.ShowDialog();
if (result == DialogResult.OK)
{
Application.Run(new myForm());
}
}
What would be the best way to pass value from loginForm to Program.cs and myForm?
In login form
public string UserName {get; private set;}
if (string.Compare(dbPassword, appPassword) == 0)
{
UserName = txtUser.Text;
//I need to pass username value to myForm...
DialogResult = DialogResult.OK;
}
else
{
//Show warning
}
in main
DialogResult result;
using (var loginForm = new Login())
result = loginForm.ShowDialog();
if (result == DialogResult.OK)
{
var username = loginForm.UserName;
Application.Run(new myForm(username));
}
Expose username as a string property of your login form class. This way you'll be able to fetch it after the form will be closed (it will still remain in memory).
This is the best way to transfer data from one form to another, On the LoginForm.cs write like this:
ex.UserName = txtUserName.text;
Password=txtPassword.text;
MainForm mainForm = new MainForm(UserName,Password);
this.Hide();
mainForm.Show();
In the MainForm.cs edit the
public MainForm ()
{
}
like this:
public MainForm(string userName,string password){
}
it is simply use EF on your codes
just like below
}
Siman_dbEntities db = new Siman_dbEntities();
public string UserNameLogedIn;
private void btnLogin_Click(object sender, EventArgs e)
{
var login = from b in db.Tbl_Users.Where(b => b.Username == txtUsername.Text && b.Password == txt_Password.Text)
select b;
if (login.Count()==1)
{
this.Hide();
main frmmain = new main();
frmmain.Show();
}
var query = db.Tbl_Users.Where(c => c.Username == txtUsername.Text).Single();
UserNameLogedIn = query.Name.ToString();
}

Enabled the button after the form opened c#

currently my window is like this with the edit and delete button disabled. In order to enable the buttons, user have to login with the administrator type. Right now, I already login with the administrator type from the member type. The disabled buttons supposed to be enabled after I logged in with the administrator type, but it is not.
Is there any way to enable the button, after the form opened with the buttons disabled?
Here is the images:
As you can see on the below image, there is a admin login button with edit and delete buttons disabled. (Main System Form):
Administrator Login (Privelege Form)
Here is the code that I am using:
public class SystemManager
{
public static void AdminLogin(string _value1, string _value2, Form _windowsForm, TextBox _windowsTextBox)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string query = "SELECT * FROM [Member] WHERE [Username] = #Username";
connection.Open();
using (OleDbCommand command = new OleDbCommand(query, connection))
{
command.Parameters.Add("#Username", OleDbType.VarChar);
command.Parameters["#Username"].Value = _value1;
using (OleDbDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
string password = (string)reader["Password"];
string userType = (string)reader["UserType"];
_isValidPassword = BCrypt.ValidateHash(_value2, password);
if (userType == "Administrator")
{
_isAdministrator = true;
}
else if (userType != "Administrator")
{
_isAdministrator = false;
}
if (_isValidPassword && _isAdministrator)
{
Authenticate _authenticate = new Authenticate();
_authenticate.ShowDialog();
ShowMessageBox("Authenticated.", "Success", 2);
UserInformation.isAdministrator = true;
_windowsForm.Hide();
_windowsForm.Close();
}
}
if (!_isValidPassword || !_isAdministrator)
{
Authenticate _authenticate = new Authenticate();
_authenticate.ShowDialog();
ShowMessageBox("Either username or password incorrect or you are not administrator. Please try again.", "Error", 1);
ClearTextBoxes(_windowsForm.Controls);
_windowsTextBox.Focus();
}
reader.Close();
}
}
connection.Close();
}
}
}
public partial class MainSystem: Form
{
void MainSystem_Load(object sender, EventArgs e)
{
UserPrivelege();
}
void UserPrivelege()
{
if (UserInformation.CurrentLoggedInUserType == "Member")
{
this.button3.Enabled = false; // Edit Button
this.button4.Enabled = false; // Delete Button
this.button7.Enabled = false;
this.button9.Enabled = true; // Admin Login Button
}
else if (UserInformation.CurrentLoggedInUserType == "Administrator" || UserInformation.isAdministrator)
{
this.button3.Enabled = true; // Edit Button
this.button4.Enabled = true; // Delete Button
this.button7.Enabled = true;
this.button9.Enabled = false; // Admin Login Button
}
}
}
public partial class Privelege : Form
{
void button1_Click(object sender, EventArgs e) // OK Button
{
Check();
}
void Check()
{
if (this.textBox1.Text == string.Empty || string.IsNullOrWhiteSpace(this.textBox1.Text))
{
SystemManager.ShowMessageBox("Username field required.", "Information", 2);
}
else if (this.textBox2.Text == string.Empty || string.IsNullOrWhiteSpace(this.textBox2.Text))
{
SystemManager.ShowMessageBox("Password field required.", "Information", 2);
}
else
{
SystemManager.AdminLogin(this.textBox1.Text, this.textBox2.Text, this, this.textBox1);
}
}
Thank you.
I really appreciate your answer.
There are several architectural issues here which when resolved will also make this function the way you want. First of all it is not ideal to call a function from a form which will act upon that form. It is a much better practice to return what is needed from that function and have the code to digest that result in the form which it affects. Let's try a simple example of what the login button could do:
private void btnLogin_Click(object sender, EventArgs e)
{
var login = new LoginForm();
login.ShowDialog();
var result = login.DialogResult == System.Windows.Forms.DialogResult.Yes;
if (result)
{
button2.Enabled = true;
button3.Enabled = true;
}
}
Obviously the only way this would work is if your login for was setting its DialogResult property, which is a simple way to pass a result from a modal dialog. We still have the issue of converting a login result to that value. This can be addressed in the login button of the dialog, and the login method it calls.
private void btnDialogLogin_Click(object sender, EventArgs e)
{
// Form validation here...
var result = SystemManager.AdminLogin(NameButton.Text, PassButton.Text);
DialogResult = DialogResult.No;
if (result)
{
DialogResult = DialogResult.Yes;
}
this.Close();
}
Now we have to change the AdminLogin method to a boolean:
public class SystemManager
{
public static bool AdminLogin(string _value1, string _value2)
{
// Database and evluation...
if(isAdmin)
{
return true;
}
return false;
}
}
This will make it easy to pass values as they are needed, without each object knowing more details about the other than is necessary. If the admin login needs to pass more information than just if the user is an admin, than create a class which contains all the different things one might want to know about the user's login and pass that as a return instead.
what you can do here is, once the user clicks login on your first form, you can send a boolean value to the constructor of your second form, say true for admin and false for others and depending on this value you can enable or disable your button.
The form load event, MainSystem_Load(), is only fired once (at first initialization). The UserPrivelege() function isn't called after the admin login. You will need to invoke that functionality after the admin logs in.
assign value to UserInformation.CurrentLoggedInUserType and on click of Admin login button open your login form as dialog and after close of this form call UserPrivelege(); fuction
Admin login onclick :-
PrivelegeForm frm= new LoginForm();
DialogResult result= frm.ShowDialog();
if (result==DialogResult.Ok)
{
UserPrivelege();
}
don't forget to assign your static variable UserInformation.CurrentLoggedInUserType

passing username to form but username returns null c#

This code is to return the value of textbox in the Login form.
public partial class Login : Form
{
public string returnUsername()
{
string username = textBox1.Text;
return username;
}
}
This code is to allow the ChangePass form to show.
public partial class Mainmenu_Employee : Form
{
private void changePasswd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
Login login = new Login();
ChangePass passwd = new ChangePass(login);
passwd.Show();
}
}
This code is to take the username from Login form so that I can change the password of the username.
public partial class ChangePass : Form
{
Login login = null; //parent form
Mainmenu_Employee main = new Mainmenu_Employee();
public ChangePass(Login login1)
{
InitializeComponent();
login = login1;
}
private void buttonChangePass_Click(object sender, EventArgs e)
{
Model_DB_Employee emp = new Model_DB_Employee();
//Login login = new Login();
string username = login.returnUsername();
if (textBoxNewPass.Text == string.Empty || textBoxConfirmPass.Text == string.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
else
{
if (textBoxNewPass.Text == textBoxConfirmPass.Text)
{
try
{
emp.changePasswd(username,textBoxConfirmPass.Text);
MessageBox.Show(username);
MessageBox.Show("Password updated!");
this.Hide();
main.Show();
}
catch(SystemException ex)
{
MessageBox.Show("Password not updated" + ex);
}
}
else
{
MessageBox.Show("Passwords do not match!");
}
}
}
Change password function:
public void changePasswd(string username, string newpass) //change password
{
Model_Employee emp = new Model_Employee();
//Hasher hash = new Hasher(); //call hasher class for hashing
//string hashed;
//string salt = emp.generateSalt(); //generate random salt
//newpass = newpass + salt; //append salt to newpass
//hashed = hash.encryption(newpass); //hash newpass
for (int i = 0; i < rows.Count; ++i)
{
if ((string)empTab.Rows[i]["username"] == username)//check if ID matches
{
empTab.Rows[i]["passwd"] = newpass; //set passwd to hash new password
//check if dataset has changes
if (dataset.HasChanges())
{
//update database
dbAdapter.Update(dataset, "employee");
MessageBox.Show("Employee Updated!");
refreshTable();
}
else
{
refreshTable();
}
}
}
}
I am trying to change a user's password when he is logged in.
When he logs in, I want to capture his username through a textbox.
After he logs in, there will be a main menu displayed.
The user needs to click on the change password link and a change password form will appear.
Therefore, I need to pass the username from the login form to the change password form in order to use a change password function. However, the issue I am facing now is that the username does not get passed from the login form to the change password form.
The problem is the line:
Login login = new Login();
This is shadowing the login instance field with a new instance of Login as a local variable, so rather than accessing the Login created earlier that the user has interacted with, you're accessing a blank one. You can just delete the above line of code.
The problem is that with Login login = new Login() you´re shadowing your class instance variable login. Try:
private void buttonChangePass_Click(object sender, EventArgs e)
{
Model_DB_Employee emp = new Model_DB_Employee();
string username = login.returnUsername();
if (textBoxNewPass.Text == string.Empty || textBoxConfirmPass.Text == string.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
else
{
if (textBoxNewPass.Text == textBoxConfirmPass.Text)
{
try
{
emp.changePasswd(username,textBoxConfirmPass.Text);
MessageBox.Show(username);
MessageBox.Show("Password updated!");
this.Hide();
main.Show();
}
catch(SystemException ex)
{
MessageBox.Show("Password not updated" + ex);
}
}
else
{
MessageBox.Show("Passwords do not match!");
}
}
}
When, between these two lines, does the username in the new login get set?
Login login = new Login();
string username = login.returnUsername();
You never show the Login form, how do you suppose that someone sets the textBox1 with an actual username?
You need something like this
string username = string.Empty;
Model_DB_Employee emp = new Model_DB_Employee();
using(Login login = new Login())
{
if(DialogResult.OK == login.ShowDialog())
username = login.returnUsername();
}
if(username == string.Empty)
{
MessageBox.Show("Username required");
return;
}

Categories