Keep receiving Invalid column name 'Username' - c#

i had the exact name in my database yet i still keep getting that error as titled.
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Image Link : http://i.imgur.com/tKtvlfj.png
Additional information: Invalid column name 'Username'.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ERegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*)from Employer where Username='" + TextBoxELUsername.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = "select password from Employer where Username='" + TextBoxELUsername.Text + "'";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
string password = passComm.ExecuteScalar().ToString().Replace(" ","");
if (password == TextBoxLoginPassword.Text)
{
Session["New"] = TextBoxELUsername.Text;
Response.Write("Password is Correct");
}
else
{
Response.Write("Password Incorrect");
}
}
else
{
Response.Write("Username Incorrect");
}
}

Your SQL is invalid. You forgot a space between the count(*) and from keyword. Try this instead:
select count(*) from Employer where Username=
Also you should change your sql to not allow sql injections and use the Parameters object

In the case of your Sql statement to retrieve the count(*) you really should Parameterize that statement to prevent sql injection.
string checkuser = #"select count(*)from Employer where Username= ?";
SqlCommand com = new SqlCommand(checkuser, conn);
comm.Parameters.AddWithValue("?", TextBoxELUsername.Text );
In addition try returning the variable temp in this fashion.
int temp = (int)comm.ExecuteScalar();
Beyond that I would try creating a second connection contained within the IF statement. It may sound odd but that connection can be stripped out of memory before the IF statement is triggered and in turn the program has no idea what connection your are trying to open.
You could avoid a second connection all together by creating a single sql statement
string checkuser = #"select count(*)from Employer where Username= ? and password = ?";
SqlCommand com = new SqlCommand(checkuser, conn);
comm.Parameters.AddWithValue("?", TextBoxELUsername.Text );
comm.Parameters.AddWithValue("?", TextBoxLoginPassword.Text );
your count return will only exist is both the username and password are correct.
You may also want to use the following code to force case sensitivity on your query
alter database your_database collate Latin1_General_CS_AS

Related

Must declare the scalar variable "#UserName"

I have to make a simple login that will not crash when you insert into the browser a (") so i needed to parameterize the query string but for some reason im gettin an error saying:
Must declare the scalar variable "#UserName"
here is the code
private void DoSqlQuery()
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RolaConnectionString"].ConnectionString);
conn.Open();
string checkUser = "select * from UserData where UserName = #UserName";
SqlCommand com = new SqlCommand(checkUser, conn);
com.Parameters.AddWithValue("#Username", txtUserName.Text.Trim());
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where UserName = #UserName";
SqlCommand passConn = new SqlCommand(checkPassword, conn);
com.Parameters.AddWithValue("#Username", txtUserName.Text.Trim());
string password = passConn.ExecuteScalar().ToString();
conn.Close();
if (password == txtPassword.Text)
{
Session["New"] = txtUserName.Text;
Response.Write("Password is correct");
Response.Redirect("~/LoggedIn.aspx");
}
else
{
Response.Write("Password is not correct");
}
}
else
{
Response.Write("Username is not correct");
}
}
catch(Exception e)
{
Response.Write(e.ToString());
}
}
You are referencing the wrong command in the inner if statement:
string checkPassword = "select Password from UserData where UserName = #UserName";
SqlCommand passConn = new SqlCommand(checkPassword, conn);
com.Parameters.AddWithValue("#Username", txtUserName.Text.Trim());
^^^-- should be passConn
As a result, your second command never gets the parameter added so you get the error you mention. Case sensitivity may also be a problem, but it depends on the collation of your database - SQL Server is case-insensitive by default.
Some other suggestions not related to your problem:
Wrap commands and connection in using statements
Query the username and password in one query (WHERE UserName = #UserName AND Password = #Password). Hackers will first search for valid usernames, then try to hack the password using dictionary attacks. Trying to find a matching combination is much harder.
Do not store your passwords in plain text - use a salted hash
Or just use built-in security providers rather than rolling your own.

How to check if SQL database already has the entered Username?

I've written this registration form which adds data to my SQL Server database. What I want is an exception when the user enters a username that is already in the database.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn2.Open();
string CheckUser = "select Username from UserData where Username like #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", "'%"+ UsernameTextBox.Text +"%'");
com2.ExecuteNonQuery();
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
conn2.Close();
if (IsMatch == 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string InsertQuery = "insert into UserData (Username, Email, Password, Country) values (#Username, #Email, #Password, #Country)";
SqlCommand com = new SqlCommand(InsertQuery, conn);
com.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
com.Parameters.AddWithValue("#Email", EmailTextBox.Text);
com.Parameters.AddWithValue("#Password", PasswordTextBox.Text);
com.Parameters.AddWithValue("#Country", CountryDropDownList.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
conn.Close();
}
else
{
Response.Write("User Already Exists!");
}
}
catch (Exception ex)
{
Response.Write(Convert.ToString(ex));
}
}
When I run it, I get an exception on the following line:
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
Blam's second solution works, but the IsMatch can be simplified a bit by casting to int instead of going to string and parsing.
This should also be handled at the database level. Set a primary key on your username column:
ALTER TABLE UserData ADD CONSTRAINT
PK_UserData PRIMARY KEY CLUSTERED (Username)
If you do it this way, then you don't even have to check for duplicates explicitly, you can just try to create the user and handle the exception if it fails:
try
{
using (var conn = new SqlConnection((ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)))
{
conn.Open();
#if DOUBLE_CHECK
string CheckUser = "select count(*) from UserData where Username = #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn);
com2.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
if ((int)com2.ExecuteScalar() > 0)
{
Response.Write("User already exists");
return;
}
#endif
string InsertQuerry = "insert into UserData (Username,Email,Password,Country) values (#Username,#Email,#Password,#Country)";
SqlCommand com = new SqlCommand(InsertQuerry, conn);
com.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
com.Parameters.AddWithValue("#Email", EmailTextBox.Text);
com.Parameters.AddWithValue("#Password", PasswordTextBox.Text);
com.Parameters.AddWithValue("#Country", CountryDropDownList.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
}
}
catch (SqlException se)
{
if (se.Errors.OfType<SqlError>().Any(e => e.Number == 2627))
{
Response.Write("User already exists");
}
else
{
Response.Write(se.ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
If you handle the exception this way, the #if DOUBLE_CHECK section is redundant and can be removed. An attempt to add duplicate name will cause a SQL error and exception, and this will detect and handle the "duplicate key" error.
Two unrelated notes on your code:
Response.Redirect() will abort the current thread and your conn.Close() will not be called. Use a using() to ensure it's called.
Storing a password in the database as plain text is a disaster waiting to happen. PLEASE take a look at Best way to store password in database for some ideas about how to do this correctly
That won't return an integer
string CheckUser = "select count(*) from UserData where Username like #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", "'%"+ UsernameTextBox.Text +"%'");
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
And you don't need to use two different connections.
Just use one and close it in a Finally.
string CheckUser = "select count(*) from UserData where Username = #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", UsernameTextBox.Text );
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
This returns 0 or 1. This should fix your issue. Looks like you need to return an int type. Or you could change it to bool if you want. Either way, this sql statement should help! :)
select
isnull(convert(bit,(select top 1 case
when username != '' then 1
else 0 end
from UserData
where username like #Username)),0)

getting error in color authentication password

I am trying to create color password but i am getting this error
System.Data.SqlClient.SqlException was unhandled by user code
Incorrect syntax near '='.
my code is this and please help me ....
thnxx in advance :)
protected void Button_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData 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 checkPasswordQuery = "select Password from UserData where Username ='" + TextBoxUserName.Text + "'";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
string password = passComm.ExecuteScalar().ToString().Replace(" ","");
if (password == TextBoxPassword.Text)
{
Response.Write("Password is correct");
string checkcolorQuery = "select Color1,Color2,Color3,Color4 from Username='" + TextBoxUserName.Text + "'";
SqlCommand colorCom = new SqlCommand(checkcolorQuery, conn);
string color = colorCom.ExecuteScalar().ToString(); // **getting error here**
if (color == TextBoxColor1.Text && color == TextBoxColor2.Text && color == TextBoxColor3.Text && color == TextBoxColor4.Text)
{
// Session["New"] = TextBoxUserName.Text;
Response.Write("Color Priority is correct");
Response.Redirect("User.aspx");
}
else
{
Response.Write("Color Priority is not correct");
}
}
else
{
Response.Write("Password is not correct");
}
}
else
{
Response.Write("Username is not correct");
}
}
}
Your query is currently
select Color1,Color2,Color3,Color4 from Username='foo'
Surely you need it to be something like
select Color1,Color2,Color3,Color4 from tablename where Username='foo'
You should also change the way you are executing your SQL.
Use something like this to execute your SQL.
public static void ExecuteSQL(string sqlCommand, Dictionary<string,object> parameters )
{
using (SqlConnection dbConn = new SqlConnection(GetConnectionString()))
{
dbConn.Open();
using (SqlCommand dbCommand = new SqlCommand(sqlCommand, dbConn))
{
if (parameters != null)
{
foreach (var parameter in parameters)
{
dbCommand.Parameters.AddWithValue(parameter.Key, parameter.Value);
}
}
dbCommand.ExecuteScalar();
}
dbConn.Close();
}
}
So in your code you'd just have
string checkuser = "select count(*) from UserData where Username =#username";
var parameters = new Dictionary<string, object>();
parameters.Add("#username", TextBoxUserName.Text);
ExecuteSQL(checkuser, parameters);
Problem #1
string checkcolorQuery = "select Color1,Color2,Color3,Color4 from Username='" + TextBoxUserName.Text + "'";
This is the line that is causing the error you're getting. "from Username='whatever'" is not valid SQL, presumably (based on other queries in your code) you meant "from UserData where Username='whatever'".
Problem #2
While we're on the subject, though, this is a textbook example of an SQL injection vulnerability, and that should really be addressed too. Consider what would happen if somebody typed the following into your TextBoxUserName textbox:
';drop table UserData;--
Important: don't actually try this, think about it instead.
Problem #3
colorCom.ExecuteScalar().ToString();
ExecuteScalar() is only for use when you're expecting a single value. It works fine in your first query, because all that's being returned is a single value (the contents of one row's password field). In this second query, though, you're returning four values - only from a single row, true, but you're selecting four fields (Color1 through Color4).
What you should do here is use ExecuteReader() instead, which will return a data reader which you can use to extract those four values and then proceed to compare them the user's input.
Your line
string checkcolorQuery = "select Color1,Color2,Color3,Color4 from Username='" + TextBoxUserName.Text + "'";
is the problem. Username is a column, not a table. It should be
string checkcolorQuery = "select Color1,Color2,Color3,Color4 from UserData where Username='" + TextBoxUserName.Text + "'";

Whats wrong with my MS Access Update Query?

Here is my Query:
string Select = "Update DC set Password = '" + txtPass.Text + "' WHERE ID ="+Convert.ToInt32(cbxDocs.SelectedIndex + 1);
con = new OleDbConnection();
this.readconfile = new ReadConfigFile();
con.ConnectionString = this.readconfile.ConfigString(ConfigFiles.ProjectConfigFile);
con.Open();
cmd = new OleDbCommand(Select, con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
I don't know what is wrong but it gives me an error message that "Syntax error in UPDATE STATEMENT".
I have two fields in my table 'DC' ID and Password, nothing else.
PASSWORD is reserve word enclose it in square brackets like [Password], so your query should start like:
"Update DC set [Password]....
Consider using parameterized query, this will save you from Sql Injection
I think u don't need the ' on ur query and Password is reserved in almost every ddb.
And you could use parameters to avoid the concat with the +
Ex.
string pass = TxtPass.Text;
int s = cbxDocs.SelectedIndex+1;
string Select = "Update DC set Password = #a WHERE ID = #o";
OleDbCommand cmd = new OleDbCommand(Select, conn);
cmd.Paramaters.AddWithValue("#a", pass);
cmd.Parameters.AddWithValue("#o", s);
//everything else....

ASP.NET Login, invalid password

con.Open();
string mysql; // generate an sql insert query for the database
mysql = "SELECT 1 FROM [Users] WHERE Username=? AND Password=?";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddWithValue("#p1", tbUser.Text);
cmd.Parameters.AddWithValue("#p2", tbPass.Text);
cmd.ExecuteNonQuery();
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if(temp==1)
{
Session["LogIn"] = lblUser.Text;
lblLogin.Text = "Welcome " + lblUser.Text + ", you are now logged in.";
}
else
{
lblLogin.Text = "Invalid Username/Password!";
}
con.Close();
Error: Syntax error in FROM clause.
"OleDbException was unhandled by user code."
Thanks.
EDIT
Now that I look closer there are many things wrong with this code. Standard practice is to check for the username/password combination in one shot:
mysql = "SELECT 1 FROM [User] WHERE UserName=? AND Password=?";
OleDbCommand CheckUser = new OleDbCommand(mysql, con);
// Add OleDbParameters here with the correct type/length
CheckUser.Parameters.Add("#userName", OleDbType.Char, 20).Value = tbUser.Text ;
CheckUser.Parameters.Add("#password", OleDbType.Char, 20).Value = tbPass.Text ;
int temp = Convert.ToInt32(CheckUser.ExecuteScalar().ToString());
and adding parameters to the command with the username and password values. That way hackers can't determine valid usernames without knowing the password.
This block:
mysql2 = "SELECT * FROM [User] WHERE Password='" + tbPass.Text + "'";
OleDbCommand Pass = new OleDbCommand(mysql2, con);
string Password = Pass.ExecuteScalar().ToString();
Will return the first column form the first row of the result set. Unless Password is the first column in the User table, you're not getting the password back, you're getting some other value.
It could be:
mysql2 = "SELECT password FROM [User] WHERE Password='" + tbPass.Text + "'";
OleDbCommand Pass = new OleDbCommand(mysql2, con);
string Password = Pass.ExecuteScalar().ToString();
First, just because it builds doesn't mean it's right.
Second, your code is vulnerable to SQL injection.
Third, without an error message or intent there's no way for us to divine what's wrong.
Last but not least: your code will only work if the first row of the first column obtained with the query returns a value of 1. I don't know what you're doing but if all else works for you, you may want to check that.
You can simply do it as :
con.Open();
string mysql; // generate an sql insert query for the database
mysql = "SELECT 1 FROM [Users] UserName='" + tbUser.Text + "' AND
Password='"+ tbPass.Text+"'";
OleDbCommand CheckUser = new OleDbCommand(mysql, con);
int temp = Convert.ToInt32(CheckUser.ExecuteScalar());
if(temp==1)
{
//Login
}
else
{
//Invalid UserName or Password.
}

Categories