Login form in ASP.net does not work - sql

I'm new to ASP.net and currently failing to create a simple functioning login form. After establishing the connection to my database, I wanted the function to check whether a given combination of username and password exists in the database. Due to the fact that I have not created the "member zone" page yet, It's supposed to do nothing if the data is valid and return "Login failed" in the opposite case. For some reason, it doesn't work. I would be glad if someone could help me trace the problem.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT * FROM users WHERE username='" + UserName.Text +
"' AND password='" + Password.Text + "' ";
SqlCommand cmd = new SqlCommand(query, con);
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
Response.Write("Login failed.");
}

You have SELECT * FROM in the query and you are using ExecuteScalar method to check if anything is returned.
You should use SELECT COUNT(*) FROM to get the number of rows exist in the table for given username and password.
Another thing which is not right in your code is the generation of query. Using parameterized query is the most recommended approach.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}
This should resolve your issue.

You forgot to open connection before executing ExecuteScalar()
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
//Add Below line and test your code.
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}

Related

I am updating Image fields in my SQL table using Asp.net. It give me a multi-part Identifier bound error

I am storing the users current Identity in the user name variable, and using that variable to compare inside the query!
protected void btnUpload_Click(object sender, EventArgs e)
{
string constr = "Data Source=Talhamalik\\sqlexpress;Initial Catalog=Moodee;Integrated Security=True";
int length = FileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[length];
FileUpload1.PostedFile.InputStream.Read(pic, 0, length);
string Username = Page.User.Identity.Name.Trim();
using (SqlConnection con = new SqlConnection(constr))
{
try
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
//calling connection method
//inserting uploaded image query
SqlCommand com = new SqlCommand("Update Users Set Image=#Image, ImageName =#Name where [Email] =" + Username, con);
com.Parameters.AddWithValue("#Image", pic);
com.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
}
}
finally
{
con.Close();
}
}
}
I think you need to surround username with quotes
Try this
SqlCommand com = new SqlCommand("Update Users Set Image=#Image, ImageName =#Name
where [Email] ='" + Username+"'", con);
Why not use a parameter for the username value as well, it will protect you against sql-injection,,,,,, something like....
SqlCommand com = new SqlCommand("Update Users Set Image=#Image, ImageName =#Name where [Email] = #Username", con);
com.Parameters.AddWithValue("#Image", pic);
com.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
com.Parameters.AddWithValue("#Username", Username);
com.Connection = con;

How do I print SQL query using MessageBox in C#

I am stuck with this problem since yesterday. I have created a button, which when clicked display the results from a SQL Server table. I thought of using MessageBox to print these results or if there is any other way to print results?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * FROM Products", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
command.ExecuteNonQuery();
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
I have tried different methods but it never worked.. I am really stuck. If you want more details, let me know. Thanks for the help in advance
Add a datagridview control to show multiple rows and try this code and rename it what you want and replace this YourDataGridVeiwName from the name you set for datagridview control and try below code
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
sda.Fill(dt);
YourDataGridVeiwName.DataSource= dt;
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
You need to use the SqlDataReader and iterate over the rows returned, extract what you need from each row, and then display that to the enduser.
I modified your code a bit, to make it safer (using blocks!), and I modified the query to return only the product name (assuming you have that) since you cannot really display a whole row in a message box....
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string productName = reader.GetFieldValue<string>(0);
MessageBox("Product is: " + productName);
}
reader.Close();
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}

Retrieve SQL Statement Does Not Go Into While Loop

I am having problem when doing retrieve function in 3-tier in C#. Here is the codes:
public DistributionStandardPackingUnits getSPUDetail(string distributionID)
{
DistributionStandardPackingUnits SPUFound = new DistributionStandardPackingUnits();
using (var connection = new SqlConnection(FoodBankDB.connectionString))
{
SqlCommand command = new SqlCommand("SELECT name, description, quantity FROM dbo.DistributionStandardPackingUnits WHERE distribution = '" + distributionID + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
string name = dr["name"].ToString();
string description = dr["description"].ToString();
string quantity = dr["quantity"].ToString();
SPUFound = new DistributionStandardPackingUnits(name, description, quantity);
}
}
}
return SPUFound;
}
When I run in browser, it just won't show up any retrieved data. When I run in debugging mode, I realized that when it hits the while loop, instead of executing the dr.Read(), it simply just skip the entire while loop and return null values. I wonder what problem has caused this. I tested my query using the test query, it returns me something that I wanted so I think the problem does not lies at the Sql statement.
Thanks in advance.
Edited Portion
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}

how to insert row in SQL database in ADO.Net Connection oriented mode

I have a database in which a table has name Registration which is used to register the user.
It has only two column one is Username and one is password.
A page named Register.aspx is used for registering the member which have two textbox one is for taking Username(textbox1) and one is for taking password(textbox2) and one button for insert these value in database.
The Main problem is that we cannot write statement like this :
Insert into Registration (Username, password)
values ('TextBox1.text','TextBox2.text')
I am using ADO.net Connection oriented mode, I googled but I didn't find any way to insert row in SQL database in connected mode. Please provide me a idea for inserting this row?
ADO.NET has DataReader which supports Connected mode. All else are disconnected.
DataReader is connected architecture since it keeps conneection open untill all records are fetched
If you want to insert in ADO.NET then you should perform the following steps:
private void btnadd_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
Execute command by calling following method................
1.ExecuteNonQuery()
This is used for insert,delete,update command...........
2.ExecuteScalar()
This returns a single value .........(used only for select command)
3.ExecuteReader()
Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
try
{
using (var connection = new SqlConnection(yourConnectionString))
{
string queryString = "Select id, name, age from Table where name = #name";
using (var command = new SqlCommand(queryString, Connection))
{
command.Parameters.AddWithValue("#name", name);
Connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
item = new Item(long.Parse(dataReader[0].ToString()),
dataReader[1].ToString(),
int.Parse(dataReader[2].ToString()));
}
dataReader.Close();
}
}
}
catch (Exception ex)
{
// if exception will happen in constructor of SqlConnection or Command, the // resource can leak but Dispose method will never be called, couse the object was not created yet.
// Trace and handle here
throw;
}
finally
{
}
But ADO.net is useless for enterprice development. You have to have and abstraction from Data Acess Layer and go to entities, not table records
Use the ORM, Luke!
using System.Data.SqlClient;
string cnstr = "server=.;database=dbname;user=username;password=password;";
SqlConnection con = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand { Connection = con };
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
//something;
}
finally
{
if (con != null)
con.Close();
}

Values not updates after update query

I am developing a project in ASP.NET with c# and SQL Server 2005 as back end. It includes a page profile.aspx which displays the information of a user from database. The session variable is used to keep track of the current logged in user.
The profiles table in the database contains a username column and 10 others columns like dept, address, contact, skills, interests etc etc.
I am displaying all these values on profile.aspx. Another page is edit_profile.aspx which comes up when the edit button on profile.aspx is clicked. Here the data is displayed in textboxes, with older entries already displayed, which can be edited, and click the Update button to confirm.
The update query runs fine, there is no error, but the values are not updates in the database tables. What is the possible reason? Solution?
Thank you
protected void Page_Load(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
protected void Button1_Click(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlCommand sda = new SqlCommand("update profiles set department='"+txt_deptt.Text+"',qualifications='"+txt_qualificatns.Text+"', address='"+txt_add.Text+"', contacts='"+txt_contacts.Text+"', interests='"+txt_interests.Text+"', awards='"+txt_awards.Text+"', website='"+txt_website.Text+"', skills='"+txt_skills.Text+"', mstatus='"+txt_mstatus.Text+"' where username='" + Session["currentusername"].ToString() + "'", con);
DataSet ds = new DataSet();
try
{
con.Open();
int temp=sda.ExecuteNonQuery();
con.Close();
if (temp >= 1)
{
lbl_message.ForeColor = System.Drawing.Color.Green;
lbl_message.Text = "Profile Updated Successfully!";
}
else
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Integer less than 1";
}
}
catch
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Try Again Later, An Error Occured!";
}
//Response.Redirect("profile.aspx");
}
}
You are overwriting the contents of your textboxes every time the page loads so the user inputted conntet is never written to the database...
Look at the Page.IsPostBack method. Basically, wrap the commands to fill the textboxes with
if (!Page.IsPostBack) {}
To only load the values into the text box the first time the page loads (and so not overwrite the user entered values when you click the button you need to check that the page isn't a post back.
I think maybe a book on basic ASP.Net will help answer many questions you may have early on.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
}