Not sure why I get an error every single time i try to connect. I tried so many things. When i type the wrong password while connecting manually it says access not granted or whatever so I know it connects but when it connects I get this weird error.
An unhandled exception of type
'System.Collections.Generic.KeyNotFoundException' occurred in
mscorlib.dll Additional information: The given key was not present in
the dictionary.
For localhost it works when I have this connection string.
server=localhost; port=3306; USER ID=root; password=***; database=database;
but when I change the server user id and password it decides to not work.
The exception is thrown at cn.Open();
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection cn = new MySqlConnection();
cn.ConnectionString = "server=db4free.net ;port=3306;
user=goof; password=pwd; database=s;";
cn.Open();
MySqlCommand cmd = new MySqlCommand("select * from users where
username = '"
+ textBox1.Text + "',
and password = '"
+ textBox2.Text + "'", cn);
MySqlDataReader dr;
dr = cmd.ExecuteReader();
int count = 0;
while(dr.Read())
{
count += 1;
}
if(count == 1)
{
MessageBox.Show("success");
}
else
{
MessageBox.Show("error");
}
}
The problem is the user=goof field should be user id=goof.
Change your connection string into this:
cn.ConnectionString = "server=db4free.net ;port=3306; USER ID=goof; password=pwd; database=s;";
try using "user id" or "uid" instead of just "user" and let us know if its does the job!
Related
I'm trying to make it so i can use username/password i've set in the properties/settings to connect to mysql as i dont want to store mysql details in plaintext here what i'm using but not sure how to go about reading the username/password from properties, Could anyone help? thanks
private void PassTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
try
{
string MyConnection = "datasource=localhost;port=3309;username=user;password=pass123";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand("select * from applogin.users where UserId='" + this.UserTextBox.Text + "' and UserPassword='" + this.PassTextBox.Text + "' ;", MyConn);
MySqlDataReader MyReader;
recby = UserTextBox.Text;
MyConn.Open();
MyReader = MyCommand.ExecuteReader();
int count = 0;
while (MyReader.Read())
{
Console.WriteLine(MyReader[count]);
count++;
}
if (count == 1)
{
MessageBox.Show("Accepted, Welcome!");
this.Hide();
Form5 f5 = new Form5();
f5.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and passwor.\nAccess denied.");
}
else
{
MessageBox.Show("Username and password is incorrect.\nPleas try again.");
}
MyConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
bool flag=false;
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar()+"");
flag=true;
//close Connection
this.CloseConnection();
return flag;
}
else
{
return flag;
}
}
}
I would rather recommend to read password from an environment variable instead of hardcoding it in the code.
This is a broad topic.
Mainly, it is "how to store a 'secret' well?"
I'll give some hints.
First, in dotnet CORE, there is new stuff.
https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-3.1&tabs=windows
That is for local development, BUT AT LEAST forces you to think about where that secret is being stored.
Using .ini, .config, .txt files and keeping a secret in plain text IS NOT secure for production scenarios.
So then you have to start thinking about "how is my code deployed?"
If you are deploying to Azure, there is Azure Key Vault.
If you are deploying to a machine/VM, then you have to consider something more robust, like Hashicorp Vault.
But you're going to get a few "quick fix" answers. You need to really consider where you keep this secret for your deployed code.
If I read your question correctly, you don't care about the connection string userid/password but about the users login credentials.
This is based on your line:
MySqlCommand MyCommand = new MySqlCommand("select * from applogin.users where UserId='" + this.UserTextBox.Text + "' and UserPassword='" + this.PassTextBox.Text + "' ;", MyConn);
And it appears you are asking about how to encrypt the password so that someone can't monitor the communication. Of course, your connection string is already an issue, but back to what I believe is your question.
It's not clear if you are using the actual user name and password as entered or not. If so, the easiest option is to use 1 way encryption - and only store the encrypted values. Then your code would get the value of the textbox and encrypt it. Then execute a query with the encrypted value (preferably with those encrypted values as parameters, not inline text.)
The result would be a query that might look like:
select * from applogin.users where UserId='kajsdf09823rcfs98dsjssdf' and UserPassword='j;las9onq;p;9wf;kjadf' ;
and written correctly (assuming you have a method named encrypt that implements whatever encryption you choose):
userId = new SqlParameter("#userName", encrypt(this.UserTextBox.Text));
userpw = new SqlParameter("#userPw", encrypt(this.PassTextBox.Text));
cmd.Parameters.Add(userId);
cmd.Parameters.Add(userpw );
cmd.CommandText = "select * from applogin.users where UserId=#userName and UserPassword=#userPw ;";
There are other great suggestions as well, I encourage you to follow up on those as well.
I am creating a user login for my software which is connected to Access, I keep on getting the same error which highlights the line ' i = (int)command.ExecuteScalar();' saying...
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error (missing operator) in query expression 'Username= 'MGRjs' AND Password 'Candy''.
private void LoginButton_Click(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\Loughborough\3rd Year\Individual Project\StockManagement system\Database.accdb");
OleDbCommand command = new OleDbCommand();
int i = 0;
if (IDtbx.Text == string.Empty)
{
MessageBox.Show("Please log in");
}
command = new OleDbCommand("select count(*)from NewUser where Username= '" + IDtbx.Text + "' AND Password '" + PSWtbx.Text + "'", connection);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
i = (int)command.ExecuteScalar();
}
connection.Close();
if (i > 0)
{
MainSystem mainForm = new MainSystem();
mainForm.FormClosed += new FormClosedEventHandler(Login_FormClosed);
mainForm.Show();
this.Hide();
LoginError.Visible = false;
}
else
{
LoginError.Visible = true;
}
}
Your SQL is wrong so your database is raising and error.
select count(*)from NewUser where Username= 'blablalbla' AND Password 'whatever'
You are missing the = between the password and the value.
BTW, your code is prone to SQL Injection, please consider using parametrized queries yo avoid security flaws,
I have been searching for the better part of the morning looking to figure out a way to get a simple login form for a program I am writing for work.
The things that I need for this:
1: User login form
2: Authenticate Usernames and passwords inputed on the form
3: Secure the password string so that it can not be read as plain text.
4: Make it so that Admin users can add other users into the Database.
I can't even get the login form to work correctly let alone the rest of the stuff. Everything that I look at online keeps throwing an error when I click the login button
Error code:
SqlException Occured
Exception thrown "System.Data.SqlClient.SqlException' in System.Data.dll
Additional Information:
Invalid object name 'Login'
I have found where this is at and I do not understand what it is doing or referencing, here is the code for the btnLogin_Click
private void btnLogin_Click(object sender, EventArgs e)
{
{
string USERNAME, PASSWORD;
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\turner.m\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
USERNAME = txtUserName.Text;
PASSWORD = txtPassword.Text;
SqlCommand cmd = new SqlCommand("select USERNAME,PASSWORD from Login where USERNAME='" + txtUserName.Text + "'and PASSWORD='" + txtPassword.Text + "'", con);
//cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (txtUserName.Text == dr[0].ToString() && txtPassword.Text == dr[1].ToString())
{
txtUserName.Text = "";
txtPassword.Text = "";
this.Hide();
}
else
{
MessageBox.Show("invalid userid or password");
}
dr.Close();
con.Close();
}
}
}
Attach (open) mdf file database with SQL Server Management Studio
Then run your query:
select USERNAME,PASSWORD
from Login
where USERNAME= 'foo'
and PASSWORD= 'bar'
Probably your SQL will not execute because your TableName is not valid.
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Could not use ''; file already in use
This is where the error points at:
da.Fill(dt);
The database is located at C:\ChattBankMDB.mdb on my computer.
Database: http://puu.sh/hjQj0/d86ede4c00.png
When I press the button1, I would like for the form to follow up and login on the Customer database else a messagebox.show will say failure to login.
Button on form:
public partial class CustLogin : Form
{
OleDbConnection db = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\ChattBankMDB.mdb");
OleDbDataAdapter da = new OleDbDataAdapter();
DataTable dt = new DataTable();
public CustLogin()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
da = new OleDbDataAdapter("Select CustID, CustPassword From Customers", db);
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
if (UserText.Text == dt.Rows[i]["CustID"] && PassText.Text == dt.Rows[i]["CustPassword"])
{
WelcomeCust f = new WelcomeCust();
this.Hide();
f.Show();
}
else
{
MessageBox.Show("FAILURE TRY AGAIN");
}
}
}
I've noticed a couple of potential issues:
Database Injection.
Password in plain text.
Utilizing SqlConnection.
A .mdb isn't a SQL database, it is actually a Microsoft Access database. So you'll want to actually use ADO.NET connection. So your code should actually be:
private readonly string dbConnection = ConfigurationManager.ConnectionStrings["..."].ConnectionString;
private const string query = "SELECT * FROM [Example] WHERE ([Id] = #Id);";
public void Example()
{
using(var connection = new OleDbConnection(dbConnection))
using(var command = new OleDbCommand(query, connection))
{
// Apply parameter, open connection, etc.
}
}
You utilize parameters to avoid a sub-query being introduced. As for your password in plain text you should take a look at BCrypt or another library for a Salt / Hash approach.
Then the change to the connection should alleviate your issue.
Your next issue I believe stems from the Fill being before you build your data table.
The database is an Acces database , so you need to use OleDB to connect to it.
Moreover, the query can cause errors.
Replace :
("Select* from Customers where CustID ='" + UserText.Text +"'
and CustPassword =" + PassText.Text + '"', conn)
By :
("Select * from Customers where CustID = '" + UserText.Text + "'
and CustPassword = '" + PassText.Text + "'", conn);
I'm getting a "Syntax error in UPDATE statement" error when I run the following Access statements. How do I get past that?
This is the relevant portion of my web page code.
protected void Button1_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\\Users\\Prasat PVS\\Documents\\db.mdb";
string q1 = "SELECT * FROM users WHERE password ='" + TextBox1.Text + "'";
string q2 = "UPDATE users SET password='"+TextBox2.Text+"' WHERE password='"+TextBox1.Text+"'";
using (OleDbConnection con = new OleDbConnection(connect))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand(q1, con))
{
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
using (OleDbConnection con1 = new OleDbConnection(connect))
{
con1.Open();
using (OleDbCommand cmd1 = new OleDbCommand(q2, con1))
{
cmd1.ExecuteNonQuery();
}
Label1.Text = "Your Password Has Been Changed Successfully";
con1.Close();
con.Close();
}
}
else
{
Label1.Text = "Your Password Is Incorrect Try Again";
}
}
}
}
maybe the problem is because you have used password as name for password field... instead use pass or something other
My bet is that your password has an apostrophe in it. If that's the case, you'll have something like UPDATE users SET password = 'pass'word'... which is pretty clearly the wrong syntax. That's the most likely thing I can see that could be causing an error like that.
Yet another point to parameterizing your queries...
And while you're at it, I mentioned this in a comment, but you'd be much better to only run one query (your update, after you add in a check for the username) and check the result of ExecuteNonQuery to know whether any rows were affected (the password changed successfully) or not (the username or password was incorrect).