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);
Related
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
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 + "'";
I am getting an error at the ExecuteNonQuery and really don't know why. I spent a lot of time searching the web and realized that User has to be between [], but it hasn't solved my problem.
else {
DataTable table = new DataTable();
string query = "SELECT * FROM [User] WHERE Email = '" + tbMail.Text + "'";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, connectionString);
int count = adapter.Fill(table);
if (count != 0) {
MessageBox.Show("This email is already in use", "Email in use", MessageBoxButtons.OK, MessageBoxIcon.Information);
} else {
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand insertCommand = new OleDbCommand();
adapter = new OleDbDataAdapter();
string encryptedPassword = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(tbPass.Text)));
connection.Open();
string command = "INSERT INTO [User] (Username, Password, Email) VALUES('" + tbUser.Text + "', '" + encryptedPassword + "', " + tbMail.Text + ")";
insertCommand.Connection = connection;
insertCommand.CommandText = command;
adapter.InsertCommand = insertCommand;
adapter.InsertCommand.ExecuteNonQuery();
connection.Close();
}
}
The error is:
There was an error parsing the query. [Token line number,Token line offset,,Token in error,,]"
Your email value must be between quotes, just like username and password.
Another point is that you should use sql parameters to prevent sql injection attacks.
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.
I'm trying to do a Login code in C# with MySQL. Basically the user enters a username and password then the code checks the database if the the password is correct. I'm having trouble getting the code to read from the data base... Here is where I'm at.
public string strUsername;
public string strPassword;
//Connect to DataBase
MySQLServer.Open();
//Check Login
MySqlDataReader mySQLReader = null;
MySqlCommand mySQLCommand = MySQLServer.CreateCommand();
mySQLCommand.CommandText = ("SELECT * FROM user_accounts WHERE username =" +strUsername);
mySQLReader = mySQLCommand.ExecuteReader();
while (mySQLReader.Read())
{
string TruePass = mySQLReader.GetString(1);
if (strPassword == TruePass)
{
blnCorrect = true;
//Get Player Data
}
}
MySQLServer.Close();
From what I've done in the past, I thought this would work but if I print it, it Seems like its not being read. I am still fairly new to MySQL so any help would be Great.
Non-numeric field value must be enclosed with single quote.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer;
but you have to use Parameters to prevent SQL Injection.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username =#username";
mySQLCommand.Connection=MySQLServer;
mySQLCommand.Parameters.AddWithValue("#username",strUsername);
string con_string = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True";
string query = "SELECT * FROM Users WHERE UseName='" + txtUserName.Text.ToString() + "' AND Password='" + txtPassword.Text + "'";
SqlConnection Con = new SqlConnection(con_string);
SqlCommand Com = new SqlCommand(query, Con);
Con.Open();
SqlDataReader Reader;
Reader = Com.ExecuteReader();
if (Reader.Read())
{
lblStatus.Text="Successfully Login";
}
else
{
lblStatus.Text="UserName or Password error";
}
Con.Close();
As AVD said you should use parameters to prevent sql injection....