access denied error while connecting to newly restored MDF database - c#

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);

Related

C# WPF connecting to MySql server and create db if doesn't exist

I'm trying to create new DB if it doesn't exist when pressing the button "Restore" but it keeps jumping to the exception. What am i doing wrong?
private void Button_Click_Restore(object sender, RoutedEventArgs e)
{
string CreateDatabase;
string dbInfo = "DATABASE=" + Database.Text;
string connectionString = "SERVER=" + Hostname.Text + ";" + dbInfo + ";" + "UID=" + User.Text + ";" + "PASSWORD=" + Password.Text + ";" + "PORT=" + Port.Text;
MySqlConnection connection = new MySqlConnection(connectionString);
CreateDatabase = "CREATE DATABASE IF NOT EXISTS " + Database.Text + " ; ";
MySqlCommand command = new MySqlCommand(CreateDatabase);
try
{
connection.Open();
command.ExecuteReader();
MessageBox.Show("DB has been created.");
}
catch (Exception)
{
MessageBox.Show("Please Check Server and Database name.");
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}

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();
}
}

Error in restoring BAK to MDF file

I'm using following code to restore a BAK file to an MDF file, initially I create a database and then try to restore it using my BAK file, but I get some errors:
I use an open file dialog to select my BAK file
openDialogConvert.ShowDialog();
RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");
string sqlname = "";
if (instances.Length > 0)
{
foreach (String element in instances)
{
if (element == "MSSQLSERVER")
sqlname = System.Environment.MachineName;
else
sqlname = System.Environment.MachineName + #"\" + element;
}
}
String str;
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 = '" + Environment.CurrentDirectory + "\\" + dbname + ".mdf') " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = '" + Environment.CurrentDirectory + "\\" + dbname + ".ldf') ";
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);
}
myCommand.Dispose();
str = #"RESTORE DATABASE [" + dbname + "] FROM DISK = N'" + openDialogConvert.FileName + #"' WITH MOVE N'IODB_Data'
TO N'" + Environment.CurrentDirectory + #"\\" + dbname + #".mdf', MOVE N'IODB_Log'
TO N'" + Environment.CurrentDirectory + #"\\" + dbname + #".ldf', REPLACE ";
myCommand = new SqlCommand(str, myConn);
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConn.Close();
my new (empty) database is created successfully but I get strange errors while trying to restore the BAK file in this newly created database.
I get following error using the above code:
The operating system returned the error '32(failed to retrieve text
for this error. Reason: 15105)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.mdf'.
File 'IODB_Data' cannot be restored to 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.mdf'. Use
WITH MOVE to identify a valid location for the file.
The operating system returned the error '32(failed to retrieve text
for this error. Reason: 15105)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.ldf'.
File 'IODB_Log' cannot be restored to 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.ldf'. Use
WITH MOVE to identify a valid location for the file.
Problems were identified while planning for the RESTORE statement. Previous messages provide details.
RESTORE DATABASE is terminating abnormally.
but when I insert a 'GO' at the end my command, I get following error:
Incorrect syntax near GO
what is going wrong here?
of course I've tested the restore operation successfully with SQL server management studio and I've found correct logical names for my BAK file (in fact I've copied the script from MSSMS)
You can also try this.
Step 1 - connect the database server using MS SQL Server Management
Studio.
step 2 - Find the database in the left pane & right-click to choose
the restore option.
Step 3 - Choose the destination and source for restoration.
Step 4 - Browse for the backup file from the device & click on ok
Step 5 - Select the database you want to restore from the list and
click ok.
After completing the restore process, your database will be ready to use.
Note: You must create a new database to restore the old one.

Create Oracle database and schema programmatically ADO.NET

How can I create a oracle database programmatically in ADO.NET and a schema for it with userId + password so I can just go to my non-favorite tool the sql oracle developer tool where I just create a connection entering:
connectionstring name
UserId(schema)
password
I've done it with SQL before but never tried with ADO.NET ...
string connectionString = "...";
string oracleDataPath = "C:\\PATH_TO_ORADATA\\";
string username = "NEW_USER";
string password = "NEW_PWD";
string schema = "NEW_SCHEMA";
using (OracleConnection conn = new OracleConnection(connectionString))
{
conn.Open();
OracleCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLESPACE \"" + schema + "\" DATAFILE '" + oracleDataPath + schema + ".DBF' SIZE 10M AUTOEXTEND ON NEXT 1M";
cmd.ExecuteNonQuery();
cmd.CommandText = "CREATE USER \"" + username + "\" IDENTIFIED BY \"" + password + "\" DEFAULT TABLESPACE \"" + schema + "\" TEMPORARY TABLESPACE TEMP";
cmd.ExecuteNonQuery();
cmd.CommandText = "GRANT CONNECT TO \"" + username + "\"";
cmd.ExecuteNonQuery();
cmd.CommandText = "ALTER USER \"" + username + "\" QUOTA UNLIMITED ON \"" + schema + "\"";
cmd.ExecuteNonQuery();
}
Use the ADMIN/DBA account on the connection string.
Set oracleDataPath with the path where your Oracle keeps its data files.
Let me know if it works :-)

Error trying to add filename to end of string:

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;
}
}
}
}

Categories