How to assign database values into global variables in a class - c#

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
...

Related

Why can't i save registered users to the database?

So i have been trying to resolve this issue for a while now, with no awail. Everything works but when i try to login with a "succesfully registered user", it still shows invalid credentials, meaning that the save didn't succeed,
This is my code:
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace SchoolManagementApplication
{
public partial class LoginDialog : Form
{
public LoginDialog()
{
InitializeComponent();
}
private bool VerifyUserCredentials(string username, string password)
{
bool isValidUser = false;
// Connection string
string connectionString = Properties.Settings.Default.UnPConnectionString;
// SQL query
string query = "SELECT COUNT(*) FROM [Table2] WHERE Username = #Username AND Password = #Password";
// Create a new connection
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a new command
using (SqlCommand command = new SqlCommand(query, connection))
{
// Add parameters to the query
command.Parameters.AddWithValue("#Username", username);
command.Parameters.AddWithValue("#Password", password);
// Open the connection
connection.Open();
// Execute the query
int result = (int)command.ExecuteScalar();
// Check if the result is greater than 0
if (result > 0)
{
isValidUser = true;
}
connection.Close();
}
}
return isValidUser;
}
public void AddUser(string username, string password)
{
string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\shayan.homaiesfahan\\Desktop\\SchoolManagementApplication\\SchoolManagementApplication\\bin\\Debug\\Unp.mdf;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// insert the new user into the table
string insertSql = "INSERT INTO [Table2] (Username, Password) VALUES (#Username, #Password)";
using (SqlCommand insertCommand = new SqlCommand(insertSql, connection))
{
insertCommand.Parameters.AddWithValue("#Username", username);
insertCommand.Parameters.AddWithValue("#Password", password);
insertCommand.ExecuteNonQuery();
}
connection.Close();
}
}
private void BtnOK_Click(object sender, EventArgs e)
{
// Get the entered username and password
string username = tbxUsername.Text;
string password = tbxPassword.Text;
// Verify the user credentials
if (VerifyUserCredentials(username, password))
{
MessageBox.Show(string.Format("Welcome: {0}", username));
// Code to open the main application goes here
this.Hide();
MainInterface MI = new MainInterface();
MI.Show();
}
else
{
MessageBox.Show("Invalid credentials. Please try again.");
//// Clear the textboxes
tbxUsername.Text = "";
tbxPassword.Text = "";
}
}
private void Btn_register_Click(object sender, EventArgs e)
{
string username = tbxUsername.Text;
string password = tbxPassword.Text;
// Verify that the username and password are not empty
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
// Call the AddUser method
AddUser(username, password);
// Show a message that the user has been registered
MessageBox.Show("You have been successfully registered!");
// Clear the textboxes
tbxUsername.Text = "";
tbxPassword.Text = "";
}
else
{
// Show a message that the username and password are required
MessageBox.Show("Username and password are required.");
}
}
private void btnCancel2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
It did work in one point, but somehow it stopped working.

Creating a user profile page using a database

I am doing a simple project for school where I have to create a login form and make it so when a person logs in it then shows their profile with all their user information. So how would I code the textboxes in windows forms C# so when a person logs in the textboxes show information gathered from database of person who just logged in.
This is the code for the login form.
OleDbConnection connection = new OleDbConnection(); connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\RAV21001310\\OneDrive\\Database1.accdb;";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from tblUser where Username= '"+username.Text+"' and Password= '"+password.Text+"'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username and password is correct");
var profile = new profile();
}
if (count > 1)
{
MessageBox.Show("Duplicate username and password");
}
else
{
MessageBox.Show("Username or password incorrect");
}
connection.Close();
As I said in the comments, always use parameters in your query strings. Also, since OleDbDataReader is forward reading only, what I would do is create a new user and add to a list for each record returned. Then, if you only get one record, use that user data to populate the form. One other major flaw in your code... You are storing passwords as plain text in the database. The best practice is to encrypt/hash the password using one-way encryption and only store the hash in the database. Everytime the user enters a password at login, hash it using the same algorithm and compare it against the hash stored in the DB.
Here's an example incorporating Using (suggested by #Flydog57) and Parameters. But I'm not showing how to hash and store encrypted passwords.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
public class Program
{
public static void Main()
{
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;
List<User> UserList = new List<User>();
while (reader.Read())
{
count = count + 1;
User user = new User() {
Username = reader.GetString(1),
FirstName = reader.GetString(2),
LastName = reader.GetString(3),
DateCreated = reader.GetDateTime(4)
};
UserList.Add(user);
}
if (count == 1)
{
//Alert User
MessageBox.Show("Username and password is correct");
//Create an instance of the ProfileForm and populated it with the User data.
var ProfileForm pf = new ProfileForm(UserList[0]);
//Show the Profile Form as a modal window.
pf.ShowDialog();
}
if (count > 1)
{
MessageBox.Show("Duplicate username and password");
}
else
{
MessageBox.Show("Username or password incorrect");
}
}
}
connection.Close();
}
}
}
//This is a class to hold user data.
public class User {
public string Username { get; set; } = "";
public string Password { get; set; } = "";
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public DateTime DateCreated { get; set; } = DateTime.MinValue;
}
This is a quick sample of the code-behind for a "ProfileForm". When you verify the user is authenticated, then create an instance of the ProfileForm, populate it with the userdata, then show the form to the user. There are many other ways to populate a profile form and handle updates to user data, this is just one example.
public class ProfileForm : Form
{
public User User
{
get
{
//When you get the User, update all the user data from text boxes.
User.FirstName = firstnameTextBox.Text;
User.LastName = lastnameTextBox.Text;
//return the newly updated User variable.
return User;
}
set
{
//When we write new data to the form User variable,
//populate each relevant text box on the form.
usernameTextBox.Text = User.Username;
firstnameTextBox.Text = User.FirstName;
lastnameTextBox.Text = User.LastName;
}
}
public ProfileForm(User User) {
this.User = User;
}
}

LOGIN FORM using class

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

C# winforms save UserID value to class

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;

How to call a method from another class inside a Window?

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.

Categories