MySQL - C# - System.FormatException Error - c#

I decided to create an application that connects to an MySQL server but it seems that there is a problem with my code.
public partial class FRM_LOGIN : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public FRM_LOGIN()
{
InitializeComponent();
}
private void BTN_CONNECT_Click(object sender, EventArgs e)
{
server = "localhost";
database = "databasenamehere";
uid = "root";
password = "root";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";old guids=true;";
connection = new MySqlConnection(connectionString);
try
{
if (TXTBOX_USERNAME.Text == "" || TXTBOX_PASSWORD.Text == "")
{
MessageBox.Show("Please fill up all the fields of the login form.");
}
else
try
{
connection.Open();
MySqlCommand com = new MySqlCommand("SELECT * FROM tbl_login WHERE (user_id=#id AND user_password=#pwd)", connection);
com.Parameters.Add(new MySqlParameter("id", SqlDbType.NVarChar)).Value = this.TXTBOX_USERNAME.Text;
com.Parameters.Add(new MySqlParameter("pwd", SqlDbType.NVarChar)).Value = this.TXTBOX_PASSWORD.Text;
MySqlDataReader myReader = com.ExecuteReader();
myReader.Read();
if (myReader.HasRows == true)
{
MessageBox.Show("Login Successfull", "Login Information");
this.Hide();
FRM_MAIN frm_main = new FRM_MAIN();
frm_main.Show();
}
else
{
MessageBox.Show("Invalid User Name or Password", "Hello", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
connection.Close();
}
catch (MySqlException ex)
{
throw;
}
}
catch (MySqlException ex)
{
{
case 0:
MessageBox.Show(ex.Message);
MessageBox.Show("Cannot connect to server. Contact administrator", " Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case 1045:
MessageBox.Show(ex.Message);
MessageBox.Show("Invalid username/password, please try again");
break;
}
}
}
}
ALOT of it is patch work from various answers from here and some tutorials, so please don't judge, complete newbie here.
So as most of you can tell, i have a form with 2 textboxes and a button. My goal was to authenticate the user by using finding out if the credentials are in the table tbl_login. If there are results, close form1 open another form.
My problem at the moment is that every time I click the button an exception is thrown.
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll
{"Input string was not in a correct format."}
and it points me out to the
MySqlDataReader myReader = com.ExecuteReader();
Any ideas why this keeps on happening? Any help would be greatly appreciated.

Related

Unable To establish an oracle connection from c# form Application

Im trying to pass two parameters to my oracle package.
I can get the parameters, but it is not being passed into the database. Every time I run the application it fails to make a connection and goes straight to my try catch method.
Is there something I am doing wrong?
This is what I have so far:
using System.Data.OracleClient;
private void btnGetData_Click(object sender, EventArgs e)
{
GetOrders_OracleCon_GetData(Parameter1,Parameter2);
// when i output or add in a break i can see that the data does come into the Parameter values. However after that it doesnt go to my db
}
public void GetOrders_OracleCon_GetData(Int32 PM1, String PM2)
{
using (OracleConnection objConn = new OracleConnection("Data Source=" + dbcon + "; User ID=" + uid + "; Password=" + pass))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "PCK_Orders.get_data";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("pm1", OracleType.Number).Value = PM1;
objCmd.Parameters.Add("pm2", OracleType.VarChar).Value =PM2;
objCmd.Parameters.Add("selected_orders", OracleType.Cursor).Direction = ParameterDirection.Output;
try
{
objConn.Open();
OracleDataReader objReader = objCmd.ExecuteReader();
if (objReader.HasRows)
{
GetOrders_GetData(objReader);
btnCancel.Enabled = true;
}
else
{
Timer_ProgBar.Stop();
MessageBox.Show("Orders for this Datedoes not exist", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
GP_ClearAllFields("Y", "Y");
Timer_ProgBar_Initialize(0, "");
}
}
catch (Exception)
{
Timer_ProgBar.Stop();
MessageBox.Show("An error has occured");
// this is the error that i catch but im not sure what is causing it. am i missing something?
Timer_ProgBar_Initialize(0, "");
}
objConn.Close();
}
}

C# How To Separate Login For Admin And User

So basically Admin and User goes to different windows, here's the code
private void cmdEnter_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "" && txtPassword.Text == "") //Error when all text box are not fill
{
MessageBox.Show("Unable to fill Username and Password", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (txtUsername.Text == "") //Error when all text box are not fill
{
MessageBox.Show("Unable to fill Username", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (txtPassword.Text == "") //Error when all text box are not fill
{
MessageBox.Show("Unable to fill Password", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
try
{
string myConnection = "datasource=localhost;port=3306;username=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("select * from boardinghousedb.employee_table where username='" + this.txtUsername.Text + "' and password='" + this.txtPassword.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username and Password . . . is Correct", "Confirmation Message", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Hide();
Menu mm = new Menu();
mm.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and Password . . . Access Denied", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Username and Password is Not Correct . . . Please try again", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
myConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
but I don't know how, other tutorials talks about local database but I'm using MySQLHere is the employee table, title=admin or user
You have several problems with your code.
you should create unique constraint in your database to avoid users with duplicate usernames
You should keep your passwords hashed, rather than in plain text. This way, if someone gets to your database, he will still not be able to read passwords.
You should use SQL Parametrzided queries to avoid SQL Injection.
Your query is prone to SQL Injection. SQL Injection is a way of injecting SQL Commands in to your query. Some user could write someName' OR 1=1-- in your username textbox, and your query would translate as select * from boardinghousedb.employee_table where username='someName' OR 1=1--. Note the -- in the end, which makes rest of the query commented out. You can read more at this link. If you are allowed, i suggest you to look in to the EntityFramework. It's really powerful tool for querying your database.
Use finally block after catch to close your db connections.
Related to your question, if you want to distinguish admin from user, you need to introduce some kind of role, or at least bool value where you state IsAdmin for that user.
You can then place your code to a separate function/functions/classes, depending on your needs, and query users with WHERE Role='Admin' or similar.
For an example
public bool IsValidLogin(string username, string password);
or
public bool IsValieLoginForAdmin(string username, string password);
or any other implementation you like.
And then re-use it in a following way:
private void cmdEnter_Click(object sender, EventArgs e)
{
if(IsValidLogin("username", "password"))
//or
if(IsValidLoginForAdmin("username", "password"))
//do something
}
EDIT:
You could also introduce new column to your table, caled UserRole. For the simplicity, I will just modify your code as it is, and you can re-factor it as you learn.
MySqlCommand SelectCommand = new MySqlCommand("select * from boardinghousedb.employee_table where username='" + this.txtUsername.Text + "' and password='" + this.txtPassword.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
string userRole = string.Empty;
while (myReader.Read())
{
count = count + 1;
userRole = myReader["UserRole"].ToString();
}
if (count == 1)
{
MessageBox.Show("Username and Password . . . is Correct", "Confirmation Message", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Hide();
if(userRole =="Admin")
//show admin window
else
//show user window
Menu mm = new Menu();
mm.ShowDialog();
}
MySqlCommand SelectCommand = new MySqlCommand("select * from boardinghousedb.employee_table where username='" + this.txtUsername.Text + "' and password='" + this.txtPassword.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
string userRole = string.Empty;
while (myReader.Read())
{
count = count + 1;
userRole = myReader["UserRole"].ToString();
}
if (count == 1)
{
MessageBox.Show("Username and Password . . . is Correct", "Confirmation Message", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Hide();
if(userRole =="Admin")
//show admin window
else
//show user window
Menu mm = new Menu();
mm.ShowDialog();
}
else if (count > 1)
{ MessageBox.Show("Duplicate User And Password"); }
else
MessageBox.Show("Username and Password Incorrect", "Login Error:");
myConn.Close();
}
your code
if (txtUsername.Text == "" && txtPassword.Text == "") //Error when all text box are not fill
{
MessageBox.Show("Unable to fill Username and Password", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (txtUsername.Text == "") //Error when all text box are not fill
{
MessageBox.Show("Unable to fill Username", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (txtPassword.Text == "") //Error when all text box are not fill
{
MessageBox.Show("Unable to fill Password", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
try
{
string myConnection = "datasource=localhost;port=3306;username=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("select * from boardinghousedb.employee_table where username='" + this.txtUsername.Text + "' and password='" + this.txtPassword.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username and Password . . . is Correct", "Confirmation Message", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Hide();
Menu mm = new Menu();
mm.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and Password . . . Access Denied", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Username and Password is Not Correct . . . Please try again", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
myConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
this code has missing its return type the error says

C# - Multiple Users from SQL Database for Login Form

So, I have a loginform where a user has to login to go into the mainform.
I have a database with a table created to store usernames and passwords, for logging in to the application.
If the user types in the correct username and password and clicks login, it should take him/her to the mainform. This I know how to do, but how do I get the usernames and passwords from the SQL database and check if they exist, and if they exist, is it the correct username for the correct password or vice versa?
Like I said, I created a SQL database to store usernames and passwords.
I then saved a user with the username and password both as "admin", just for testing purposes.
I tried this following code, but it isn't letting me log in even though I typed the correct username and password.
string username;
string password;
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
SqlCeConnection con = new SqlCeConnection(#"connectionString");
SqlCeCommand com = new SqlCeCommand("SELECT username, password FROM UsersPass WHERE username = '" + txtUsername.Text + "' AND password = '" + txtPassword.Text + "'", con);
con.Open();
if (con.State == ConnectionState.Open)
{
SqlCeDataReader dtr = com.ExecuteReader();
while (dtr.Read())
{
username = dtr["username"].ToString();
password = dtr["password"].ToString();
if (username == txtUsername.Text && password == txtPassword.Text)
{
Mainform frm = new Mainform();
frm.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid credentials!\nPlease enter a valid username and password to continue.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
catch (Exception)
{
MessageBox.Show("Erorr", "Error");
}
}
Forgive me if I'm missing something completely obvious, I'm fairly new to C#.
Thank you in advance.
You say you are getting the error message. Start by giving yourself more information on that. Either place a breakpoint in
catch (Exception)
{
MessageBox.Show("Erorr", "Error");
}
so you can see some details on the exception or change it to
catch (Exception ex)
{
MessageBox.Show("Erorr", ex.Message + Environment.NewLine + ex.StackTrace);
}
That will give you details on exactly why your application is failing and set you on a path towards getting things working like you want.
I suspect you have a bad connection string.
Edit: This particular issue was caused by sql server compact edition references being used in place of standard edition references. See the comments.
Simply another way in that:
private void btnLogin_Click(object sender, EventArgs e)
{
string currentUserID=string.Empty;
SqlConnection connection= new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT UserID From UserPass WHERE username =#username AND password =#password";
command.Parameters.AddWithValue("#username", txtUsername.Text);
command.Parameters.AddWithValue("#password", txtPassword.Text);
command.Connection = connection;
object obj=command.ExecuteScalar();
if (obj!=null)
{
currentUserID= obj.ToString();
connection.Close();
Mainform frm = new Mainform();
frm.Show();
this.Hide();
}
else
{
connection.Close();
MessageBox.Show("Invalid credentials!\nPlease enter a valid username and password to continue.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Select MySQL Data in C#

I want to login to the program using c#, with my username and password that's stored to the SQL Database in phpmyadmin.
This is what I have so far.
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection connection;
string server = "localhost";
string database = "login";
string uid = "root";
string password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
connection.Close();
Form1 frm = new Form1(this);
frm.Show();
Hide();
}
else
{
MessageBox.Show("Database Connection Failed", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
catch (Exception ex)
{
MessageBox.Show("An Error Occured, Try again later.", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
It connects to the database, however I don't want it to show the form1 Until both a valid Username and Password have been entered.
I'm guessing I need to use SELECT * FROM but I'm not exactly sure how to go about it.
You can use this way to see if username and password match
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = #username and password=#password";
command.Parameters.Add("#username", txtUserName.Text);
command.Parameters.Add("#password", txtPassword.Text);
var count = cmd.ExecuteScalar();
if(count>0)
//Logged In
Just to say, if you use a query like
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = '"+txtusernam +"'";
You will be open to SQL Injection
Warning
As Steve mentioned in comments Passwords in clear text are a vulnerability of the same magnitude of string concatenation
you make try this one
using(var con = new MysqlConnection{ ConnectionString = "your connection string " })
{
using(var command = new MysqlCommand{ Connection = con })
{
con.Open();
command.CommandText = #"SELECT level FROM userTable WHERE username=#username, password=#password";
command.AddWithValue("#username", txtusername.Text);
command.AddWithValue("#password", txtpassword.Text);
var strLevel = myCommand.ExecuteScalar();
if(strLevel == DBNULL.Value || strLevel == Null)
{
MessageBox.Show("Invalid username or password");
return;
}
else
{
MessageBox.Show("Successfully login");
hide(); // hide this form and show another form
}
}
}
use below Query
Select * from UsersTable Where Username='"+username+"' AND password='"+password+"'
Then you can make a if condition that if your query contain a result (rows) then users authenticated (exists in Table)
Note:Select query may fetch multiple users having same userName and
password, its upto you to keep usersname unique in table

C# - Why is MySQL Server slow in my server machine?

I developed a POS like application and during testing with 2 PCs I didn't encounter any problems with the speed. It's just a simple LAN cable setup between 2 computers. But when I deployed it in a client, it ran slow.
The client has 1 PC serving as the admin and the main server, and there are 2 more PCs serving as the cashier. All connected in a router. The cashiers are connected to the admin's PC (main server) to retrieve, insert, update and delete data. I just want to ask if there are processes that needs to be done in MySQL or are there anything wrong with my codes when connecting to the database.
Here's my sample code for connecting to the database, I doubt having problems with it as this has been the standard in connecting to a database and adding records. Just in case I might bore you with codes, you can simply jump to the second code I posted, I have a comment there asking if the initialization of my class is correct. Thanks everyone!
class DBConnection
{
private MySqlConnection connection;
private MySqlCommand cmd;
private MySqlDataReader dr;
private DataTable tbl;
private MySqlDataAdapter da;
private DataSet ds;
private string connectionString;
private string server;
private string database;
private string uid;
private string password;
private frmNotifOk myNotification;
public DBConnection()
{
Initialize();
}
private void Initialize()
{
server = "CASHIER";
database = "sampledb";
uid = "root";
password = "samplepassword";
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server.");
break;
}
return false;
}
}
private void CloseConnection()
{
try
{
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
public void AddRecord(String DBQuery, bool showNotif)
{
string query = DBQuery;
bool notify = showNotif;
try
{
if (this.OpenConnection() == true)
{
cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
if (notify)
{
MessageBox.Show("Item successfully added.");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
this.CloseConnection();
}
}
And finally, here's how I use the method in a form:
public partial class frmNewCashier : Form
{
private DBConnection dbConnect;
string sampleDataSource= "SELECT * FROM SampleTable";
public frmNewCashier()
{
InitializeComponent();
//Is this the correct place of initializing my DBConnection class?
dbConnect = new DBConnection();
}
private void frmCashier_Load(object sender, EventArgs e)
{
try
{
dgvSearchItems.DataSource = dbConnect.DatabaseToDatagrid(dgvSearchItemsDataSource);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
I put the initialization of DBConnection class in public frmNewCashier(), is this the correct place or should I put it in Load event or somewhere? I'm thinking if this has bearing to the slowness of database. Aside from this question, do you know anything that I might have missed that causes the slowness?
class DBConnect
{
public MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
public void Initialize()
{
server = "localhost";
database = "db_sea_horses";
uid = "root";
password = " " ;
//password = "123";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
public bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{ //0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
public bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
class DBmethods : DBConnect
{
DataSet dataset2;
public void input_sql(string query)
{
try
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
int x = cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
catch(MySqlException myex)
{
MessageBox.Show(ex.Message);
}
}
///////////////////////////////////////////////
///// select
/////////////////////////////////////////////
public DataSet output_sql(string query,String table_name)
{
//Open connection
this.OpenConnection();
DataSet dataset = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, connection);
adapter.Fill(dataset, table_name);
//close Connection
this.CloseConnection();
//return list to be displayed
return dataset;
}
}
}
method calling example
1) insert / update / delete statement
DBmethods dbm = new DBmethods();
dbm.input_sql(" you can excute insert / update / delete query");
2) select statement
DataSet ds = dbm.output_sql("select * from storage_bunkers where job_id LIKE '%" + itemname.Text + "%' ", "storage_bunkers");
DataView myView = ((DataTable)ds.Tables["storage_bunkers"]).DefaultView;
dataGridView1.DataSource = myView;
First, try pinging from client machine to server which has installed SQL server. If it is taking too much time then there's problem with network connection.
If not, put a debug point and try debugging then identify the location that taking too long. Then you will able to get a answer.
Also, do not forget to close each and every db connection after using that.

Categories