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

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();

Related

Get values from data table and pass it to label

I want to get the FullName when the user login succesfully and put their FullName to the label
string conn = ConfigurationManager.ConnectionStrings["SystemDatabase"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
sqlconn.Open();
string query = "Select * from UserAccount where Username = '" + txtUsername.Text.Trim() + "' and Password = '" + txtPassword.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query,sqlconn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
FrmPOS frm = new FrmPOS();
frm.Show();
frm.lblCashierName.Text = ?//here i want to display the fullname from the UserAccount table.
this.Hide();
}
I don't know how to get the data from the DataTable. Or is there any other way to do it?
You might use dt.Rows[0]["FullName"].ToString() to get the FullName column from first record.
using (SqlConnection sqlconn = new SqlConnection (conn))
{
sqlconn.Open();
string query = "SELECT * FROM UseAccount WHERE Username = #Username AND Password = #Password";
using (SqlCommand cmd = new SqlCommand(query, sqlconn)
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Username", txtUsername.Text.Trim());
cmd.Parameters.AddWithValue("#Password", txtPassword.Text.Trim());
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt != null || dt.Rows.Count > 0)
{
FrmPOS frm = new FrmPOS();
frm.Show();
frm.lblCashierName.Text = dt.Rows[0]["FullName"].ToString();
this.Hide();
}
}
}
}
Anyway, I would like to enhance your source code for some best practices
Apply using block to SqlConnection, SqlCommand, and SqlDataAdapter. Thus when each process ends, the using block will perform Dispose to release resources.
Apply SqlCommand with Parameters (a.k.a Parameterized query) as your way could lead to SQL Injection by concatenating the value into command.
Checking DataTable to ensure it has record(s) then only proceed; aims to solve possible NullReferenceException happened when no data return.
You can try this
string conn = ConfigurationManager.ConnectionStrings["SystemDatabase"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
sqlconn.Open();
string query = "Select * from UserAccount where Username = '" + txtUsername.Text.Trim() + "' and Password = '" + txtPassword.Text.Trim() + "'";
SqlCommand command = new SqlCommand(query,sqlconn);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read() == true)
{
FrmPOS frm = new FrmPOS();
frm.Show();
frm.lblCashierName.Text = reader["FullName"].ToString();
this.Hide();
}

How to open next form base on select query base on flag

I am creating one application my requirement is what when column name Status is N in Registration table, then current form should hide and Login form should be open.
If Status is not N then its should be open Registration_Form. I'm trying but it's causing
Error creating window handle
on the rf.Show() call.
on insert button code
string status = "Y";
//Random random = new Random();
//int randomNumber = random.Next(0, 100);
string random1 = System.Web.Security.Membership.GeneratePassword(10, 0);
string concate = textBox1.Text + "-" + textBox2.Text + "-" + textBox3.Text.Substring(textBox3.Text.Length - 4) + "-" + random1;
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string SqlString = "Insert Into Registration (Name,Last_Name,Contact_No,Address,Insert_Date,Registration_key,Status) Values (?,?,?,?,?,?,?)";
//using (OleDbCommand cmd = new OleDbCommand(SqlString, con))
//{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Last_Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Contact_No", textBox3.Text);
cmd.Parameters.AddWithValue("#Address", textBox4.Text);
cmd.Parameters.AddWithValue("#Insert_Date", textBox5.Text);
cmd.Parameters.AddWithValue("#Registration_key", concate);
cmd.Parameters.AddWithValue("#Status", status);
//}
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully,NOW PLEASE ACTIVATE APPLICATION PUTTING ACTIVATE KEY ", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
on update button code --
string Status = "N";
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string recover = "SELECT Registration_key from Registration where Registration_key='" + textBox6.Text + "'";
OleDbCommand cmd = new OleDbCommand(recover, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox6.Text = reader["Registration_key"].ToString();
if (con.State == ConnectionState.Open)
{
con.Close();
}
string cmd1 = "update Registration set Status=#Status where Registration_key=#Registration_key";
cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#Registration_key", textBox6.Text);
con.Open();
int n2 = cmd.ExecuteNonQuery();
con.Close();
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Invalid Activated Key", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
con.Close();
on load event--
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
i got a solution i remove e
lse if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
this and instead that normal use else condition
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Pls Register yourself");
}
this code giving me what requirement i want

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

Why won't my labels stay changed

when i run my code the labels stay the same but when i debug it i can see the text changes and then changes back when it is done runnning
public void getData(string a)
{
SqlConnection conn = new SqlConnection(#"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = reader["UserID"].ToString();
label2.Text = reader["UserName"].ToString();
label3.Text = reader["Email"].ToString();
}
conn.Close();
}
Just in case, try this:
public void getData(string a) {
SqlConnection conn = new SqlConnection(#"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
SqlDataReader reader = command.ExecuteReader();
string id, name, email;
while (reader.Read())
{
id = reader["UserID"].ToString();
name = reader["UserName"].ToString();
email = reader["Email"].ToString();
}
conn.Close();
label1.Text = id;
label2.Text = name;
label3.Text = email;
}
}
Hope, it helps.

Display SQL query result in a label in asp.net

I'm trying to display the SQL query result in a label but it's not showing. This is my code:
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
showresult.ExecuteNonQuery();
string actresult = ((string)showresult.ExecuteScalar());
ResultLabel.Text = actresult;
conn.Close();
Need help please. Thanks!
Try this one.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
Is there a typo in there? You have two calls to the database:
showresult.ExecuteNonQuery();
This won't return a value and I'm not sure why you would have it there
string actresult = ((string)shresult.ExecuteScalar());
Unless you have a shresult variable, this query should error. What is the shresult variable?
Use SqlParameter to filter the result and call ExecuteScalar() or ExecuteReader() method.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID=#ID";
SqlCommand showresult = new SqlCommand(result, conn);
// If ID is int type
showresult.Parameters.Add("#ID",SqlDbType.Int).Value=ID.Txt;
// If ID is Varchar then
//showresult.Parameters.Add("#ID",SqlDbType.VarChar,10).Value=ID.Txt;
conn.Open();
string actresult = (string)showresult.ExecuteScalar();
conn.Close();
if(!string.IsNullOrEmpty(actresult))
ResultLabel.Text = actresult;
else
ResultLabel.Text="Not found";
using (SqlConnection conn = new SqlConnection(connectionString))
{
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = #id";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.Parameters.AddWithValue("id", ID.Text);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
}
This will dispose the connection and has no string concatenation in the query.
conn.Open();
string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.ExecuteNonQuery();
int actresult = ((int)showresult.ExecuteScalar());
ResultLabel.Text = actresult.Tostring();
conn.Close();

Categories

Resources