My fileupload isnt creating the path if its not there, its only working if the folder belonging to the user id is actually already in place, I need it to upload whether the folder is there or not.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
string filenameDB = Path.GetFileName(FileUpload1.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
Label2.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES (" + theUserId + ", '" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
OdbcCommand md = new OdbcCommand("UPDATE User SET flag = 0 WHERE UserId = '" + theUserId + "'", cn);
// OdbcCommand cmd = new OdbcCommand("UPDATE Pictures SET picturepath ='" + fileuploadpaths + "' WHERE UserId = '" + theUserId + "'", cn);
md.ExecuteNonQuery();
Response.Redirect("UserProfileWall.aspx");
}
catch (Exception ex)
{
Label2.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Why don't you simply check if the folder is already created, if it's not create it. if(System.IO.Directory.Exists("YourDirectoryPath")) do your stuff;
The command you want to utilize is
string fileuploadDir = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
if(!System.IO.Directory.Exists(fileuploadDir)
{
System.IO.Directory.CreateDirectory(fileuploadDir)
}
Insert this after:
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
Corrected based on comments below.
string dirPath= Path.GetDirectoryName(fileuploadpath);
if(!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
Related
I want to update my sql table. I was searching here and found solutions on how to go onto that problem. But sadly it just wont update the database. I have no clue what the problem is.
I checked to sql command a couple of times for writing mistakes but couldnt find any or fixed them but still sadly nothing. I suppose it's something within the try block but cant find it out.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I hope someone can help me find my mistake.
EDIT: when i try it out it seems to work as the windows pops up with "workd" but the database is unchanged.
As MichaĆ Turczyn wrote in his answer, you have some problems with your code.
I agree with everything he wrote, but I thought you might benefit from seeing how your code should look like - so here you go:
var connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
var sql = "UPDATE Employees SET LastName = #LastName, FirstName = #FirstName, Title = #Title ... ";// repeat for all variables
try
{
using(var connection = new SqlConnection(connetionString))
{
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#LastName", SqlDbType.NVarChar).Value = Lnamestring;
command.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = Fnamestring;
command.Parameters.Add("#Title", SqlDbType.NVarChar).Value = Titelstring;
// repeat for all variables....
connection.Open();
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
MessageBox.Show($"Failed to update. Error message: {e.Message}");
}
Few issues with your code:
1) Use using, when working with IDisposable objects, in your case connection and command.
2) As suggested in comments, use SqlCommandParameters instead of concatenating strings for security reasons (google "preventing from SQL injections")
3) You don't execute your query! How you want it to make an impact if you don't do it? There's, for example, method like ExecuteNonQuery in SqlCommand class.
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Don't forget to execute the command
Try to get the stacktrace or error message from Exception as much as possible. For example: MessageBox.Show($"Can not open connection ! {e.GetBaseException().Message}, {e.StackTrace}");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "update CarTb1 set ( #RegNo , #MOdel , #Price , #Available where #Brand);";
cmd.CommandType = System.Data.CommandType.Text;
Da = new SqlDataAdapter("Select * From CarTb1", con);
Da.Fill(Dt);
cmd.Parameters.AddWithValue("#RegNo", txtRegnumber.Text);
cmd.Parameters.AddWithValue("#Brand", combBrand.Text);
cmd.Parameters.AddWithValue("#Model", txtModel.Text);
cmd.Parameters.AddWithValue("#Price", txtPrice.Text);
cmd.Parameters.AddWithValue("#Color", txtColor.Text);
cmd.Parameters.AddWithValue("#Available", combAvailable.Text);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited Successfally");
con.Close();
ClearData();
Please use the ExecuteNonQuery() instead of SqlDataAdapter:
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
I am developing a database application in C#.NET and SQL Server 2012.
Some of my SQL statements are not working properly . When I execute the code it does not give any error. But when I try to delete something or Update a record, I does not do that. The code lies below:
public void updateFinalTable()
{
DialogResult result = MessageBox.Show("Please make sure no fields are empty or they will get changed. \n\t\t Do you want to continue?",
"Important Note",
MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE fianlTable SET AccountNumber='" + textBox1.Text + "', Date='" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "', CustomerName='" + textBox3.Text + "' , Debit='" + txtDebit.Text + "', Credit='" + txtCredit.Text + "', Balance='" + txtBalance.Text + "' WHERE Id LIKE '" + textBox4.Text + "' ", con);
cmd.ExecuteNonQuery();
this.fianlTableBindingSource.AddNew();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("select * from fianlTable WHERE (UserName LIKE '" + LoginSession.UserID + "')", con);
sda.Fill(dt);
dataGridView1.DataSource = dt;
refresh();
con.Close();
MessageBox.Show("Record Updated Successfully!");
catch (Exception)
{
MessageBox.Show("Record Could Not be updated...! ");
}
}
}
Similar is the case with delete operation . Both codes give no error but inside the database no change is observed.
You have used Like in your where condition instead of =. So your code should be like this -
SqlCommand cmd = new SqlCommand("UPDATE fianlTable SET AccountNumber='" + textBox1.Text + "', Date='" +
dateTimePicker1.Value.ToString("MM/dd/yyyy") + "', CustomerName='" +
textBox3.Text + "' , Debit='" + txtDebit.Text + "', Credit='" +
txtCredit.Text + "', Balance='" + txtBalance.Text +
"' WHERE Id = '" + textBox4.Text + "' ", con);
ATTENTION This type of query potentially lead to SQL Injection. You better go with parametrized queries, like this -
string qry = = "UPDATE fianlTable SET AccountNumber = #accnt, CustomerName = #cname Where ID = #id)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#accnt", textBox1.Text);
cmd.Parameters.AddWithValue("#cname", textBox3.Text);
cmd.Parameters.AddWithValue("#id", textBox4.Text);
cmd.ExecuteNonQuery();
Incorrect syntax near 'C:'. Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
SqlConnection objcon = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True;");
SqlCommand sqlcmd = new SqlCommand();
protected void btnBackup_Click(object sender, EventArgs e)
{
try
{
string _DatabaseName = ddlDatabases.SelectedItem.Text.ToString();
string _BackupName = _DatabaseName + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + ".bak";
objcon.Open();
string sqlQuery = "BACKUP DATABASE " + _DatabaseName + " TO DISK = 'C:\\SQLServerBackups\\" + _BackupName + "' WITH FORMAT, MEDIANAME = 'Z_SQLServerBackups', NAME = '" + _BackupName + "';";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, objcon);
sqlCommand.CommandType = CommandType.Text;
int iRows = sqlCommand.ExecuteNonQuery();
objcon.Close();
lblMessage.Text = "The " + _DatabaseName + " database Backup with the name " + _BackupName + " successfully...";
ReadBackupFiles();
}
catch (SqlException sqlException)
{
lblMessage.Text = sqlException.Message.ToString();
}
catch (Exception exception)
{
lblMessage.Text = exception.Message.ToString();
}
}
Try the following:
SqlConnection objcon = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True;");
SqlCommand sqlcmd = new SqlCommand();
protected void btnBackup_Click(object sender, EventArgs e)
{
try
{
string _DatabaseName = ddlDatabases.SelectedItem.Text.ToString();
string cleandb=Path.GetFileNameWithoutExtension(_DatabaseName);
string _BackupName = cleandb + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + ".bak";
objcon.Open();
string sqlQuery = "BACKUP DATABASE [" + _DatabaseName + "] TO DISK='C:\\SQLServerBackups\\" + _BackupName + "'";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, objcon);
sqlCommand.CommandType = CommandType.Text;
int iRows = sqlCommand.ExecuteNonQuery();
objcon.Close();
lblMessage.Text = "The " + _DatabaseName + " database Backup with the name " + _BackupName + " successfully...";
ReadBackupFiles();
}
catch (SqlException sqlException)
{
lblMessage.Text = sqlException.Message.ToString();
}
catch (Exception exception)
{
lblMessage.Text = exception.Message.ToString();
}
}
I've removed the extra parameters on the backup command, surrounded the database name with brackets, and removed the spaces around the equals sign in DISK =
Ok new problem this is my full code I will explain what I'm trying to do and segment each part so you can see what it is I'm trying to achieve:
Full Code:
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;");
cn.Open();
OdbcCommand sc = new OdbcCommand(string.Format("SELECT picturepath FROM Pictures WHERE UserID ='{0}'", theUserId), cn);
OdbcDataReader reader = sc.ExecuteReader();
while (reader.Read())
{
if (System.IO.File.Exists(Convert.ToString(reader[0])))
{
System.IO.File.Delete(Convert.ToString(reader[0]));
}
}
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId +
"/uploadedimage/") +
Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "','" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Ok the first part I'm trying to do is select the picture path related to the userid then if a userid is there with the same userid as im trying to upload delete the file that exists(not stored in database hence the IO) this part doesn't work the file pathname of the current userid isn't being deleted.
OdbcCommand sc = new OdbcCommand(string.Format("SELECT picturepath FROM Pictures WHERE UserID ='{0}'", theUserId), cn);
OdbcDataReader reader = sc.ExecuteReader();
while (reader.Read())
{
if (System.IO.File.Exists(Convert.ToString(reader[0])))
{
System.IO.File.Delete(Convert.ToString(reader[0]));
}
}
The second part just inserts the new file upload path and name into my database related to the current userid (this works) the file is uploaded to the correct folder and its inserted into my database. I could change this to UPDATE rather than insert but atm its either or not to fussy.
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId +
"/uploadedimage/") +
Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "','" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
So my problem is why is my if statement not deleting the currently held record in my database for the path of the current image? All that happens is my new image is uploaded into the same folder but the old image still remains?
Remember though I'm not trying to delete the "same" file name a simple saveas would overwrite it which is already in my code, what I need is for my code to delete any image that is currently in the userid specific folder when I'm trying to save the new image upload.
Any thoughts some help on the code?
Thanks guys
Looking at your code, I believe SystemDown has the answer in the comments:
When you save the file to disk you use the following code:
// Even though you've just calculated the result of Path.GetFileName you
// redo it here?
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId
+ "/uploadedimage/")
+ Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
Then you store it in the DB as:
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
However when you delete the file you're not performing Server.MapPath:
System.IO.File.Delete(Convert.ToString(reader[0]));
Change that line to:
System.IO.File.Delete(Server.MapPath(Convert.ToString(reader[0])));
And it should all work.
you should use the server.mappath to find that if image is already exist or not then try to delete that im
Hey guys bit of a complication here, I have a create account page and it just inserts data into a mysql db:
protected void Button1_Click(object sender, EventArgs e)
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')", cn);
cmd.ExecuteNonQuery();
{
//e.Authenticated = true;
Response.Redirect("Login.aspx");
// Event useradded is true forward to login
}
}
}
But here is my problem on the create account page I have added a fileupload control and I would like to upload a image and save the imageurl in the pictures table:
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures VALUES picturepath ='" + fileuploadpaths + "' WHERE UserId = '" + theuserid + "'", cn);
cmd.ExecuteNonQuery();
The first problem is the sql syntax I need to combine the fileupload with my buttonclick so it would be INSERT INTO two tables User and Pictures but the problem after that is how on earth do I get the userid if the account isnt created yet? AHHH lol
Table structure:
So to sum it up I need to Insert user details into the user table and upload to the project file AND insert the imageUrl into the pictures table (stored like so ~/userdata/2/uploadedimages/bla.jpg) as you can see the pictures table is a 1-1 relationship to the user table so its dependant on the userid which be4 the account is created there is no userid so not sure if there is a way to stagger the code so the user details are inserted first then use a session to retrieve that userid then insert the imageurl into the pictures table?
Or Maybe there is some funky function that some clever person has already came upon this issue or maybe its just a simple sql syntax decombobulator.
P.S I KNOW ABOUT THE SQL INJECTION RISKS, please do not post about this. Thanks guys!
EDIT:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')", cn);
OdbcCommand sc = new OdbcCommand("SELECT LAST_INSERT_ID()", cn);
//convert LAST INSERT into string theUserId
string filenameDB = Path.GetFileName(FileUpload1.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
Label10.Text = "Upload status: File uploaded!";
OdbcCommand cm = new OdbcCommand("INSERT INTO Pictures (picturepath, UserId) VALUES ('" + fileuploadpaths + "', " + theUserId + ")", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Label10.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
//e.Authenticated = true;
//Response.Redirect("Login.aspx");
// Event useradded is true forward to login
}
}
}
If pictures is 1:1 with users, is it possible to put the picture path in the user table?
If not, MySQL has a last_insert_id() function allowing you to get the last auto-increment value from a table (in this case User) - usually the primary key.
You need to return the new user id from your user insert. From the mysql auto increment docs:
You can retrieve the most recent
AUTO_INCREMENT value with the
LAST_INSERT_ID() SQL function or the
mysql_insert_id() C API function.
These functions are
connection-specific, so their return
values are not affected by another
connection which is also performing
inserts.
Anyway, you'll need to store this return and pass it into related operations.
I can't see your table structure, but is it as simple as inserting into the User table, retrieving the UserID, preserving the UserID (maybe passing to the upload page on the query string, or using session, etc), and then using that UserID in the Pictures table insert? Here's documentation on how to get the unique ID from an inserted row in MySQL.