I have built a custom validator,
I have a sql query like this:
protected void custom_serverValidate(object sender, ServerValidateEventArgs e)
{
connect();
string strSQL = "select EmailAddress from Accounts_Users where EmailAddress=" + REmailTextBox.Text;
SqlCommand cmd = new SqlCommand(strSQL, objConnection);
if (e.Value.ToString() == cmd.ExecuteScalar().ToString())
{
e.IsValid = false;
}
else
e.IsValid = true;
disConnect();
}
when I execute my code in the browser and an email address and submit it , I get the error mentioned in the title. how to fix it ?
You are missing quotes around your email address. However - this is a SQL injection attack waiting to happen. Please switch to using a parameter.
string strSQL = "select EmailAddress from Accounts_Users where EmailAddress = #EmailAddress"
...
cmd.Parameters.AddWithValue("#EmailAddress", REmailTextBox.Text);
You forgot to use the single quotes. Use:
string commandText = "select EmailAddress from Accounts_Users where EmailAddress=#EmailAttress";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.Add("#EmailAddress", REmailTextBox.Text);
Related
This code will perfectly retrieve data if there are no conditional clauses
(a basic select * from table statement), but it fails when I provide username and order by clause
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());
string cname = TextBox2.Text;
Session[cname] = cname.ToString();
con.Open();
string sql = " select * from customer_reservations where customer_id='"
+ Session[cname] + "' order by reservation_time ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
/*"select *from customer_reservations where customer_id='" + cname +
"' order by reservation_time";
*/
/* select *from customer_reservations */
}
The reservation_time is stored as datetime data type in SQL Server and does seem accessible because when I do a select * statement it does convert 14' O clock to 2pm in browser
Ok, is cname text, or a number? You have to check the database.
However, it always VERY easy to mess up string concatenation, and thus I suggest this:
protected void Button1_Click(object sender, EventArgs e)
{
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString()))
{
string cname = TextBox2.Text;
Session["cname"] = cname.ToString();
con.Open();
string sql = " select * from customer_reservations where customer_id = #cname "
+ " order by reservation_time";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#cname", SqlDbType.NVarChar).Value = cname;
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
So, it tends to be easier to write out the sql without all those quotes and what not. And bonus is we get sql injection safe code.
So try above.
Also, check your on-page load event. If it loads up the grid, or does anything, then you ALWAYS, but ALWAYS want to ONLY have code run on first page load, and hence this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
As a FYI, you would have needed this:
Session["cname"] = cname;
And to get the value out, you need this:
some var = Session["cname"].ToString();
You actually creating a session var of the actual text value!! - not something called "cname".
2nd FYI:
If you want to use paging on the grid, then you can't give the GV a "reader", and thus you need/should use this:
string sql = " select * from customer_reservations where customer_id = #cname "
+ " order by reservation_time";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#cname", SqlDbType.NVarChar).Value = cname;
DataTable rstData = new DataTable();
rstData.Load(cmd.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
I'm using asp.net to create a login page; in debugging I see the correct inputted data but I keep gettting the error message Invalid Username or Password even when it is valid. I have also executed the stored procedure with values and shows the correct result. I'm not sure what is happening.
protected void login_Click(object sender, EventArgs e)
{
String username = txtUserName.Text.ToString();
String password = txtPassword.Text;
string con = ConfigurationManager.ConnectionStrings["LoginConnectionString"].ToString();
SqlConnection connection = new SqlConnection(con);
connection.Open();
string passwords = encryption(password);
SqlCommand cmd1 = new SqlCommand("spLogin", connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#UserName", username);
cmd1.Parameters.AddWithValue("#password", passwords);
SqlDataReader sqldr = cmd1.ExecuteReader();
if (sqldr.Read())
{
Session["UserName"] = username.ToUpper();
Response.Redirect("~/Home/Welcome.aspx");
}
else
{
lblError.Text = "Invalid Username or Password";
}
connection.Close();
sqldr.Close();
}
StoredProcedure
select * from Users u where UserName=#UserName and password=#password
I am trying to retrieve a value from my database, increment it by 1, and then update the database with this new value.
My code so far is
protected void Button1_Click(object sender, EventArgs e)
{
string content = Request.QueryString["ContentID"];
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand("Select likeCount from tbl_Post where tbl_Post.Id="+Convert.ToInt16(content) , conn);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int oldVal = Convert.ToInt16(dr["likeCount"]);
int newVal = oldVal + 1;
SqlCommand insert1 = new SqlCommand("update tbl_Post set
likeCount="+newVal+ "where tbl_Post.Id=" + content);
insert1.ExecuteNonQuery();
conn.Close();
}
I am getting an error on the line insert1.ExecuteNonQuery
ExecuteNonQuery: Connection property has not been initialized.
The reason of your error is the missing connection in the second command. You can add it to the SqlCommand constructor as you do in the first command, also you have a missing space in the query text for the second command.
These errors and a more serious error called Sql Injection could be avoided if you use parameters like explained in the code below
Least but probably most important is the fact that you don't need two commands to increment the likeCount field. You can write a single command
protected void Button1_Click(object sender, EventArgs e)
{
string content = Request.QueryString["ContentID"];
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString;
string updateText = #"update tbl_Post
set likeCount=likeCount + 1
where tbl_Post.Id=#id";
using(SqlConnection conn = new SqlConnection(connStr))
using(SqlCommand cmd = new SqlCommand(updateText, conn);
{
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt16(content);
cmd.ExecuteNonQuery();
}
}
Notice also the presence of the using statement around the disposable objects like connection and commands. This allows you to close and dispose these objects also in case of exceptions.
So what I'm trying to do is once I click a button. I want one sql query to insert values to the "Return_Process" Table and another sql query to delete data from the matching loan ID in another table, which is "Loan_Process".
This is the code I have written but its not deleting anything, its inserting the values to the return process but not deleting it from the loan process.
//Global variable declaration
string path;
string sql;
string sql2;
//create a method for database connection
public void connection()
{
//connection string
path = #"Data Source=NATHAN-PC\SQLEXPRESS;Initial Catalog=ASP;Integrated Security=True";
}
protected void Button1_Click(object sender, EventArgs e)
{
{
connection();
SqlConnection con = new SqlConnection(path);
con.Open();
//try
{
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID) VALUES ('" + txtRID.Text + "','" + txtfine.Text + "','" + TextBox1.Text + "','" + txtLID.Text + "')";
sql2 = "Delete FROM Loan_Process WHERE Loan_ID='"+txtLID+"'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
//lblerrormsg.Visible = true;
//lblerrormsg.Text = "Success";
con.Close();
//GridView1.DataBind();
}
//catch (SqlException)
//{
// //lblerrormsg.Visible = true;
// //lblerrormsg.Text = "Invalid";
//}
con.Close();
//GridView1.DataBind();
}
}
}
}
I'm pretty bad at ASP.net, so if someone could tell me what to do to execute both queries at the same time, would greatly appreciate it.
Do something like this:
//your code
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID)"
+ " VALUES (#rid, #fine, #retDate, #lid); " //note ; inside
+ "Delete FROM Loan_Process WHERE Loan_ID=#lid;";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#rid", SqlDbType.Int).Value = Int.Parse(txtRID.Text);
//similar for 3 remaining parameters. Just set correct SqlDbType
con.Open();
cmd.ExecuteNonQuery();
con.Close();
This is my code:
protected void logujButton_Click(object sender, EventArgs e)
{
string user = "data source=myHostServer; database = myDataBase; user id=myLogin; password=myPassword";
SqlConnection con2 = new SqlConnection(user);
con2.Open();
string loguj = "select count(*) from uzytkownik where Login = '"+ logujTextBox.Text +"'";
SqlCommand command = new SqlCommand(loguj, con2);
int wartosc = Convert.ToInt32(command.ExecuteScalar().ToString());
con2.Close();
if (wartosc == 1)
{
con2.Open();
SqlCommand pobierzHaslo = new SqlCommand("select Haslo from uzytkownik where Login = '" + logujTextBox.Text + "'", con2);
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
string haslo = rdr["Haslo"].ToString();
if (haslo == hasloTextBox.Text)
{
errorLabel.Text = "Prawidlowe Haslo !";
}
else
{
errorLabel.Text = "Zle haslo !";
}
}
else
{
errorLabel.Text = "Taki uzytkownik nie istnieje !";
}
}
When I press button, this error is appearing: "Invalid attempt to read when no data is present". Could You tell me, where i made mistake ?. Thanks for advise !
You haven't read anything from the reader yet. You have to call the Read() method:
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
if (rdr.Read())
{
string haslo = rdr["Haslo"].ToString();
....
}
If you have access to SSMS, run the query directly in a query window and make sure that you get data back. Your query may be bad. It is most likely an error from the ExecuteReader method of your SqlDataReader, based on the text of the error message.