Comparing data values from mySQL (WPF - C#) - c#

I am attempting to learn .WPF and I've already encountered snag.
I'm trying to take 2 user input strings, via text-boxes, and compare both strings to values
retrieved from a mySQL database.
findUserFromDB function below: ( this is supposed to retrieve and compare the user values )
public static void findUserFromDB(string user, string pass)
{
List<User> users = new List<User> { };
MySqlDataReader reader = null;
bool userFound = false;
MainWindow main = new MainWindow();
try
{
myConn.Open();
MySqlCommand cmd = new MySqlCommand();
//Sets command text and connection database
cmd.CommandText = string.Format("Select * From users");
cmd.Connection = myConn;
reader = cmd.ExecuteReader();
while(reader.Read())
{
User forUser = new User
{
sName = reader.GetString("Forename").Trim(),
sPass = reader.GetString("Password").Trim(),
};
users.Add(forUser);
}
if (userFound == false)
{
MessageBoxResult msg = MessageBox.Show(main, "Username or Password" +
" not recognised.", "Login failed", MessageBoxButton.OK);
}
for (int i = 0; i < user.Count(); i++)
{
if (users[i].sName == user && users[i].sPass == pass)
{
Menu m = new Menu();
string message = "Welcome back " + user + ".";
MessageBoxResult msg = MessageBox.Show(main, message,
"Login successful", MessageBoxButton.OK);
m.Show();
main.Close();
break;
}
}
}
catch (MySqlException e)
{
}
finally
{
if (reader != null)
{
reader.Close(); //Close the reader
}
if (myConn != null)
{
myConn.Close(); //ensure you close the connection
}
}
looking at it now I realise that I should be retrieving the data and then closing the DB, before comparing the values...
My questions:
What am I doing wrong?
As soon as I press the button to login nothing happens.

I got it working.
Was referencing the wrong Database ^^,
God I feel stupid...

Related

C# - Microsoft sql database | Can't add new user on my e-contact app

I tried to make an e-contact app with C# on Visual Studio 2019 connected to a Miscrosoft SQL database (local) following a youtube tutorial.
The app is not complete yet, anyway the btnAdd should work, but it doesn't add the user and the return of the method (Insert).
It always returns false - Can anyone help me?
private void BntAdd_Click(object sender, EventArgs e) {
//Get the value from the imput fields
c.Nome = txtBoxName.Text;
c.Cognome = txtBoxSurname.Text;
c.Telefono1= txtBoxPhone1.Text;
c.Telefono = txtBoxPhone.Text;
c.Email = txtBoxEmail.Text;
//Inserting Data into Database uing the method we created is previous episode
bool success = c.Insert(c);
if (success == true)
{
//Successfully Inserted
MessageBox.Show("New contact added!");
//Call the clear Method Here
Clear();
}
else
{
//Failed to add Contact
MessageBox.Show("ERROR!)");
}
//load Data on Data GRidview
DataTable dt = c.Select();
dgvRubrica.DataSource = dt;
}
public void Clear()
{
txtBoxName.Text = "";
txtBoxSurname.Text = "";
txtBoxPhone1.Text = "";
txtBoxPhone.Text = "";
txtBoxEmail.Text = "";
}
public bool Insert (rubricaClass c) {
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "INSERT INTO tbl_Rubrica (Nome, Cognome, Telefono1, Telefono, Email) VALUES (#Nome, #Cognome, #Telefono1, #Telefono, #Email)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Nome", c.Nome);
cmd.Parameters.AddWithValue("#Cognome", c.Cognome);
cmd.Parameters.AddWithValue("#Telefono1", c.Telefono1);
cmd.Parameters.AddWithValue("#Telefono", c.Telefono);
cmd.Parameters.AddWithValue("#Email", c.Email);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
It doesn't give any errors, it work but when i type the ata into txtBoxes and then i press the add button it says Error (message box inserte in the else)
Step 1 is to remove the catch-all exception handling from the Insert method. Most of the ADO.NET database classes implement IDisposable, so you just need a using(...) block to make sure the command is disposed automatically (which will also close and dispose the connection instance):
public bool Insert (rubricaClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
string sql = "INSERT INTO tbl_Rubrica (Nome, Cognome, Telefono1, Telefono, Email) VALUES (#Nome, #Cognome, #Telefono1, #Telefono, #Email)";
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#Nome", c.Nome);
cmd.Parameters.AddWithValue("#Cognome", c.Cognome);
cmd.Parameters.AddWithValue("#Telefono1", c.Telefono1);
cmd.Parameters.AddWithValue("#Telefono", c.Telefono);
cmd.Parameters.AddWithValue("#Email", c.Email);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
return isSuccess;
}
Once that's squared away, Step 2 is to move your exception handling into the application. I don't recommend this "catch everything"-style code, but it works for now, I suppose:
private void BntAdd_Click(object sender, EventArgs e)
{
//Get the value from the imput fields
c.Nome = txtBoxName.Text;
c.Cognome = txtBoxSurname.Text;
c.Telefono1= txtBoxPhone1.Text;
c.Telefono = txtBoxPhone.Text;
c.Email = txtBoxEmail.Text;
try
{
//Inserting Data into Database uing the method we created is previous episode
bool success = c.Insert(c);
if (success == true)
{
//Successfully Inserted
MessageBox.Show("New contact added!");
//Call the clear Method Here
Clear();
}
else
{
//Failed to add Contact
MessageBox.Show("ERROR!)");
}
//load Data on Data GRidview
DataTable dt = c.Select();
dgvRubrica.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This will likely tell you that you either have an error in your SQL syntax, or that the command itself could not be run (i.e. the connection string is invalid or the server can't be reached).

to hide a column in grid-view for "Stockcontroller" and make it visible for "Administrator"

This is my grideview code:
I need to use a if statment for this code: private const string select_query
need to show the first code to the Administrator and the second code to the stockcontroller. i am trying to hide only one column the last "UserID".
i dont know how to call that and sign to different users using a if statement.
just tried it out!!!
this is my stock grid-view code:
SqlCommand selectCommand = new SqlCommand(" Select * from New_User where User_Name=#USER_ID", conn);
selectCommand.Parameters.Add(new SqlParameter("USER_ID", txtusername.Text.ToString());
string UserType = null;
SqlDataReader reader = selectCommand.ExecuteReader();
bool rowfound = reader.HasRows;
if (rowfound)
{
while (reader.Read())
{
UserType = reader["User_Type"].ToString().Trim();
if (UserType == "Administrator")
{
GlobalVariablesClass.VariableOne = txtusername.Text;
private const string select_query = "SELECT TOP 3 id,stock_type,stock_no,no_of_pieces,Gem_Type,Weight,Image,Cost,Create_Date,Update_Date,UserID FROM Stock_Gems";
}
else if (UserType == "StockController")
{
GlobalVariablesClass.VariableOne = txtusername.Text;
private const string select_query = "SELECT TOP 3 id,stock_type,stock_no,no_of_pieces,Gem_Type,Weight,Image,Cost,Create_Date,Update_Date FROM Stock_Gems";
}
}
}
This is my login code:
private void tbnlogin_Click(object sender, EventArgs e)
{
try
{
SqlCommand selectCommand = new SqlCommand(" Select * from New_User where User_Name=#USER_ID and Password=#PASS", conn);
selectCommand.Parameters.Add(new SqlParameter("USER_ID", txtusername.Text.ToString()));
String password = "";
using (SHA1 sha1 = SHA1.Create())
{
byte[] data = sha1.ComputeHash(Encoding.UTF8.GetBytes(txtpassword.Text));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; ++i)
{
sb.Append(data[i].ToString("x2"));
}
password = sb.ToString();
}
selectCommand.Parameters.Add(new SqlParameter("PASS", password));
string UserType = null;
SqlDataReader reader = selectCommand.ExecuteReader();
bool rowfound = reader.HasRows;
if (rowfound)
{
while (reader.Read())
{
UserType = reader["User_Type"].ToString().Trim();
if (UserType == "Administrator")
{
GlobalVariablesClass.VariableOne = txtusername.Text;
MessageBox.Show("Welcome ", "Admin Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
Admin_Menu frm = new Admin_Menu();
frm.bunifuFlatButton3.Visible = true;
frm.Show();
this.Hide();
}
else if (UserType == "StockController")
{
GlobalVariablesClass.VariableOne = txtusername.Text;
MessageBox.Show("Welcome ", "User Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
Admin_Menu frm = new Admin_Menu();
frm.bunifuFlatButton3.Visible = false;
frm.Show();
this.Hide();
}
}
}
else
{
MessageBox.Show(" Invalid User Or Password ", "Login ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
reader.Close();
}
}
I have a grid-view with columns of items as follows:
ID|Stock_Type|Stock_No|No_of_pieces|Gem_Type|Weight|Image|Cost|Create_Date|Update_date|UserID|
I found this but I don't know how retrieve from database.
This was coded into the stock gridview loader
DisplayData();
hello.Text = GlobalVariablesClass.VariableOne;
if (Roles.IsUserInRole("Administrator"))
{
this.dataGridView1.Columns[10].Visible = true;
}
else
{
this.dataGridView1.Columns[10].Visible = false;
}
**I have used the global variation which means the username who logged in will be on all the pages..

Handling multiple buttons in same asp.net page

hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx

Using these methods, how do I check if this entry is in a SQL database?

I've got an ATM machine and that I've created and it has a Login screen.
You need to be able to log in with the Account Number "1111222233334444" which I've entered into a database and the PIN "7777"
I need it so when submit is clicked it'll check my database and table for these entries and if they're in their it'll continue to the next form. Where would the SQL methods go so that I could check if the entered account and pin number are in the database? Here's my Open Connection code.
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to the server. ");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
My CheckCredentials code is this:
public List<string>[] CheckCredentials()
{
string query = "SELECT * FROM atmmachine";
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
list[0].Add(dataReader["AccountNumber"] + "");
list[1].Add(dataReader["PIN"] + "");
}
dataReader.Close();
this.CloseConnection();
return list;
}
else
{
return list;
}
}
then my Button click code is as follows, most of this is just validation that needs to be changed obviously.
private void btn_Confirm_Click(object sender, EventArgs e)
{
String a;
String b;
a = txt_PIN.Text;
b = txt_Account.Text;
if (a.Length < 5 && a.Length > 3 && b.Length < 17 && b.Length > 15)
{
Login f1 = new Login();
this.Hide();
Navigation f2 = new Navigation();
f2.Show();
}
else
{
MessageBox.Show("Invalid PIN or Account Number");
}
}
for nath
public bool CheckCredentials()
{
string query = "SELECT 'PIN' FROM atm WHERE AccountNumber = enteredAcctnum";
string PIN;
string AccountNumber;
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string pin = reader.GetString(0);
}
reader.Close();
this.CloseConnection();
return ???
}
else
{
return ???
}
}
You don't need to SELECT *
Simply SELECT the account number column and then compare the entered pin to the matching pin column in the table.
Try something like this:
Call the CheckCredentials method passing b and a. In your log-in form:
CheckCredentials(b, a)
Now, in CheckCredentials:
SELECT pin FROM your_table WHERE accountnumber = b
You then use your reader:
while (reader.Read())
{
string pin = reader.GetString(0);
}
Then you can compare:
if (pin == a)
return true;
else return false;
NOTE: Add two string parameters in your CheckCredentials(string b, string a)

How to check if ID already exists in MS Access database file, and how to check it by using TextChanged in TextBox?

I am working on part of my program where I am deleting entry by using provided Entry ID.
As of right now I am deleting any entry specified by user. This works great but, what I am trying to do is to inform user that there is no such ID to delete. Also, I am using textbox TextChanged which let me to check for certain things in user input while user is typing.
Now, how do I check if Entry ID already exists? What should I include in my if statement to do this?
Also, is there a way I could check that by using TextChanged event handler? I'm not sure about that because I know that if I would have opening and closing connection in TextChanged event, then connection would be opened/closed every time user is typing, so I don't think this is a good idea. But how can I avoid this and so I can do this in real time? Perhaps when user stop typing, and then take a second or two to check for entry id?
This is a code of my delete entry window:
public partial class DeleteEntryWindow : Form
{
string user, pass, filePath;
// Initializing MainWindow form.
MainWindow mainWindow;
public DeleteEntryWindow()
{
InitializeComponent();
txtEntryID.TextChanged += new EventHandler(ValidateInput);
}
public DeleteEntryWindow(MainWindow viaParameter,
string user, string pass, string filePath)
: this()
{
mainWindow = viaParameter;
this.user = user;
this.pass = pass;
this.filePath = filePath;
}
private void ValidateInput(object sender, EventArgs e)
{
int intNumber;
if (!string.IsNullOrEmpty(txtEntryID.Text) &&
int.TryParse(txtEntryID.Text, out intNumber) &&
intNumber > 0)
{
lblMessage.Text = "Entry ID is valid.";
lblMessage.ForeColor = Color.Green;
btnDeleteEntry.Enabled = true;
}
else
{
lblMessage.Text = "You must enter Entry ID number!";
lblMessage.ForeColor = Color.IndianRed;
btnDeleteEntry.Enabled = false;
}
}
private void btnDeleteEntry_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show
("Are you sure you want to remove this entry?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
// SQL query which will delete entry by using entry ID.
string sql = "DELETE FROM PersonalData WHERE DataID = " +
txtEntryID.Text;
DeleteData(sql);
lblMessage.Text = "Entry was deleted!";
lblMessage.ForeColor = Color.Green;
}
else
{
// Do nothing.
}
}
private void DeleteData(string sql)
{
HashPhrase hash = new HashPhrase();
string hashShortPass = hash.ShortHash(pass);
// Creating a connection string. Using placeholders make code
// easier to understand.
string connectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};
Persist Security Info=False; Jet OLEDB:Database Password={1};";
using (OleDbConnection connection = new OleDbConnection())
{
// Creating command object.
// Using a string formatting let me to insert data into
// place holders I have used earlier.
connection.ConnectionString =
string.Format(connectionString, filePath, hashShortPass);
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
OleDbParameter prmDataID = new OleDbParameter
("#DataID", txtEntryID.Text);
command.Parameters.Add(prmDataID);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
}
To check if the ID already exists, you will need to use SQL just as your delete method does. The following may give you a starting point:
private bool DoesIDExist(string ID)
{
string filePath = ""; //TODO
string hashShortPass = ""; //TODO
DataTable temp = new DataTable();
bool result = false;
string connectionString =""; //TODO
using (OleDbConnection connection = new OleDbConnection(ConnectionString))
{
string sql = #"SELECT * FROM PersonalData WHERE DataID = #DataID";
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
command.Parameters.Add(new OleDbParameter("#DataID", ID));
using (OleDbDataAdapter oda = new OleDbDataAdapter(command))
{
try
{
oda.Fill(temp);
if (temp != null && temp.Rows.Count > 0)
result = true; //ID exists
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
return result;
}

Categories

Resources