I'm trying to save UserID value to a class after an successful login. When the login button is clicked, it validates the login into in text boxes using the #user, #pass.
My problem is that I do not know how to write a sql reader and save the resulting int to a class. I also do not know how to write that class.
I need to save it to a class so I can use it on different forms to check what account the user is logged into.
EDIT: Updated code from suggestions but i get errors Error picture any ideas where i did a mistake?
private LoginUser validate_login(string user, string pass)
{
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from table2 where username=#user and password=#pass";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = connect;
LoginUser usr = new LoginUser();
MySqlDataReader login = cmd.ExecuteReader();
while(login.Read())
{
connect.Close();
usr.UserID = login["UserID"];
usr.valid = true;
}
return usr;
}
private void button1_Click(object sender, EventArgs e)
{
{
string user = usertype.Text;
string pass = password.Text;
if (user == "" || pass == "")
{
MessageBox.Show("Empty Fields Detected ! Please fill up all the fields");
return;
}
bool r = validate_login(user, pass);
if (r)
{
LoginUser usr = new LoginUser();
usr = validate_login(user, pass);
if (usr.valid)
{
Console.WriteLine(String.Format("{0}", usr.UserID));
UserDetails.m_gnUserId = Convert.ToInt32(reader["UserID"]);
}
}
}
}
public partial class Form1 : Form
{
private LoginUser validate_login(string user, string pass)
{
...
LoginUser usr = new LoginUser();
MySqlDataReader login = cmd.ExecuteReader();
while(login.Read())
{
connect.Close();
usr.UserID = login["UserID"];
usr.valid = true;
}
return usr;
}
private void button1_Click(object sender, EventArgs e)
{
...
LoginUser usr = new LoginUser();
usr = validate_login(user, pass);
if (usr.valid)
{
Console.WriteLine(String.Format("{0}", usr.UserID));
}
}
}
public class LoginUser
{
public Bool valid = false;
public String UserID = "";
// You can have more column name up to matching with your table column.
}
One of the method is as follow
Create a class UserDetails with all the data you want to store
public static class UserDetails
{
public static int m_gnUserId {get;set;}
//Add other variables which you want to store and use across different forms
}
To Store Value
UserDetails.m_gnUserId = Convert.ToInt32(reader["UserID"]); .
This storing of Value will go after Console.WriteLine(String.Format("{0}", reader["UserID"])); in your button1_click event.
To get the value on other form
int UserId = UserDetails.m_gnUserId;
Related
I am creating a windows forms in C# with following code:
private void button1_Click(object sender, EventArgs e)
{
using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\RAV21001310\\OneDrive\\Database1.accdb;"))
{
connection.Open();
using (OleDbCommand command = new OleDbCommand("SELECT * FROM tblUser WHERE Username=#Username AND Password=#Password", connection))
{
command.Parameters.AddWithValue("#Username", username.Text);
command.Parameters.AddWithValue("#Password", password.Text);
using (OleDbDataReader reader = command.ExecuteReader())
{
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username and password is correct");
}
if (count > 1)
{
MessageBox.Show("Duplicate username and password");
}
if (count == 0)
{
MessageBox.Show("Username or password incorrect");
}
}
}
connection.Close();
}
}
}
public class User
{
public string Username;
public string Password;
public string FirstName;
public string LastName;
public string Gender;
public int Age;
public int TotalPoints;
}
The first part is for a login form. The part I am struggling with is how to make it so when a user logs in it gets all his relevant information like username, password, TotalPoints etc from the database in ms access and assigns it to the variables in the class so they can be called throughout different forms.
// Add parameters for the username and password
command.Parameters.Add("#Username").Value = username.text;
command.Parameters.Add("#Password").Value = password.text;
// Execute the query
SqlDataReader reader = command.ExecuteReader();
// Validate the user's credentials
bool isValid = false;
if (reader.Read())
{
User user = new User
{
Id = Convert.ToInt32(reader["Id"]),
// Add all fileds you want to use...
}
isValid = true;
}
// Close the reader and the connection
reader.Close();
connection.Close();
// Do someting with result
...
I have button1_click in Form1.. and i want string usernamebox.text and passwordbox.text to login class i created it before.. and I got stuck here.. Login class work but button code not how Get textBox value in from1 to login class
private void button1_Click(object sender, EventArgs e)
{
String c1 = new String();
c1 = UsernameBox.Text;
Login.Validation_user(c1.ToString());
String c2 = new String();
c2 = PasswordBox.Text;
Login.Validation_pass(c2.ToString());
}
this my string
static string connectionClient = ConfigurationManager.ConnectionStrings["Sample2"].ConnectionString;
private static bool Validation { get; set; }
this my login class "Password"
public static void Validation_pass (string password)
{
if (!Validation)
{
using (MySqlConnection sqlConn = new MySqlConnection(connectionClient))
{
string checkForLogQuery = "SELECT * FROM Login WHERE Password=#pass";
MySqlCommand cmd = new MySqlCommand(checkForLogQuery, sqlConn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pass", password);
sqlConn.Open();
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result == 1)
{
MessageBox.Show("wellcome");
Form9 f9 = new Form9();
f9.Close();
f9.DialogResult = System.Windows.Forms.DialogResult.Cancel;
Form10 f10 = new Form10();
f10.Show();
Validation = true;
}
else
{
MessageBox.Show("Your Key was incorrect");
Validation = false;
}
}
}
else
{
}
}
and "username" it same what is above
You need to validate both password and username together
Here is an example
private void button1_Click(object sender, EventArgs e) {
var res = Login.Validate(PasswordBox.Text, UsernameBox.Text);
if (res)
MessageBox.Show("wellcome");
else
MessageBox.Show("UserName or Password dose not match.");
}
public static bool Validate(string password, string userName) {
if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(userName))
return false;
using(MySqlConnection sqlConn = new MySqlConnection(connectionClient)) {
string checkForLogQuery = "SELECT 1 FROM Login WHERE Password=#pass and LOWER(UserName) = LOWER(#userName)";
MySqlCommand cmd = new MySqlCommand(checkForLogQuery, sqlConn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pass", password);
cmd.Parameters.AddWithValue("#userName", userName);
sqlConn.Open();
var value = Convert.ToBoolean(cmd.ExecuteScalar());
sqlConn.Close();
return value;
}
}
Hello im trying to create login form that saves your UserID to Userdetails class. But for some reason log in doesnt work.I think there is somewhere mistake in if (login.Read()) in validate_login but im not sure. If i put messagebox to if (r.valid) it doesnt work so thats why i think somewhere in if (login.Read()) . Any form of help would be welcome. Thanks.
I have tryed rewriting mysql query, ( cmd.CommandText = )
If i remove if (r != null) i get this error System.NullReferenceException: 'Object reference not set to an instance of an object.'
r was null.
private void db_connection()
{
try
{
conn = "..connection string..";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
}
private LoginUser validate_login(string user, string pass)
{
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from table2 where username=#user and password=#pass";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = connect;
LoginUser usr = null;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
usr = new LoginUser();
usr.UserID = login["UserID"].ToString();
usr.valid = true;
}
return usr;
}
private void button1_Click(object sender, EventArgs e)
{
{
string user = username.Text;
string pass = password.Text;
var r = validate_login(user, pass);
if (r != null)
{
if (r.valid)
{
MessageBox.Show("validated");
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine(String.Format("{0}", r.UserID));
UserDetails.m_gnUserId = Convert.ToInt32(r.UserID);
}
}
}
}
validate_login should work as follows:validate_login should run query and search for username and password that is same as textbox #user and #pass.
button1_Click should start that validate_login
Note:I know i need to hash passwords in my db and i currently dont. Its my next step after this.
Your problem is probably because you return null, if there were no such record in database.
LoginUser usr = null;
If that's not what you want, you should return new LoginUser with field valid set to false.
var usr = new LoginUser(){ valid = false };
And don't forget to check for that in your button's event handler.
So I have a Class called "User" in which I have the following method and code:
public void Login()
{
LoginWindow l = new LoginWindow();
if (l.tbxEmail.Text != "" && l.tbxPassword.Text != "")
{
string query = "SELECT * FROM UsersTBL";
l.con.Open();
l.com = l.con.CreateCommand();
l.com.CommandText = query;
SqlDataReader dr = l.com.ExecuteReader();
if (dr.Read())
{
if (dr["Email"].Equals(l.tbxEmail.Text.ToString()) && dr["UserPassword"].Equals(l.tbxPassword.Text.ToString()))
{
AppWindow a = new AppWindow();
a.Show();
}
else
l.lblMissingParameter.Content = "Incorrect Password or Email entered";
}
}
}
And in my LoginWindow I have:
public partial class LoginWindow:Window
{
User u = new User();
private void BtnSignup_Click(object sender, RoutedEventArgs e)
{
u.Login();
}
}
When I try to call my Login method via class instantiation nothing works, why is that? Am I calling it the wrong way?
This should work, although I left comments on things that should be addressed.
User class:
public bool Login(SqlConnection con, string email, string password)
{
const string query = "SELECT 1 FROM UsersTBL WHERE Email = #email AND UserPassword = #password";
if (!string.IsNullOrWhiteSpace(email) && !string.IsNullOrWhiteSpace(password))
{
try
{
con.Open();
var cmd = con.CreateCommand();
cmd.CommandText = query;
//Correct SqlDbTypes if necessary
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = email;
cmd.Parameters.Add("#password", SqlDbType.VarChar);
//Should NOT be storing passwords as plain text in the database
cmd.Parameters["#password"].Value = password;
if (cmd.ExecuteScalar() == 1)
return true;
}
catch (Exception e)
{
//log e somehow or eliminate this catch block
}
finally
{
//Close the connection if still open
if (con != null && con.State != ConnectionState.Closed)
con.Close();
}
}
return false;
}
LoginWindow class:
public partial class LoginWindow : Window
{
private void BtnSignup_Click(object sender, RoutedEventArgs e)
{
var u = new User();
if (u.Login(con, tbxEmail.Text, tbxPassword.Text))
{
AppWindow a = new AppWindow();
a.Show();
}
else
lblMissingParameter.Content = "Incorrect Password or Email entered";
}
}
To clarify, you had this problem because the tbxEmail and tbxPassword variables in your User class where not the same as the ones in your main class.
You should create both variable at class scope:
public class User {
TextBox tbxEmail; // could be strings
PasswordBox tbxPassword;
public User (TextBox tbxEmail, TextBox tbxPassword) {
this.tbxEmail = tbxEmail;
this.tbxPassword = tbxPassword;
}
}
And then:
User user = new User(tbxEmail,tbxPassword);
user.Login();
Or, create a static method (static method can't use global variables, so everything you need have to be passed as parameter of the method or created inside of it).:
public static void Login (string email, string password){
// code here
}
I wrote a rudimentary login page for one of my school projects similar to this:
private void signInButton_Click(object sender, EventArgs e)
{
DataProcedures data = new DataProcedures();
User userInfo = new User(usernameTextbox.Text, passwordTextbox.Text);
userInfo.userId = data.verifyUser(userInfo);
if (userInfo.userId != -1)
{
AppWindow a = new AppWindow();
a.Show();
}
else
{
errorLabel.Show();
}
}
public int verifyUser(User userInfo)
{
MySqlConnection conn = new MySqlConnection(connectionString);
int userId = -1;
string returnedUserName;
string returnedPassword;
try
{
conn.Open();
MySqlCommand checkUserNameCmd = conn.CreateCommand();
checkUserNameCmd.CommandText = "SELECT EXISTS(SELECT userName FROM user WHERE userName = #username)";
checkUserNameCmd.Parameters.AddWithValue("#username", userInfo.username);
returnedUserName = checkUserNameCmd.ExecuteScalar().ToString();
MySqlCommand checkPasswordCmd = conn.CreateCommand();
checkPasswordCmd.CommandText = "SELECT EXISTS(SELECT password FROM user WHERE BINARY password = #password AND userName = #username)";//"BINARY" is used for case sensitivity in SQL queries
checkPasswordCmd.Parameters.AddWithValue("#password", userInfo.password);
checkPasswordCmd.Parameters.AddWithValue("#username", userInfo.username);
returnedPassword = checkPasswordCmd.ExecuteScalar().ToString();
if (returnedUserName == "1" && returnedPassword == "1")
{
MySqlCommand returnUserIdCmd = conn.CreateCommand();
returnUserIdCmd.CommandText = "SELECT userId FROM user WHERE BINARY password = #password AND userName = #username";
returnUserIdCmd.Parameters.AddWithValue("#password", userInfo.password);
returnUserIdCmd.Parameters.AddWithValue("#username", userInfo.username);
userId = (int)returnUserIdCmd.ExecuteScalar();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown verifying user: " + ex);
}
finally
{
conn.Close();
}
return userId;
}
Hope this helps.
I have a table tbl_user where it has the columns of tbl_user_username,tbl_user_password,tbl_user_type. What I need is that how can i specifically say if the type associated with the username equals to something open some form. For example if the username= "john" and the john has the type of "Admin" open Admin panel. How can I validate the user type? This how I did so far. Thanks in advance.
private void button1Lg_Click(object sender, EventArgs e)
{
bool res = login_check(textBox1U_Name.Text, textBox2U_Password.Text);
if(res)
{
MessageBox.Show("Welcome " + textBox1U_Name.Text);
}
else
{
MessageBox.Show("Invalid Login");
}
}
public bool login_check(string username, string password)
{
using (MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.ConnectionString))
{
conn.Open();
string sql = "SELECT tbl_user_username, tbl_user_password, tbl_user_type WHERE tbl_user_username=#username, tbl_user_password=#password AND tbl_user_type=#type";
MySqlCommand cmd = new MySqlCommand(sql,conn);
cmd.Parameters.AddWithValue("uname", username);
cmd.Parameters.AddWithValue("upass", password);
bool result = cmd.ExecuteReader().HasRows;
conn.Close();
return false;
}
}