SqlException in Asp.net - Incorrect syntax near 'Van' - asp.net

I have problem with my SqlCommand everything I open the page I get the error:
System.Data.SqlClient.SqlException: Incorrect syntax near 'Van'.
I cannot find the problem because 'Van' is only found once in the entire project, and in the title..
This is my code in the Page_Load:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = " + User.Identity.Name, con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
}
The database connectionstring is correct because it works for all my other pages.. i'm trying to get the department where an employee works so he/she can only view memo's from their own department.

You need to close the parentheses after the last name provided.
SELECT (SELECT Memo_ID, Dep_Name FROM Department
WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName
FROM Staff WHERE (FirstName + SPACE(1) + LastName = 'xxx' )
Here is what it should look like:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "')", con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();

You need to quote the last name. You probably want to convert to a parameterized query too.

I'd have expected your WHERE clause to wrap the User.Identity.Name in quotes:
WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "'" ...
Could "van" be in the username?
This isn't a very secure query either - but SQL injection's another issue!

Related

"Incorrect syntax near 'admin'

this programm when i enter username and password go to data base and compare from table,but when i enter username admin ,password admin(exist in table)
compalier show error "Incorrect syntax near 'admin'" in line
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
The error is simply caused by the missing equals before the values concatenated in the sql command text.
But also fixing it, your code is wrong for other reasons.
You should ALWAYS use a parameterized query to avoid Sql Injection and parsing problems,
You could remove the COUNT function that causes an unnecessary load of all records just to confirm the existence of your searched data
You need to identify your user searching for both password and
username on the SAME record, as it is now, the code above search first the username
and then a password, but I can type an existing user name (first if passed) and use
a password of a different user (second if passed) and then gain access to
your site.
.
string checkuser = "IF EXISTS(select 1 from [Users] where Username = #usr AND Password=#pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand com = new SqlCommand(checkuser,conn))
{
conn.Open();
com.Parameters.AddWithValue("#usr", TextBoxUserName.Text);
com.Parameters.AddWithValue("#pwd", TextBoxPassword.Text);
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
Response.Redirect("Welcome.aspx");
else
Response.Redirect("Error.aspx");
}
Other things changed in the example above are the USING STATEMENT to be sure that your connection and command are disposed at the end of the operation also in case of exceptions
Try changing this line
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
to this
string checkuser = "select count(*) from [Users] where Username = '" + TextBoxUserName.Text + "'";
you are missing an = sign
you'll need to do the same to your password select as well, you also missed the = sign there.
string checkpassword = "select Password from Users where Password = '" + TextBoxPassword.Text + "'";
When checking the Password, you should also include the UserName:
string checkpassword = "select Password from Users where UserName = '" + TexBoxUserName.Text + "' AND Password = '" + TextBoxPassword.Text + "'";
If you do not include the UserName the it is only validating that some user has that password.
The following code will prevent SQL injection by paramterizing the command text
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "SELECT Count(UserName) FROM USERS WHERE UserName = #UserName";
SqlCommand com = new SqlCommand(checkuser,conn);
SqlParameter parmUserName = new SqlParameter("UserName", TextBoxUserName.Text);
com.Parameters.Add(parmUserName);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "SELECT Password FROM USERS WHERE UserName = #UserName AND Password = #Password";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
SqlParameter parmPassword = new SqlParameter("Password", TextBoxPAssword.Text);
com.Parameters.Add(parmUserName);
com.Parameters.Add(parmPassword);
string password = passComm.ExecuteScalar().ToString();

There is already an open DataReader associated with this Command which must be closed first.Why?

protected void Page_Load(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex=0;
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = '" + Login1.UserName + "'";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
SqlDataReader dr = cmdr.ExecuteReader();
if (cmdr.ExecuteReader().HasRows)//here showing the error as the title i gave.
{
Session["userName"] = Login1.UserName.Trim();
string myStringVariable = "Welcome! ";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + Login1.UserName + "');", true);
//dr.Dispose();
}
else
{
string myStringVariable = " No Username Found";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + "');", true);
}
con.Close();
}
I used datareader object dr in the same page in other events too...
Plz help....
Why are you calling ExecuteReader two times? One is enough
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)
{
-----
Your code has also other problems. Sql Injection is the most Dangerous. You should use code like this when passing values entered by your user
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on " +
"t1.RegId = t2.RegId and t2.Uname = #uname";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
cmdr.Parameters.AddWithValue("#uname", Login1.UserName);
SqlDataReader dr = cmdr.ExecuteReader();
and also using a global connection is a bad practice because you keep an expensive resource locked. Try to use the using statement, open the connection, the command and the reader and then close and destroy everything
// CREATE CONNECTION AND COMMAND
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmdr = new SqlCommand(str, con))
{
// OPEN THE CONNECTION
con.Open();
cmdr.Parameters.AddWithValue("#uname", Login1.UserName);
using(SqlDataReader dr = cmdr.ExecuteReader())
{
// USE
....
} // CLOSE AND DESTROY
} // CLOSE AND DESTROY
You've already opened the reader in the line above. I think you want:
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)//here showing the error as the title i gave.
But there are other issues - SQL Injection as #Brad M points out (do a search on parameterised queries), and you're leaking your command objects - they ought to be enclosed in using statements.
I'm also slightly nervous about what/where con is defined - it smells strongly like a global variable of some kind. The general pattern for using ADO.Net is to, inside a single method/block of code, you should create a new SqlConnection object (inside a using statement), create a new SqlCommand object (inside a using statement), open the connection, execute the command, process the results (if applicable) and then exit the using blocks and let everything get cleaned up. Don't try to share SqlConnection objects around.
you already execute reader on
SqlDataReader dr = cmdr.ExecuteReader();
So in if, you should use existing reader
dr.HasRows
Initialy be careful in your sql scripts
Avoid
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = '" + Login1.UserName + "'";
Use
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = #username";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
cmdr.Parameters.AddWithValue("#username", Login1.UserName);
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)
{
Session["userName"] = Login1.UserName.Trim();
string myStringVariable = "Welcome! ";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + Login1.UserName + "');", true);
}
and DO NOT forget to
dr.Close();

what is wrong with this C# duplicate row code?

I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct

Need help reading multiple values back from sql server database in asp code

here is my codebehind for grabbing data from database:
public static string getTestimonial()
{
string username = "xxxxx";
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxxxxxx"].ConnectionString);
Conn.Open();
string sql = "select testimonial,submitname from (SELECT TOP 1 * FROM dbo.testimonials where username='" + username + "' ORDER BY newid()) as answer;";
SqlCommand cmd = new SqlCommand(sql, Conn);
string test=cmd.ExecuteScalar().ToString();
Conn.Close();
return test;
}
yet when I try to display the data on my aspx page all I get is the first value:
<div class="span3">
<%= getTestimonial() %>
</div>
can you please help me with a method of getting both the testimonial and the submitname from the query into variables?
Thanks!
Thanks! Solved! using:
public static string getTestimonial()
{
string username = "xxxxxx";
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxxxxxx"].ConnectionString);
Conn.Open();
string sql = "select testimonial,submitname from (SELECT TOP 1 * FROM dbo.testimonials where username='" + username + "' ORDER BY newid()) as answer;";
SqlCommand cmd = new SqlCommand(sql, Conn);
var test = new StringBuilder();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
test.Append(reader.GetString(0));
test.Append(" and ");
test.Append(reader.GetString(1));
}
}
Conn.Close();
return test.ToString();
}
ExecuteScalar() will always return first column of the first row - a single value. You may want to rethink your approach, meanwhile the simplest way is to make your query return combined value:
string sql = "select testimonial + ' and ' + submitname from ....
As an aside, you probably should rewrite that function to not use inline SQL, as you are making your site vulnerable to SQL injection attacks potentially in writing it this way. (presumably, userid is not set as a constant XXXXX in the actual function and is instead passed in somehow).

How to update only some columns of database?

The problem occuring on updating only email all other blanks get null . Even if i unchecked allow null in sql server 2008 .my code is-
protected void Updateinfo_Click(object sender, EventArgs e)
{
string radiogender;
if (Radiochngmale.Checked == true)
radiogender = Radiochngmale.Text.ToString();
else
radiogender = Radiochngfemale.Text.ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
con.Open();
if (con.State == ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand();
Random r = new Random();
int next = r.Next();
if (FileUpload2.HasFile)
{
string myMap = MapPath("~/").ToLower();
string ImageName = FileUpload2.PostedFile.FileName;
sImageFileExtension = ImageName.Substring(ImageName.LastIndexOf(".")).ToLower();
if (sImageFileExtension == ".gif" || sImageFileExtension == ".png" || sImageFileExtension == ".jpg" || sImageFileExtension == ".jpeg" || sImageFileExtension == ".bmp")
{
string ImageSaveURL = myMap + "UserImage/" + next + sImageFileExtension;
FileUpload2.PostedFile.SaveAs(ImageSaveURL);
}
else
Response.Write("Invalid File");
}
cmd.Connection = con;
if(chngfname.Text==null)
chngfname.Text="Select Firstname from Login where Email='"+Session["UserName"]+"'";
if (chnglastname.Text == null)
chnglastname.Text = "Select Lastname from Login where Email='" + Session["UserName"] + "'";
if (chngage.Text == null)
chngage.Text = "Select age from Login where Email='" + Session["UserName"] + "'";
if (chngemail.Text == null)
chngemail.Text = "Select Email from Login where Email='" + Session["UserName"] + "'";
if (radiogender == null)
radiogender = "Select gender from Login where Email='" + Session["UserName"] + "'";
if (chngpassword.Text == null)
chngpassword.Text = "Select Password from Login where Email='" + Session["UserName"] + "'";
if ( FileUpload2.HasFile==null)
sImageFileExtension = "Select profile_pic from Login where Email='" + Session["UserName"] + "'";
if (chngfname.Text == null)
chngfname.Text = "Select Firstname from Login where Email='" + Session["UserName"] + "'";
cmd.CommandText = "Update Login set FirstName = '"+chngfname.Text+"',LastName='"+chnglastname.Text+"',Email='"+chngemail.Text+"',Password='"+chngpassword.Text+"' ,gender='"+radiogender+"',age='"+chngage.Text+"' , profile_pic='"+ next + sImageFileExtension + "' where Email='"+Session["UserName"]+"'";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
Why didn't it is taking the previous values even if i mentioned it to take.Please check it out and sort it out
This is happening because TextBox.Text is never null so your SQL query ends up looking like this:
Update Login
set FirstName = '',
LastName = '',
where Email = 'John.doe#nowhere.net'
-- etc...
Except for the one or two fields where the data is actually set to something. Here's probably what you wanted it to look like:
update login
set FirstName = 'John',
LastName = (select Lastname from login where email = 'John.doe#nowhere.net'),
etc...
where email = 'John.doe#nowhere.net'
But, there no need for the subqueries. If you want to avoid overwriting values where a value is null or empty string, then you want your SQL to look like the following, use Parameters and set them to DbNull when the textbox is empty.
cmd.Parameters.AddWithValue("#FirstName", (chngfname.Text == String.Empty) ? DbNull.Value : chngfname.Text;
update login
set FirstName = coalesce(#firstName, FirstName),
LastName = coalesce(#LastName, LastName),
etc...
where Email = #Email
The other option is select the record first (which I'm sure you've already done) and simply use the same value that's already in the database.
if (chngfname.Text == String.Empty) chngfname.Text = Session["CurrentUserEntity"].FirstName;
Additionally, you need to change this to a parametrized query:
string sql = "update login set FirstName = #firstName, LastName = #lastName, etc... where email = #email;
cmd.Parameters.Add(...);
You should try to use a parametrized query instead of the current string concatenation method.
This will resolve the quoting problems and prevent sql injiection attacks
cmd.CommandText = "Update Login set FirstName = #First, LastName=#Last, " +
"Email=#Mail, Password=#Pass, gender=#Gend,age=#Age, " +
"profile_pic=#Prof " +
"where Email=#oldMail";
cmd.Parameters.AddWithValue("#First", chngfname.Text);
cmd.Parameters.AddWithValue("#Last", chnglastname.Text);
cmd.Parameters.AddWithValue("#Mail", chngemail.Text);
cmd.Parameters.AddWithValue("#Pass", chngpassword.Text);
cmd.Parameters.AddWithValue("#Gend", radiogender);
cmd.Parameters.AddWithValue("#Age", chngage.Text);
cmd.Parameters.AddWithValue("#Prof", next + sImageFileExtension );
cmd.Parameters.AddWithValue("#oldMail", +Session["UserName"]);
However, as I have said in my previous comment, your code doesn't seems correct.
First a TextBox.Text cannot be null, it is an empty string. This will skip your text for null values above and you end with setting a blank value in the database. At least try to change the test with
if(string.IsNullOrEmpty(chngfname.Text))
......
But at this point you should change the code inside each if above. If your intentions is to retrieve the old values from the database and use them in case of empty string, you need to execute that string, not store it in the textbox.
EDIT: Before to start your update process you need to load the old values of the record you are trying to update. This could be done using the same connection
SqlDataAdapter da = new SqlDataAdapter("SELECT * from Login where EMail = #oldMail", con);
da.SelectCommand.Parameters.AddWithValue("#oldMail", Session["UserName");
DataTable dt = new DataTable();
da.Fill(dt);
now you have in a datatable all of your old values for that user, so when you reach the check of the old values you could write something like this
if(string.IsNullOrEmpty(chngfname.Text))
cngfname.Text = (dt.Rows["FirstName"] == DBNull.Value ? string.Empty : dt.Rows["FirstName"].ToString());
and remove that sql string because you have already retrieved the values for every potentially missing field

Resources