In my website made by asp.net, we can update the email address, password, place and about myself of a user given the old password is correct. Now what I do is, login, then use this code to update:
protected void update_profile(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString;
using (SqlConnection connection = new SqlConnection(constr))
{
string user_email = (string)(Session["User"]);
string pass = encrypt_pass(old_password.Text);
if (pass != (string)(Session["Password"]))
{
pass_err_message.Text = "Wrong password";
pass = (string)Session["Password"];
}
else
{
pass = encrypt_pass(new_password.Text);
}
string insertQuery = "update dbo.users set user_password=#new_password, user_place = #new_place, user_about=#new_about where user_email =" +user_email;
SqlCommand com = new SqlCommand(insertQuery, connection);
connection.Open();
com.Parameters.AddWithValue("#new_password", pass);
com.Parameters.AddWithValue("#new_about", new_about.Text);
com.Parameters.AddWithValue("#new_place", new_place.Text);
try
{
com.ExecuteNonQuery();
upload_err_message.Text = "Successfully uploaded";
connection.Close();
}
catch (Exception ex)
{
profile_settings_err_message.Text = "Update error: " + ex.Message;
}
}
}
But when I try to update it is saying: Update error: The multi-part identifier "abcde#gmail.com" could not be bound. And my session is gone! I thought maybe it was due to foreign key, so I removed all the foreign keys of the database, but it is still happening. What's wrong here?
EDIT: I have added back the foreign keys, since I need them to on delete cascade. I just deleted them to see if it works.
I am just taking a guess, but I believe your issue will be found right here:
"... user_email =" +user_email;
Try doing something like
"... user_email = #email";
com.Parameters.AddWithValue("#email", user_email);
That's the better way... however if you want to get lackadaisical you should be able to just surround the email in single quotes.
"... user_email = '" + user_email + "'";
I hope this helps!
Related
My requirement I inserted successfully I want to bind last increment id to the root folder file name.id was automatic incremented in SQL. I want to bind last incremented id on that bold part place.
This is my code please help me to solve this problem:
string insert = "insert into Articles values('" + html+ "','" + text + "')";
try
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
using (StreamWriter file = new StreamWriter(System.Web.Hosting.HostingEnvironment.MapPath(#"~\Articles\**ID**.html"), true))
{
file.WriteLine(value.editor); // Write the file.
}
return msg;
}
else
{
return msg1;
}
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
Please note that your code is a security risk as it's vulnerable to sql injection attacks as Sean Lange rightfully wrote in the comments.
Also, the empty catch is a problem as he pointed out. Do yourself a favor and never ever use empty catch blocks.
To get the last generated identity value in the current session you should use Sql Server's SCOPE_IDENTITY() function.
Note that if you have an instead of insert trigger on the table SCOPE_IDENTITY() will not give you the correct value.
Your code should look something like this:
string insert = "insert into Articles values(#html, #text); select scope_identity()";
using (var con = new SqlConnection("<YOUR CONNECTION STRING HERE>"))
{
using (var cmd = new SqlCommand(insert, con))
{
cmd.Parameters.Add("#html", SqlDbType.NVarChar).Value = html;
cmd.Parameters.Add("#text", SqlDbType.NVarChar).Value = text;
try
{
con.Open();
var databaseId = cmd.ExecuteScalar();
if (databaseId is int)
{
using (StreamWriter file = new StreamWriter(System.Web.Hosting.HostingEnvironment.MapPath(string.Format(#"~\Articles\{0}.html", databaseId)), true))
{
file.WriteLine(value.editor); // Write the file.
}
return msg;
}
else
{
return msg1;
}
}
catch (Exception ex)
{
// Write to log, show an error message to the user
}
}
}
I was wondering if I might be able to get some assistance as have hit an error with some code I am working on!
When clicking my login button I get the following at Line 37:
"No value given for one or more required parameters.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: No value given for one or more required parameters."
Any ideas?
Help gratefully appreciated
Thanks
Jack! :)
protected void btnLogin_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["CameraWarehouseDB"].ConnectionString);
//Opens connection with database
conn.Open();
//Declared a string - checks to see if username already exisits in the database.
string checkusername = "SELECT COUNT (*) FROM [Customer] WHERE CustomerUserName= '" + txtUserName.Text + "'";
//If count is 1, it means its already exisits, so cannot be used again and triggers alert
OleDbCommand com = new OleDbCommand(checkusername, conn);
//Replace removes any spaces the user make have accidentally inputed in the text box
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
//Verying username and password - Checks for password in database based on entered username
conn.Open();
string checkpassword = "SELECT Password FROM [Customer] WHERE CustomerUserName= '" + txtUserName.Text + "'";
OleDbCommand passwordcom = new OleDbCommand(checkpassword, conn);
string password = passwordcom.ExecuteScalar().ToString();
//Verify password based on entered password in password text box
if (password == txtPassword.Text)
{
Session["New"]=txtUserName.Text;
Response.Write("Password is correct");
}
else
{
Response.Write("Incorrect password entered, please try again");
}
}
else
{
Response.Write("Incorrect user name entered, please try again");
}
conn.Close();
}
}
I wrote this code in my login page. My code doesn't any error but update query doesn't apply on my database.
Fist query works and I redirect to index.aspx but update query (second query) doesn't apply!!!!
protected void btnLogin_Click(object sender, EventArgs e)
{
Database db1 = new Database();
string query = "select * from Admins where UserName=#username and cast(Password as varbinary)=cast(#password as varbinary)";
SqlCommand smd = new SqlCommand(query, db1.sc);
smd.Parameters.AddWithValue("#username", txtUsername.Text);
smd.Parameters.AddWithValue("#password", General.CreatePasswordHash(txtPassword.Text));
SqlDataReader sdr = smd.ExecuteReader();
smd.Parameters.Clear();
if (sdr.Read())
{
Session.Add("username", sdr[0].ToString());
string nowEnter = sdr[5].ToString();
query = "update Admins set LastEnter=#lastEnter, NowEnter=#nowEnter where UserName=#username";
string now = General.getPersianDateNow() + " ساعت " + General.getPersianTimeNow();
smd.CommandText = query;
smd.Parameters.AddWithValue("#lastEnter", nowEnter);
smd.Parameters.AddWithValue("#nowEnter", now);
smd.Parameters.AddWithValue("#username", sdr[1].ToString());
sdr.Close();
smd.ExecuteNonQuery();
Response.Redirect("~/admin/Index.aspx", false);
}
else
{
lblError.Visible = true;
}
}
In my opinion the problem is with index of sdr. First one you invoke
Session.Add("username", sdr[0].ToString());
Two lines below you use
smd.Parameters.AddWithValue("#username", sdr[1].ToString());
Anyway the safest way is to create select statement with named colums instead of using *
Check that the value you are using for the username exists in the table.
You're also adding the same parameter twice. I don't know how the SqlCommand class will handle that and I can't test it right now, but I think it might be a good idea to clear your parameters (smd.Parameters.Clear()) between executions.
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);
I am building a Forum in ASP.Net but have a small problem.
I have 1 user who creates a topic and can write a post to it fine, but if another user logs in, it won't insert the post into the database. It's returning that it does but nothing inserts. The original user can login and still post but no-one else can.
this is my code in behind
protected void addPostBtn_Click(object sender, EventArgs e)
{
//Define ADO.NET objects.
string insertSQL;
string topic = Request.QueryString["topicid"].ToString();
insertSQL = "INSERT INTO Posts (TopicID, PostBody, PUserID)"
+ "VALUES (#Topic, #NewPostText, #PUserID)";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
// Try to open the database and execute the update
int added = 0;
try
{
cmd.Parameters.AddWithValue("#Topic", topic);
cmd.Parameters.AddWithValue("#NewPostText", newPostText.InnerText);
cmd.Parameters.AddWithValue("#PUserID", Session["User_ID"]);
con.Open();
added = cmd.ExecuteNonQuery();
lblResults.Text = "Your post has been added";
}
catch (Exception err)
{
lblResults.Text = "Error inserting record. " + err.Message;
}
finally
{
con.Close();
}
if (added > 0)
{
this.BindRepeater();
}
}
I don't get any errors at all. It says it submitted fine, but it's not in the database unless the original poster does it.
EDIT:
Just realized it's to do with my view. This is my current view that it's reading from
SELECT dbo.Posts.PostBody, dbo.Posts.PostDate, dbo.Posts.PostID, dbo.[User].username, dbo.Topic.TopicID
FROM dbo.Topic RIGHT OUTER JOIN
dbo.Posts ON dbo.Topic.TopicID = dbo.Posts.TopicID LEFT OUTER JOIN
dbo.[User] ON dbo.Topic.TUserID = dbo.[User].UserID AND dbo.Posts.PUserID = dbo.[User].UserID
But it's returning NULL now for the other users names
The view needs to be as follows
SELECT dbo.Posts.PostBody, dbo.Posts.PostDate, dbo.Posts.PostID, dbo.[User].username, dbo.Topic.TopicID
FROM dbo.Topic LEFT OUTER JOIN
dbo.Posts ON dbo.Topic.TopicID = dbo.Posts.TopicID LEFT OUTER JOIN
dbo.[User] ON dbo.Posts.PUserID = dbo.[User].UserID