I having problems with a user-password coding example - c#

Using this earlier question I need a bit of help
Using the second answer in the above link I had to update it for MySQL
private void btLogin_Click(object sender, EventArgs e)
{
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
using (var con = new MySqlConnection(connectionString));
{
using (var command = new MySqlCommand(connection = con))
{
con.Open();
command.CommandText = #"SELECT level FROM userTable WHERE user=#username, password=#password";
command.Parameters.AddWithValue("#username", lbUser.Text);
command.Parameters.AddWithValue("#password", tbPassword.Text);
var strLevel = command.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
}
}
}
}
Everything looks good BUT this
using (var con = new MySqlConnection(connectionString));
{
using (var command = new MySqlCommand(connection = con))
{
con.Open();
It says that con doesn't exist. I don't know Using that well to see the problem.

The first parameter to the MySqlCommand constructor is the command text. It should work if you change your code to the following:
con.Open();
using (var command = new MySqlCommand())
{
command.Connection = con;
command.CommandText = #"SELECT level FROM userTable WHERE user=#username AND password=#password";

Related

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll in C#

Code :
private void button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlConnection CON = new SqlConnection(#"Data Source(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\stud\Documents\ronak.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand("Select * from Table where username= ' " + textBox1.Text + "' and password= ' " + textBox2.Text + "' ", CON);
SqlDataReader sda = cmd.ExecuteReader();
dt.Load(sda);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
login2 rk = new login2();
rk.Show();
}
else
{
MessageBox.Show("please chack you username and password");
}
}
This code is totally true but I have face some problem.
Your code has quite a number of different issues:
Your connection string is missing = after Data Source
You need to actually open the connection.
Do not use AttachDbFilename instead create and connect to a normal database.
Do not store plain-text passwords. Salt and hash them instead. Then compare the hash server-side, do not return it to the client.
You don't need a DataTable or DataAdapter, you can just use ExecuteScalar to retrieve a single value.
Dispose the connection and command with using.
Do not inject data into your queries. Use parameters instead.
const string query = #"
Select 1
from Table
where username= #username
and password= #password
";
using (var CON = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=ronak;Integrated Security=True;Connect Timeout=30"))
using (var cmd = new SqlCommand(query, CON))
{
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = textBox1.Text;
cmd.Parameters.Add("#password", SqlDbType.VarBinary, 256).Value = SaltAndHashPassword(textBox2.Text, textBox1.Text);
CON.Open();
var exists = cmd.ExecuteScalar() == 1;
CON.Close();
if (exists)
{
this.Hide();
login2 rk = new login2();
rk.Show();
}
else
{
MessageBox.Show("please chack you username and password");
}
}
First of all you forget = after Data source in sqlConnection
Second you are using bad names for variables
Third you dont need to use SqlCommand, you can replace it with SqlDataAdapter its more simple
Fourth you must use ( Using ) to dispose connection
Here`s the full code
private void button2_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\stud\Documents\ronak.mdf;Integrated Security=True;Connection Timeout=30"))
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter($"Select * from Table where username= '{textBox1.Text}' and password= '{textBox2.Text}' ", connection))
{
adapter.Fill(table);
if (table.Rows.Count == 0)
{
MessageBox.Show("please chack you username and password");
return;
}
if (table.Rows[0][0].ToString() == "1")
{
this.Hide();
login2 rk = new login2();
rk.Show();
}
}
}
}

Nested SQL in C#

I tried to adapt the solution from Understanding of nested SQL in C# Reply 4.
But it dont work. I cant find the mistake. Think it is something that the statement cant use a parameter as part of the table name.
string srcqry = #"USE [" + TableName+ "] " +
#"select TABLE_NAME from [INFORMATION_SCHEMA].[TABLES]";
using (SqlConnection srccon = new SqlConnection(cs))
using (SqlCommand srccmd = new SqlCommand(srcqry, srccon))
{
srccon.Open();
using (SqlDataReader src = srccmd.ExecuteReader())
{
string insqry = #"USE [" + TableName+ "] " + "ALTER SCHEMA "+SchemaNameNew+" TRANSFER [dbo].#tabelle";
// create new connection and command for insert:
using (SqlConnection inscon = new SqlConnection(cs))
using (SqlCommand inscmd = new SqlCommand(insqry, inscon))
{
inscmd.Parameters.Add("#tabelle", SqlDbType.NVarChar, 80);
inscon.Open();
while (src.Read())
{
inscmd.Parameters["#tabelle"].Value = src["TABLE_NAME"];
inscmd.ExecuteNonQuery();
}
}
}
}
I got the error that the statement is wrong in the #tabelle area.
Any idea why it wont work?
Thanks
I found a working solution.
while (src.Read())
{
var table= src["TABLE_NAME"];
var con = new System.Data.SqlClient.SqlConnection(cs);
con.Open();
var cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"USE [" + dbname+ "] " + "ALTER SCHEMA " + schemaname+ " TRANSFER [dbo]."+table;
cmd.ExecuteNonQuery();
con.Close();
}

SqlConnection is null but why?

I want to connect to my GuvenliBilgisayarim database. But baglanti is null - why ?
My code is:
SqlConnection baglanti = new SqlConnection("Data Source=DILEKZ\\SQLEXPRESS;Initial Catalog=GuvenliBilgisayarim;Integrated Security=True");
private void btn_giris_Click(object sender, EventArgs e)
{
baglanti.Open();
SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi='" + txt_kulAdi.Text + " and kullanici_sifre=" + txt_sifre.Text +"',baglanti");
komut.Connection = baglanti;
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
Rapor rpr = new Rapor();
rpr.Show();
}
else
{
MessageBox.Show("Kullanıcı adı veya şifre yanlış");
}
dr.Close();
}
Your SqlCommand's Text is invalid. The correct is (notice to the quotes '"):
SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi='" + txt_kulAdi.Text + "'" +
" and kullanici_sifre='" + txt_sifre.Text + "'",baglanti);
However this kind of string concatenation is open for SQL injection. Try parameterized queries instead. Something like this:
SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi=#kulAdi" +
" and kullanici_sifre=#sifre",baglanti);
komut.Parameters.AddWithValue("#kulAdi",txt_kulAdi.Text);
komut.Parameters.AddWithValue("#sifre",txt_sifre.Text);
Although specify the type directly and use the Value property is more better than AddWithValue:
komut.Parameters.Add("#kulAdi", SqlDbType.VarChar).Value = txt_kulAdi.Text;
Can we stop using AddWithValue() already?

Is using multiple Sql connection in a button click in c# in asp.net is efficient?

public void buttonclick(object sender,eventArgs e)
{
SqlConnection con0 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con0.Open();
SqlCommand cmd0 = new SqlCommand("", con0);
con0.Close();
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con1.Open();
SqlCommand cmd3 = new SqlCommand("book_master_insert", con1);
cmd3.CommandType = CommandType.StoredProcedure;
SqlParameter customer_id = new SqlParameter("#customer_id", cust_id);
SqlParameter booking_from = new SqlParameter("#booking_from", ddlfrom.SelectedItem.Text);
SqlParameter booking_destination = new SqlParameter("#booking_destination", ddlto.SelectedItem.Text);
SqlParameter load_type = new SqlParameter("#load_type", ddlLoadtype.SelectedItem.Text);
SqlParameter no_of_containers = new SqlParameter("#no_of_containers", txt_no_of_container.Text);
SqlParameter booking_pickupdate = new SqlParameter("#booking_pickupdate", txt_date.Text);
SqlParameter booking_pickuptime = new SqlParameter("#booking_pickuptime", txt_time.Text);
SqlParameter booking_createdate = new SqlParameter("#booking_createdate", localDate);
cmd3.Parameters.Add(customer_id);
cmd3.Parameters.Add(booking_createdate);
cmd3.Parameters.Add(booking_from);
cmd3.Parameters.Add(booking_destination);
cmd3.Parameters.Add(load_type);
cmd3.Parameters.Add(no_of_containers);
cmd3.Parameters.Add(booking_pickupdate);
cmd3.Parameters.Add(booking_pickuptime);
cmd3.ExecuteNonQuery();
con1.Close();
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con2.Open();
SqlCommand cmd2 = new SqlCommand("select booking_ID from booking_master where customer_id='"+cust_id+"' and booking_from='" + ddlfrom.SelectedItem.Text + "'and booking_destination='" + ddlto.SelectedItem.Text + "' and load_type='" + ddlLoadtype.SelectedValue + "' and no_of_containers='" + txt_no_of_container.Text + "' and CAST (booking_pickupdate as date) ='" + txt_date.Text + "' and booking_pickuptime='" + txt_time.Text + "';", con2);
SqlDataReader rdr = cmd2.ExecuteReader();
while (rdr.Read())
{
booking_ID = rdr["booking_ID"].ToString();
}
con2.Close();
}
Because con0, con1, and con2 are the same, you can write it like this, and please make cmd2 like cmd3, using parameterized query:
using (var conn = new SqlConnection("...Connection String..."))
{
conn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
// Query1
cmd.CommandText = "...Query1...";
cmd.ExecuteNonQuery();
// Query2
cmd.CommandText = "...Query2...";
cmd.ExecuteReader();
}
}
Talking about efficiency first what are you trying to do?
System.Data.SqlClient ( ADO.Net ) re-use connection pooling if it detects new connection is same with the first connection made base on it connectionstring.
Calling multiple SqlConnection doesn't matter as long as you close and dispose it after use. Much better if you wrap it with using() {} statement, but keep in mind that it depend on what you are trying to do or what you requirement is. Open/Close of connection is much cheaper than hold open connection for long time. If you can re-use connection do it like what #x... answers.
It is nothing to do with efficiency but you should AVOID appending user input value in you SQL query. This lead to SQL injection and exploitation like what #mar_s said. Alternatively you can use cmd.Parameters.AddWithValue("#Name", "Bob"); for your safety.
Note : I haven't tested the code :
public void buttonclick(object sender,eventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["BUM"].ConnectionString;
using(SqlConnection con0 = new SqlConnection(connectionString))
{
con0.Open();
using(SqlCommand cmd = new SqlCommand("book_master_insert", con0))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#customer_id", cust_id);
cmd.Parameters.AddWithValue("#booking_from", ddlfrom.SelectedItem.Text);
cmd.Parameters.AddWithValue("#booking_destination", ddlto.SelectedItem.Text);
cmd.Parameters.AddWithValue("#load_type", ddlLoadtype.SelectedItem.Text);
cmd.Parameters.AddWithValue("#no_of_containers", txt_no_of_container.Text);
cmd.Parameters.AddWithValue("#booking_pickupdate", txt_date.Text);
cmd.Parameters.AddWithValue("#booking_pickuptime", txt_time.Text);
cmd.Parameters.AddWithValue("#booking_createdate", localDate);
cmd.ExecuteNonQuery();
// This is a BAD idea and you should replace this using parametrized queries
using(SqlCommand cmd2 = new SqlCommand("select booking_ID from booking_master where customer_id='"+cust_id+"' and booking_from='" + ddlfrom.SelectedItem.Text + "'and booking_destination='" + ddlto.SelectedItem.Text + "' and load_type='" + ddlLoadtype.SelectedValue + "' and no_of_containers='" + txt_no_of_container.Text + "' and CAST (booking_pickupdate as date) ='" + txt_date.Text + "' and booking_pickuptime='" + txt_time.Text + "';", con2))
{
using(SqlDataReader rdr = cmd2.ExecuteReader())
{
while (rdr.Read())
{
booking_ID = rdr["booking_ID"].ToString();
}
}
}
}
}
}

How do I add SQL auth to a C# forms app?

I need to be able to verify a username and password against a sql server and I need code for a C# forms application.
I have it setup with 2 textboxes (1 user and 1 pass) and then I have a login button.
SqlConnection UGIcon = new SqlConnection();
UGIcon.ConnectionString = "Data Source=HP-PC//localhost;Initial Catalog=UGI;Integrated Security=True";
UGIcon.Open();
string userText = textBox11.Text;
string passText = textBox12.Text;
SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword FROM LoginDetails WHERE stUsername='" + textBox11.Text + "' and stPassword='" + textBox12.Text + "'", UGIcon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if ( dt.Rows.Count > 0)
{
MessageBox.Show("Login Success!!");
cmd = new SqlCommand("SELECT stRole from LoginDetails where stUsername=#stUsername", UGIcon);
cmd.Parameters.AddWithValue("#stUsername",userText);
string role = cmd.ExecuteScalar().ToString();
MessageBox.Show(role);
UGIcon.Close();
}
else
{
MessageBox.Show("Access Denied!!");
UGIcon.Close();
}
I'm a real believer in using the "using" statements. You can also save yourself a 2nd query by asking for the stRole variable in the original query. The using blocks will automatically dispose of the objects, so when execution leaves this area, the objects will automatically be cleaned up.
using (SqlConnection UGIcon = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=UGI;Integrated Security=True"))
{
UGIcon.Open();
string userText = textBox11.Text;
string passText = textBox12.Text;
SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword, stRole FROM LoginDetails WHERE stUsername='" + userText + "' and stPassword='" + passText + "'", UGIcon);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
string role = rdr["stRole"].ToString();
MessageBox.Show(role);
}
}
else
{
MessageBox.Show("Access Denied!!");
}
}
}
Pls check this code
SqlConnection thisConnection = new
SqlConnection(#"Server=(local)\sqlexpress;Integrated Security=True;" +
"Database=northwind");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "Select count(*) from UserDetails
WHere UserName = "+txtUsername.text.trim().toLower() + " and Password = " +txtPassword.text.trim().toLower();
Object countResult = thisCommand.ExecuteScalar();
Console.WriteLine("Count of Customers = {0}", countResult);
thisConnection.Close();

Categories

Resources