Select Query Error - c#

I want to create a login account by matching UserName & Password. I want to save the result in a local variable named as result. When a user logs in, the result should be one, but it always returning -1. My code is following......
protected void LoginBtn_Click(object sender, EventArgs e)
{
string Name = nameTextBox.Text;
string Password = passwordTextBox.Text;
nameTextBox.Text = "";
passwordTextBox.Text = "";
string connectionstring = #"Integrated Security=True;Initial Catalog=HMIS;Data Source=.\SQLEXPRESS";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
string selectquery = "Select ID from UsersInfo where UserName='" + #Name+ "' and Password='" + #Password + "'";
SqlCommand cmd = new SqlCommand(selectquery, connection);
cmd.Parameters.AddWithValue("#UserName", Name);
cmd.Parameters.AddWithValue("#Password", Password);
//object result = cmd.ExecuteNonQuery();
//if (result != null)
int result = (int)cmd.ExecuteNonQuery();
if (result > 0)

Your parameter name was incorrect #UserName whereas in the query string #Name was used.
Try this code.
protected void LoginBtn_Click(object sender, EventArgs e)
{
string Name = nameTextBox.Text;
string Password = passwordTextBox.Text;
nameTextBox.Text = "";
passwordTextBox.Text = "";
string connectionstring = #"Integrated Security=True;Initial Catalog=HMIS;Data Source=.\SQLEXPRESS";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
string selectquery = "Select ID from UsersInfo where UserName='" + #Name+ "' and Password='" + #Password + "'";
SqlCommand cmd = new SqlCommand(selectquery, connection);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#Password", Password);
//object result = cmd.ExecuteNonQuery();
//if (result != null)
int result = (int)cmd.ExecuteNonQuery();
if (result > 0)

The ExecuteNonQuery Method returns the number of row(s) affected by either an INSERT, an UPDATE or a DELETE. For all other types of statements, the return value is -1.
Use the ExecuteReader method instead. This returns a SqlDataReader, which has a HasRows property.
ExecuteNonQuery shouldn't be used for SELECT statements.

Related

Column 'username' does not belong to table Table

I am trying to do lock user account for Invalid login attempts in Asp.Net C# by using Visual Studio 2019. Database is using MySql Workbench 8.0 CE. But facing the error
C# code shown as below:
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace Canteen_UAT
{
public partial class LoginDetail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
MySqlConnection scon = new MySqlConnection("server = XXX.XXX.XX.XXX; user id = root; password = XXXXX; persistsecurityinfo = True; database = posdbms_uat");
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
String uname;
String pass;
String status;
//String lockstatus;
int attemptcount = 0;
if (ds.Tables[0].Rows.Count > 0)
{
uname = ds.Tables[0].Rows[0]["username"].ToString();
pass = ds.Tables[0].Rows[0]["password"].ToString();
status = ds.Tables[0].Rows[0]["status"].ToString();
scon.Close();
if (status == "Open")
{
if (uname == TextBox1.Text && pass == TextBox2.Text)
{
Session["username"] = uname;
Response.Redirect("Order.aspx");
}
else
{
Label2.Text = "Invalid Username or Password - Relogin with Correct Username & Password. No of Attempts Remaining : " + (2 - attemptcount);
attemptcount = attemptcount + 1;
}
}
else if (status == "Locked")
{
Label2.Text = "Your Account Locked Already : Contact Administrator";
}
else
{
Label2.Text = "Invalid Username or Password - Relogin wit Correct Username and Password.";
}
if (attemptcount == 3)
{
Label2.Text = "Your Account Has Been Locked Due to Three Invalid Attempts - Contact Administrator.";
setlockstatus(TextBox1.Text);
attemptcount = 0;
}
}
}
private void setlockstatus(String username1)
{
String mycon = "server = xxx; user id = root; password = xxx; persistsecurityinfo = True; database = posdbms_uat";
String updatedata = "Update posdbms_uat.logindetail set status='Locked' where username='" + username1 + "' ";
MySqlConnection con = new MySqlConnection(mycon);
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = updatedata;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
}
Not sure what might be causing this.
What I have tried:
I created a table as posdbms_uat, datatable match the column name in the database table and with appropriate datatype. Not sure how this error pops up.
The query:
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
...only returns the number of rows matching the WHERE condition - not the actual data in the rows. It should be fixed by specifying the columns you want to get:
String myquery = "select username, password, status from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
Also, you should consider using parametrization to avoid SQL injection (see this SO question). Another thing is, please do not store the password in plain text.

Hashed password is not recognized after changing it

I have hased my password right there on in the registration.aspx. having this code in my business layer:
public static string CreateSHAHash(string Phrase)
{
SHA512Managed HashTool = new SHA512Managed();
Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}
and this code in the register page:
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
Having the codes above, the password are being hashed in the DB and it is working fine when I log in with this code:
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString();
if (password == BusinessLayer.ShoppingCart.CreateSHAHash(txtPassword.Text))
{
Session["New"] = txtUser.Text;
Response.Write("<script>alert('Logged In')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
However when I change it having this code in my changepassword.aspx, its not letting me in with my new password.
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "select * from UserData ";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
if (BusinessLayer.ShoppingCart.CreateSHAHash(txt_cpassword.Text) == reader["Password"].ToString())
{
up = 1;
}
}
reader.Close();
con.Close();
if (up == 1)
{
con.Open();
str = "update UserData set Password=#Password where UserName='" + Session["New"].ToString() + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 50));
com.Parameters["#Password"].Value = BusinessLayer.ShoppingCart.CreateSHAHash(txt_npassword.Text);
com.ExecuteNonQuery();
con.Close();
lbl_msg.Text = "Password changed Successfully";
}
else
{
lbl_msg.Text = "Please enter correct Current password";
}
}
What am I missing here?
Check if the 50 truncates the hash.
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 50));
On a sidenote i see that your solution is very open to SQL injection.
"select Password from UserData where Username ='" + txtUser.Text + "'";
A user can write sql statements in the textbox, and hijack your database, create his own tables or drop the whole database. You should always parameterize the queries. I see that you did that to the Update statement, but you should consider doing it for all of your variables.
This quickly creates a lot of code, so i would also consider making an SQL wrapper, that wraps in all of the things you repeat. When you are done refactoring it could look something like this:
var sql = new SqlWrapper("select Password from UserData where Username = #username", txtUser.Text);
var dataSet = sql.Execute();
Then you can hide all of your connectionstring, commands++ behind this wrapper and only tell the wrapper what you actually care about.
You should also consider using a salt for your password. If you and I have the same password, the hash will be the same. A salt will fix this problem.
A good article about password security -> https://crackstation.net/hashing-security.htm

Error in method Unable to evaluate expression

Im getting this error,
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
And I don't know what is causing it.
There are two methods Login and Session Selection. The login session just matches email and a password; and the session selection queries the db with a GUID that will be used as the session ID. The error is thrown when I call SessionSelection() in Login
private void SessionSelection( )
{
string connectstr = "data source=.\\SQLEXPRESS;Integrated Security=True; Initial Catalog= NewApp";
try
{
string query = #"SELECT UserIDkey FROM Registration WHERE Email='" + txtEmail.Text.Trim() + "'";
SqlConnection con = new SqlConnection(connectstr);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string SessionResult = reader["UserIDkey"].ToString();
Session["PrivateKey"] = SessionResult;
//SessionResult = SpecialKey;
}
reader.Close();
con.Close();
}
catch
{
}
}
private void Login()
{
string passwordEncryption = txtPassword.Text.Trim();
System.Security.Cryptography.MD5CryptoServiceProvider x2 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs2 = System.Text.Encoding.UTF8.GetBytes(passwordEncryption);
bs2 = x2.ComputeHash(bs2);
System.Text.StringBuilder s2 = new System.Text.StringBuilder();
foreach (byte b in bs2)
{
s2.Append(b.ToString("x2").ToLower());
}
string EncryptedPassword = s2.ToString();
if (!string.IsNullOrEmpty(txtEmail.Text))
{
string connectstr = "data source=.\\SQLEXPRESS;Integrated Security=True; Initial Catalog= NewApp";
// (ConfigurationManager.AppSettings["connectionString"]);
try
{
string query = #"SELECT * FROM Registration WHERE Email='" + txtEmail.Text.Trim() + "'and Password='" + EncryptedPassword + "'";
SqlConnection con = new SqlConnection(connectstr);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
var Results = (int)cmd.ExecuteScalar();
//string sqlRead = cmd.ExecuteReader().ToString();
if (Results > 0)
{
SessionSelection();
txtEmail.Text = "";
txtPassword.Text = "";
Response.Redirect("~/Home.aspx");
}
else
{
Response.Write("Incorrect UserName/Password");
}
con.Close();
}
catch (Exception ex)
{
Response.Write("Incorrect UserName/Password");
}
}
Problem : You are not giving space between your Email string and and keyword in your command string in Login() method:
string query = #"SELECT * FROM Registration WHERE Email=
'" + txtEmail.Text.Trim() + "'and Password='" + EncryptedPassword + "'";
^^^
Solution : You needto have space between your Email string and and keyword in your command string in Login() method:
Try This:
string query = #"SELECT * FROM Registration WHERE Email=
'" + txtEmail.Text.Trim() + "' and Password='" + EncryptedPassword + "'";
Suggestion: Your query is open to SQL Injection attacks so I'd strongly suggest you to use Parameterised queries to avoid SQL Injection attacks.
Solution 2: with Parameterised queries
try
{
string query = #"SELECT * FROM Registration WHERE Email=#Email
and Password=#Password";
SqlConnection con = new SqlConnection(connectstr);
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Email",txtEmail.Text.Trim());
cmd.Parameters.AddWithValue("#Password",EncryptedPassword);
con.Open();
var Results = (int)cmd.ExecuteScalar();
//string sqlRead = cmd.ExecuteReader().ToString();
if (Results > 0)
{
SessionSelection();
txtEmail.Text = "";
txtPassword.Text = "";
Response.Redirect("~/Home.aspx");
}
else
{
Response.Write("Incorrect UserName/Password");
}
con.Close();
}
The Problem was Response.Redirect("~/Home.aspx", false);
To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Execute method instead.
Fix
Response.Redirect("~/Home.aspx", false);

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 + "'";

Checking if a user exists, and stopping a database insert (access database)

I just don't know how to check if the users exists in the database and stop it from inserting a new row to the db (which will cause an error as I set the user to be a primary key)
protected void Button1_Click1(object sender, EventArgs e)
{
{
OleDbConnection myconnection = new OleDbConnection();
myconnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Event.mdb";
myconnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myconnection;
myCommand.CommandType = CommandType.Text;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
myCommand.CommandText = query;
try
{
int amountOfUsers = (int)myCommand.ExecuteScalar();
if (amountOfUsers < 1)
{
String myQuery = "insert into users (uname,upassword,email,type) Values ('" + UserName.Text + "','" + Password.Text + "' ,'" + Email.Text + "',' user');";
myCommand.CommandText = myQuery;
myCommand.ExecuteNonQuery();
Label1.Text = "user registered";
}
else
{
Label1.Text = "user already exists";
UserName.Text = "";
Email.Text = "";
}
}
finally
{
myconnection.Close();
}
}
}
correct your query:
query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'" ,UserName.Text );
Your question isn't clear at all but I can suggest a few things..
First of all, I think you forget to use your uname as a second parameter in your:
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
line. You used {0} but never point any value to this parameter. (I assume you don't have a username called {0}) Like;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'", UserName.Text);
As a second, please always use parameterized queries. This kind of string concatenations are open for SQL Injection attakcs.
Like;
String myQuery = "insert into users (uname,upassword,email,type) Values (#uname, #upassword, #email, #type)";
OleDbCommand myCommand = new OleDbCommand(myQuery);
myCommand.Parameters.AddWithValue("#uname", UserName.Text);
myCommand.Parameters.AddWithValue("#upassword", Password.Text);
myCommand.Parameters.AddWithValue("#uname", Email.Text);
myCommand.Parameters.AddWithValue("#uname", "user");
i want to check if the username in UserName.Text is availble in the
data base or no and if it does i want to stop from inserting new data
Than you should use SELECT first to check your username is exist in your database or not like;
string query = string.Format("SELECT * FROM users WHERE uname = '{0}'", UserName.Text);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
SqlDataReader reader = myCommand.ExecuteReader();
if(reader.HasRows)
{
//Your username exist in your database
}
else
{
//Doesn't exist
}
you have missing the parameter uname , you have pass the text of UserName textbox to uname
for eg
"SELECT COUNT(*) FROM users WHERE uname='" + UserName.Text +"'

Categories