failed to copy database as backup file - c#

Description:
I am trying to copy my sql database as backup file, once I login, and redirect to backup.aspx and I clicked backup button, it prompt me an error output
If I open directly backup.aspx I can copy the database without any error
I knew that the problem is my database is connect after I login, so it tell me it is being used by another process
What I want to ask is that anyway can solved this problem ?
I aim to disconnect from db on page load but I cant make it, it still prompt me the same error
Error message:
The process cannot access the file 'C:\Users\Roy\Desktop\backup
fyp\10-18-2011\WebSite5\App_Data\Database.mdf' because it is being
used by another process.
Code for button click:
string time1 = DateTime.Now.ToString("dd-MM-yyyy hh-mmtt");
Directory.CreateDirectory(#"C:/SME-Online/" + time1);
string destination = #"C:/SME-Online/" + time1;
string source = Server.MapPath(#"~/App_Data");
File.Copy(Path.Combine(source, "Database.mdf"), Path.Combine(destination, "Database.mdf"), true);
File.Copy(Path.Combine(source, "Database_log.LDF"), Path.Combine(destination, "Database_log.LDF"), true);

You should backup database first and then copy *.bak file as backup, here some code to get you started, of course you can alter that query or filename generation code to suit it to your needs, be sure to check Backup T-SQL statement help.
public void BackupDatabase()
{
/// this method should get opened connection
SqlConnection conn = GetOpenedDBConnectionFromSomewhere();
string dbName = conn.Database;
string backupFName = "c:\\MSSQLData\\Backup\\" + dbName + "_" + DateTime.Now.Ticks.ToString() + ".bak";
string sql = "BACKUP DATABASE [" + conn.Database + "] TO DISK = '" + backupFName + "'" +
"WITH NOFORMAT, INIT, NAME = 'Backup of DB:" + dbName + "', SKIP, NOREWIND, NOUNLOAD, STATS = 10;";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
}

Related

Unable to Format Message Error when connecting to DB

I am currently working on a function that connects to a database through a connection string that includes the parameter: "Provider=OleDB.Provider". When I ran the code I get the following error:
Unable to format message, ID: 0xc0010001: Class not registered
I have also made sure the file is located on the database and the name parameter I am passing matches the name of the Database, since I got this from the msdn webstie:
"The variable cannot be found. This occurs when an attempt is made to retrieve a variable from the Variables collection on a container during execution of the package, and the variable is not there. The variable name may have changed or the variable is not being created."
Some of the code I have for the connection is(error happens on conn.open):
using (OleDbConnection conn = new OleDbConnection("Provider=mrOleDB.Provider.2;Persist Security Info=False;User ID=\"\";Data Source=" + data_source + ";Location=\"Provider=SQLOLEDB.1;Persist Security Info=False;User ID=" + user + "; PWD=" + password + ";Initial Catalog='" + jobnumber + "';Data Source=" + oDatabase + ";OLE DB Services=-4\";Extended Properties=\"\";Initial Catalog=" + oroot + jobnumber + "\\" + jobnumber + ".mdd;Mode=ReadWrite;MR Init MDSC=\"\";MR Init MDSC Access=2;") {
//(Theres a little more on the connection string but its adding settings for the data collection similar to the last part: MR Init mdsc)
try{
conn.Open();
}
catch(exception er)
Console.Writelin(er.message)
}
Could you please help me understand this error, or what it means? I tried looking for some solutions but was not able to find a solution that is similar to my issue. Thank you for all your help!

Delete specific files in directory

I'm uploading PDF files into a folder using FileUpload control in this way:
string pdfFilPath = Path.GetFileName(FileUpload1.PostedFile.FileName.ToString());
string pdfPath = Server.MapPath(#"~/PDF/" + pdfFilPath);
FileUploadFoto.PostedFile.SaveAs(pdfPath);
But at the same time I'm inserting an Id, Description and PDFUrl in the database for this file:
SqlCommand cmd = new SqlCommand("INSERT INTO Book(Description, PDFUrl)
VALUES (''' + textBoxDescription.Text + "','" + "~/PDF/" + pdfFilPath + "')", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
If I select all columns from the database and show them on a GridView, they appear as follows:
ID Description PDFUrl
1 In this book... ~/PDF/jQuery in Action.pdf
Now, if I want to delete a book review, all I do is ("DELETE FROM Book Where Id='" + textBoxId.Text + "'", conn);, but this will delete only the Id,Description and the PDFUrl from the database.
My question is: How can I delete the PDF file at the same time when I delete the review from the database?
Don't forget though, you should check to see if the file exists before you delete it or else it will throw an error. This can happen if the user refreshes the postback.
if (File.Exists(Server.MapPath(PDFUrl))
{
File.Delete(Server.MapPath(PdfUrl));
}
If all you have is the ID, then first fun a query to get the PDFUrl from the DB based on the ID.
Then:
FileInfo fi = new FileInfo(Server.MapPath(PDFUrl));
fi.Delete;
Source: MSDN
Also, you should really use parameterized queries for reasons explained on the OWASP SQL Injection Prevention Cheat Sheet.
You can just create a method which delete the file from the directory, after that you delete the file from the database.
public void DeleteFile(string id)
{
FileInfo fi = new FileInfo(Server.MapPath(PDFUrl));
fi.Delete;
SqlComand cmd = new SqlComand("DELETE FROM Book Where Id='" + textBoxId.Text + "'", conn);
cmd.ExecuteNonQuery();
}

Sql connection not working in release

I've trouble with my program, everything works in debug mode but when i switch to release i'm getting InvalidOperationException:
_sqlcon.ConnectionString = "Data Source=" + Properties.Settings.Default.serverAdress + ";" + "Initial Catalog=" + Properties.Settings.Default.initialDB + "; User ID=" + Properties.Settings.Default.sqlID + "; Password=" + Properties.Settings.Default.sqlPass + ";" + "Connect Timeout=" + Properties.Settings.Default.timeOut + "; Asynchronous Processing = true;";
this is my connection string
Data Source=.\\SQLEXPRESS;Initial Catalog=visondb; User ID=sql; Password=test;Connect Timeout=30; Asynchronous Processing = true;
and i try simple to open connection using
try
{
// await dbConnAsync(_sqlcon);
_sqlcon.Open();
}
catch (SqlException ex)
{
MessageBoxResult result = System.Windows.MessageBox.Show(ex.ToString());
}
But in release it's not working and when i'm using exe i just get window "program stop responding".
Where to look for error ?
My best guess (based on the limited info here) would be that one of the values you're pulling from your release Properties.Settings.Default to generate your connection string is either
blank (an empty string), or
not what you expect it to be.
Thus creating an invalid connection string.
You should debug on the line before _sqlcon.Open(); and make sure the connection string is what you expect it to be when you're in release mode.

How to Create an Excel File in C#; Office 2007; Win 7 64bit?

Previously my C# app used this command to create an Excel file:
try
{
//SELECT INTO command
string cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AccfilePath +
";Persist Security Info=False";
ConnOpen(cnStr);
using (connectionToDatabase)
{
//Give the Export Table (destination) a Name
//baseTblName = dt.TableName;
//Generate the SQL string to SELECT * INTO the NEW table in destination
string selectcmd = "SELECT * INTO [Excel 12.0;Database=c:\\"+ExfilePath+"]." + tblName + " FROM " + tblName;
using (OleDbCommand createCmd = new OleDbCommand(selectcmd, connectionToDatabase))
{
createCmd.ExecuteNonQuery();
}
ConnClose();
}
}
I have moved to Win 7 64 bit and the OleDbCommand now gives me a "Failure Creating File". I have gone so far as to make the user an Administrator because I assumed it was a security issue.
There is no problem with this Oledb command. I have been fighting 64bit issues all day and assumed there was. My file path had incorrect syntax; after I fixed that it worked as expected.

Error while opening a connection to MS Access 2007 file: Cannot open the MS Office Access database engine workgroup information file

Cannot open the MS Office Access database engine workgroup information file - When I have code as posted.
What I am trying to do in my code is to create MS Access 2007 file and then set the user name and password to it from my program. What am I doing wrong here?
Error occurs here: objOleDbConnection.Open();
EDIT: I have made some changes, seems like it opens a connection but the command is incorrect.
Now problem is here:
objOleDbCommand.CommandText =
"ALTER USER " + storedAuth.UserName +
" PASSWORD [" + storedAuth.Password + "] []";
The entire code:
// Creating an object allowing me connecting to the database.
OleDbConnection objOleDbConnection = new OleDbConnection();
objOleDbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + sfdNewFile.FileName + ";Persist Security Info=False";
// Creating command object.
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.Connection = objOleDbConnection;
try
{
objOleDbConnection.Open();
objOleDbCommand.CommandText = "ALTER USER " +
storedAuth.UserName + " PASSWORD [" +
storedAuth.Password + "] []";
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
objOleDbConnection.Close();
}
To change an Access DB password, you must it open in exclusive mode. Try adding this to your connection string ;Exclusive=1.
createMSFile.Create("Provider=Microsoft.ACE.OLEDB.12.0;Exclusive=1;Data Source=" +
sfdNewFile.FileName);
Well, the error you are getting suggests someone else is keeping the file open, which prevents the password change...
HelpNeeder, I think the problems you are experiencing should first be solved in your other question:
Error tells me I haven't close the connection, but haven't I?
Thanks!

Categories