Error trying to add filename to end of string: - c#

Error trying to add filename to end of string:
if (FileUploadControl.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 filename = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
// error on this line filename only assignment, call can be used as a statement
FileUploadControl.SaveAs(Server.MapPath(fileuploadpath));
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
If I try it this way:
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
I get a mysql error as there is no filename added to the end of the path (btw im only trying to save the path not the image) altho technically i should still be able to insert half a filepath into sql so maybe this error isnt related to my original upload method using the code above. But obviously I still need the full pathname.
The file could not be uploaded. The following error occured: ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.5.9]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''C:\Users\Garrith\Documents\Visual Studio 2010\WebSites\WebSite1\userdata\1\uplo' at line 1

You are using Server.MapPath twice on the same string. Please remove it from anyone location so that the path mapped according to server may not be mapped again.
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
FileUploadControl.SaveAs(Server.MapPath(fileuploadpath));
You may do it like this...
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
FileUploadControl.SaveAs(fileuploadpath);

you are getting this error as the first character in you path is ~. What you have to do is try removing this character and then save the string in your database.
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath.Substring(1,fileuploadpath.Length - 1) + "')", cn);

its ok managed to do it myself with this:
//string filename = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}

Related

How to programmatically impose security on a programmatically created MS SQL database in C#

I'm a complete beginner in setting up databases dynamically. I found this code which is used to create a database:
String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
My problem is that how should I prevent other applications from accessing the created database without specifying credentials like a username and password? I want to be able to do this programmatically (without using MS SQL Server Studio) since it is deployed along with the C# application on the customer's PC.
I have tried this for fun a long time ago, from MSDN. Give it a try:
public static void AddUsersToDatabase(string databaseserver, string databasename, string usertobeadded)
{
using (SqlConnection conn = new SqlConnection("server=" + databaseserver + "; database=" + databasename + "; User ID=WPDOMAIN\\spdev; Integrated Security=SSPI; password=Password123;"))
{
conn.Open();
string password = "Password123";
string sql = "CREATE LOGIN " + usertobeadded + " WITH PASSWORD = '" +
password + "'; USE " + databasename + "; CREATE USER " + usertobeadded + " FOR LOGIN " + usertobeadded + ";";
SqlCommand cmd = new SqlCommand(sql);
cmd.ExecuteNonQuery();
conn.Close();
}
}

access denied error while connecting to newly restored MDF database

I'm restoring a SQL Server .bak file on SQL Server Express. But after restoring the database, I cannot use it in my code, it seems that the file is somehow locked, and the only way is copying it to another folder, also when I try to copy the .mdf file (using Windows Explorer) I get a warning about admin permission. I cannot copy this file using C# File.Copy (unauthorizedaccessexception, access denied), here is my code:
SqlConnection myConn = new SqlConnection("Server=" + sqlname + ";Integrated security=SSPI;database=master");
string dbname = "tmpDB" + DateTime.Now.Ticks.ToString();
str = "CREATE DATABASE " + dbname + " ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = '" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + ".mdf') " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = '" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + ".ldf') ";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
myCommand.Dispose();
str = #"RESTORE DATABASE [" + dbname + "] FROM DISK = N'" + openDialogConvert.FileName + #"' WITH FILE = 1, MOVE N'IODB_Data'
TO N'" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + #".mdf', MOVE N'IODB_Log'
TO N'" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + #".ldf', REPLACE ";
myCommand = new SqlCommand(str, myConn);
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConn.Close();
//here I'm going to connect to my newly created & restored database, but I get access denied error
SqlConnection sql = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + #"\" + dbname + ".mdf ;Integrated Security=True");
sql.Open();
What is going wrong here? I want to connect to my newly restored database as soon as I restore my database.
I get following error when I try to connect to my newly created & restored .mdf:
Unable to open the physical file "D:\9 mordad fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635110451805001328.mdf". Operating system error 5: "5(Access is denied.)".
An attempt to attach an auto-named database for file D:\9 mordad fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635110451805001328.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I suspect it may be already attached.
Can you connect using:
new SqlConnection("Server=" + sqlname +
";Integrated security=SSPI;" +
"database=" + dbname);

Restore from code doesn't work and provides no errors

I'm having a difficult time restoring several databases with my C# script. It's also not providing any errors -- it just does nothing.
Here's the code:
// Connect to SQL Server
SqlConnection conn = new SqlConnection("Data Source=SERVERNAME;" + "Integrated Security=SSPI;" + "Connection timeout=60");
StreamWriter logFile = new StreamWriter(#"F:\Backups\log.txt");
try{
conn.Open();
}catch(Exception e){
string errorTxt = "There was an error connecting to the server: " + e.ToString();
logFile.WriteLine(errorTxt);
}
// Get Directory
DirectoryInfo source = new DirectoryInfo(#"F:\Backups\SERVERNAME\");
foreach(FileInfo fi in source.GetFiles()){
// We need to get the DB name:
string filename = fi.Name.ToString();
int bkpIndex = filename.IndexOf("_backup");
string sql = "USE master RESTORE DATABASE " + filename.Substring(0, bkpIndex) + " FROM DISK = '" + fi.FullName + "' WITH REPLACE";
try{
Console.WriteLine("Restoring {0}.", filename.Substring(0, bkpIndex));
logFile.WriteLine("SQL: {0}", sql);
SqlCommand cmd = new SqlCommand(sql, conn);
}catch(Exception ex){
logFile.WriteLine("Error restoring {0}: " + ex.ToString(), filename.Substring(0, bkpIndex));
}
}
logFile.Close()
conn.Close()
You're not executing the command anywhere... Try ExecuteNonQuery!
e.g.
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();

How to convert last insert id into string?

I have a create account page and on the page I have one button to insert all the details into two seperate tables one of the tables Pictures is dependant on the User table 1:1 relationship via UserID.
I have written some code to try get the last insert id so I can insert into the pictures table:
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
}
}
}
Not sure if this is correct and I also need to know how to convert the select statement into a string so I can retrieve the UserID from the User table, see database structure:
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;");
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 + "')SELECT LAST_INSERT_ID()", cn);
//OdbcCommand sc = new OdbcCommand("SELECT LAST_INSERT_ID()", cn);
//convert LAST INSERT into string theUserId
//using (DataTable dt = DataTier.ExecuteQuery(cmd))
////error for datatable and datatier
//if (dt.Rows.Count == 1)
//{
// //Read the new ID from the record that has just been inserted
// string theUserId = dt.Rows[0]["UserID"].ToString();
using (OdbcDataReader reader = cmd.ExecuteReader())
{
string theUserId = String.Format("{0}", reader.GetString(0));
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);
cn.Open();
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
}
}
}
You can use a query similar to the following to post a record, then get the ID.
string sQuery = #"INSERT INTO [ExpenseType]
(
[ExpenseTypeName]
,[Deleted]
,[IsTaxable]
,[UpdatedDate]
,[UpdatedUser]
,[ParentCategoryComponentID]
,[CategoryComponentID]
,[NLNominalAccountID]
,[SYSTaxCodeID]
)
VALUES
(
#ExpenseTypeName
,#Deleted
,#IsTaxable
,#UpdatedDate
,#UpdatedUser
,#ParentCategoryComponentID
,#CategoryComponentID
,#NLNominalAccountID
,#SYSTaxCodeID
)
SELECT SCOPE_IDENTITY() AS 'ID' ";
using ( SqlCommand oSqlCommand = new SqlCommand( sQuery ) )
{
oSqlCommand.Parameters.AddWithValue( "#ExpenseTypeName", this.ExpenseTypeName );
oSqlCommand.Parameters.AddWithValue( "#Deleted", this.Deleted );
oSqlCommand.Parameters.AddWithValue( "#IsTaxable", this.IsTaxable );
oSqlCommand.Parameters.AddWithValue( "#UpdatedDate", base.GetUpdatedDate() );
oSqlCommand.Parameters.AddWithValue( "#UpdatedUser", base.GetUpdatedUser() );
oSqlCommand.Parameters.AddWithValue( "#ParentCategoryComponentID", this.ParentCategoryComponentID );
oSqlCommand.Parameters.AddWithValue( "#CategoryComponentID", this.CategoryComponentID );
oSqlCommand.Parameters.AddWithValue( "#NLNominalAccountID", this.NLNominalAccountID );
oSqlCommand.Parameters.AddWithValue( "#SYSTaxCodeID", this.SYSTaxCodeID );
using ( DataTable dt = DataTier.ExecuteQuery( oSqlCommand ) )
{
if ( dt.Rows.Count == 1 )
{
//Read the new ID from the record that has just been inserted
string RecordID = dt.Rows[ 0 ][ "ID" ].ToString();
}
}
}
Note the SELECT SCOPE_IDENTITY() AS 'ID' at the end of the query.
and
if ( dt.Rows.Count == 1 )
{
//Read the new ID from the record that has just been inserted
string RecordID = dt.Rows[ 0 ][ "ID" ].ToString();
}

ExecuteNonQuery: Connection property has not been initialized?

I get an error in my code:
ExecuteNonQuery: Connection property has not been initialized.
This could be due to the line in this code:
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
Full code:
{
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();
}
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
//FileUploadControl.SaveAs(Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
There is another problem, I dont think its an insert I want as this is going to make a duplicate entry within my database, would it just be a case of changing it from INSERT INTO to UPDATE?
Also is there a way to overwrite upon uploading the image? Atm it just saving the image into the same folder as the one I already have? The first image or any image obviously isnt going to have the same file name so how would I go about overwriting any image in the folder with the one im uploading?
EDIT:
New error (fileupload works as its stored in the correct area but passing the fileupload to the insert statement is abit wonky)
I get the error
The file could not be uploaded. The following error occured: ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.5.9]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''C:\Users\Garrith\Documents\Visual Studio 2010\WebSites\WebSite1\userdata\1\uplo' at line 1
Which is kind of strange?
All im trying to do is save the filepath+filename in mydb my attempt at passing to the insert has obviously failed.
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=root; Password=commando;");
cn.Open();
string filename = Path.GetFileName(FileUploadControl.FileName);
//FileUploadControl.SaveAs(Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
StatusLabel.Text = "Upload status: File uploaded!";
//some kind of function to take the path then enter it into my insert syntax?
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
As you can see on this line:
VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
im missing the "filename" i tryed this:
VALUES ('" + theUserId + "' , '" + fileuploadpath, filename + "')", cn);
Cheap shot lol but worth a go I guess and it cryed as it always does!
You need to associate the connection with the cmd:
OdbcCommand cmd =
new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
cmd.Connection = cn; // <--------
cmd.ExecuteNonQuery();
Also, remove the braces here:
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};
Server=localhost; Database=gymwebsite2; User=root; Password=commando;"); cn.Open();
}
You want to create the OdbcCommand using CreateCommand on OdbcConnection. The code as posted does not tie cmd to cn. Also, you should use CommandParameters instead of inlining the values (to guard against SQL injection attacks).
OdbcCommand cmd = cn.CreateCommand();
cmd.CommandText = "INSERT INTO Pictures (UserID, picturepath) VALUES (?, ?)";
cmd.Parameters.Add(new OdbcParameter("#UserID", OdbcType.Int, theUserID));
cmd.Parameters.Add(new OdbcParameter("#picturepath", OdbcType.VarChar, fileuploadpath));
cmd.ExecuteNonQuery();
This is the problem:
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')"); <--- there is no connection intialize here
Change it to:
//eg: odbconnection cn = new odbcconnection();
string fileup = fileupload + "," filename;
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileup.ToString() + "')",cn);
Regards
The following is syntactically fubar'd:
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();
}

Categories