backup restore sql database through AttachDBFilename - c#

I am not able to create a backup of database saved in location like C:\database\mydb.mdf
error : Unable to create a backup
Backup sqlBackup = new Backup();
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "Archive";
sqlBackup.Database = databaseName;
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
//ServerConnection connection = new ServerConnection(serverName, userName, password);
ServerConnection connection = new ServerConnection(serverName);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
string dataBaseName = #"C:\database\mydb.mdf";
string serverName = #"Data Source=.\SQLEXPRESS;Integrated Security=True;User Instance=True";
string destinationPath = "C:\\mydb.bak";
Maybe I am passing wrong variables?
Please can anyone verify it and post me the right solution
thnx in advance.
PS: database is not password protected and can use mixed authentication

First of all - I guess some of your parameters are wrong:
ServerConnection connection = new ServerConnection(serverName);
Here, you need to pass just the server's name - so in your case, do not send in your whole connection string - just .\SQLExpress
As for your database name - I don't know if you can use SMO to backup an "attached" MDF file in SQL Server - normally, this would be the database name (the name of the database only - no file name, no extension) when the database is on the server.
string dataBaseName = #"C:\database\mydb.mdf";
So my suggestion here would be:
attach this MDF file to your SQL Server instance (which you have installed anyway)
give it a meaningful name, e.g. mydb
then use just the database name as your value here:
string dataBaseName = "mydb";
With these points in place, your code does work just fine in my case, at least...

Related

Failed to invoke the service.

I am getting this error:
Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.
Instance failure.
here is my code :
void ConnectToDb()
{
connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = #"(localdb)\MSSQLLocalDB";
connStringBuilder.InitialCatalog = "WRESTLING.MDF";
connStringBuilder.Encrypt = true;
connStringBuilder.ConnectTimeout = 30;
connStringBuilder.AsynchronousProcessing = true;
connStringBuilder.MultipleActiveResultSets = true;
connStringBuilder.IntegratedSecurity = true;
string temp = #"Server=EC2AMAZ-FN5N011\\MSSQLSERVER;Database=C:\APP_DATA\WRESTLING.MDF;Trusted_Connection=True;";
string temp1 = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=C:\APP_DATA\WRESTLING.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(temp);
comm = conn.CreateCommand();
}
When you want to connect to a local database file (.mdf) you can use the following connection string syntax with AttachDbFilename:
#"Data Source=(local);AttachDbFilename=C:\APP_DATA\WRESTLING.MDF;Integrated Security=True;Connect Timeout=30;"

C# SQL Connection String returning error

Hi I'm new when it comes to connecting to a server/database and was wondering why this returns an error.
I have a FastHost server with a database.
I've just put in an example IP but i have been using the one given on my control panel on the site.
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012" +
"Initial Catalog = DiscoverThePlanet" +
"User ID = TestUser" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
This returns the
Can not open Connection!" message.
I get the following show in my code:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I know my server is fine because i have connected to it on SQL Server Management studio and added tables and data.
You're missing a couple of ;
conn.ConnectionString =
"Data Source = 123.456.789.012" +
";Initial Catalog = DiscoverThePlanet" +
";User ID = TestUser" +
";Password = Test";
An even better solution is to use ConnectionStringBuilder.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "123.456.789.012";
builder["Initial Catalog"] = "DiscoverThePlanet";
builder["User ID"] = "TestUser";
builder["Password"] = "Test";
Console.WriteLine(builder.ConnectionString);
Or (as #Fischermaen mentioned) you can use the properties, instead of indexes. It's even more readable!
builder.DataSource = "123.456.789.012";
builder.InitialCatalog = "DiscoverThePlanet";
builder.UserID = "TestUser";
builder.Password = "Test";
Also, in this scenario you aren't using any user input, but beware of connection string injection when manually creating your connection string. ConnectionStringBuilder can help you avoid those.
A connection string injection attack can occur when dynamic string
concatenation is used to build connection strings that are based on
user input. If the string is not validated and malicious text or
characters not escaped, an attacker can potentially access sensitive
data or other resources on the server. For example, an attacker could
mount an attack by supplying a semicolon and appending an additional
value. The connection string is parsed by using a "last one wins"
algorithm, and the hostile input is substituted for a legitimate
value.
The connection string builder classes are designed to eliminate
guesswork and protect against syntax errors and security
vulnerabilities. They provide methods and properties corresponding to
the known key/value pairs permitted by each data provider. Each class
maintains a fixed collection of synonyms and can translate from a
synonym to the corresponding well-known key name. Checks are performed
for valid key/value pairs and an invalid pair throws an exception. In
addition, injected values are handled in a safe manner.
A last (and, in my opinion, best) alternative is to move your connectionstring from code into a config. This will make it much easier for you to use the same code in different environments.
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString];
And your config.
<connectionStrings>
<add name="MyConnectionString" connectionString="[ConnectionString goes here]" providerName="System.Data.SqlClient" />
</connectionStrings>
Add a semicolon after each part of your connection string code:
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
https://www.connectionstrings.com/sql-server/ should tell you more about the correct format.
Your connectionstring is not well formated, you forgot some ; :
"Data Source = 123.456.789.012;Initial Catalog = DiscoverThePlanet;User ID = TestUser;Password = Test"
An example :
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
https://www.connectionstrings.com/sql-server/
There are some ';' missing. Try this:
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
Use StringBuilder if you wants to write ConnectionString like mention,
String object it will occupy memory each time.
StringBuilder will occupy memory only once, so it will give you better performance.
SqlConnection conn = new SqlConnection();
StringBuilder sb=new StringBuilder();
sb.Append("Data Source = 123.456.789.012;");
sb.Append("Initial Catalog = DiscoverThePlanet;");
sb.Append("User ID = TestUser;");
sb.Append("Password = Test;");
conn.ConnectionString =sb.ToString();
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
Semi Column is missing in the Connection String. So correct it
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}

Selecting database dynamically in Entity Framework

I have multiple SQL databases with the same schema .Say(Database1,Database2....)
How do i dynamically select a database in Entity framework model in runtime?.Since they have the same schema, it does not make sense to import all the data models before hand.
You can change database connection string like this:
DataModelContainer context = new DataModelContainer(
ConnectionOperation.CreateEntityConnection());
And this is CreateEntityConnection Method:
internal static EntityConnection CreateEntityConnection()
{
// Start out by creating the SQL Server connection string
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source. The IP address network address
sqlBuilder.DataSource = System.Configuration.ConfigurationManager.AppSettings["Connection"];
// The name of the database on the server
sqlBuilder.UserID = "sa";
sqlBuilder.Password = "12345";
sqlBuilder.InitialCatalog = "DatabaseName";
sqlBuilder.IntegratedSecurity = true;
sqlBuilder.MultipleActiveResultSets = true;
// Now create the Entity Framework connection string
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl";
// Create and entity connection
EntityConnection conn = new EntityConnection(entityBuilder.ToString());
return conn;
}

Restoring SQL Server 2005 database using C#. Rollback issue

Hi I'm just starting to learn C#. I am trying to restore a .bak file. However I am getting the error. Exclusive access cannot be obtained because the database is in use.
I did my research here and here both says I have to perform a rollback. I do not know how to apply rollback in my restore code.
public void RestoreDatabase(String RestorePath)
{
try
{
SqlConnection sqlCon = new SqlConnection("Data Source=RITZEL-PC\\SQLEXPRESS;User ID=NNIT-Admin;Password=password;Initial Catalog=master;");
ServerConnection connection = new ServerConnection(sqlCon);
Server sqlServer = new Server(connection);
Restore restoreDB = new Restore();
restoreDB.Database = "NNIT DB";
restoreDB.Action = RestoreActionType.Database;
restoreDB.Devices.AddDevice(RestorePath, DeviceType.File);
restoreDB.ReplaceDatabase = true; // will overwrite any existing DB
restoreDB.NoRecovery = false; // NoRecovery = true;
restoreDB.SqlRestore(sqlServer);
MessageBox.Show("Restored");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " " + ex.InnerException);
}
}
Using SMO you can set user access and rollback like this:
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases["DbToRestore"];
if (db != null)
{
sqlServer.KillAllProcesses(db.Name);
db.DatabaseOptions.UserAccess = DatabaseUserAccess.Multiple;
db.Alter(TerminationClause.RollbackTransactionsImmediately);
}
Restore restoreDB = new Restore();
Does this work?
SqlCommand cmd = new SqlCommand("ALTER DATABASE yourdatabasename SET MULTI_USER WITH ROLLBACK IMMEDIATE", sqlConn);
cmd.ExecuteNonQuery();

how to restore using restore class of Microsoft.SqlServer.Management.Smo namespace

public void RestoreDatabase(String databaseName, String filePath,
String serverName, String userName, String password, String dataFilePath, String logFilePath)
{
Restore sqlRestore = new Restore();
BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = databaseName;
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlRestore.Action = RestoreActionType.Database;
String dataFileLocation = dataFilePath;
String logFileLocation = logFilePath;
db = sqlServer.Databases[databaseName];
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation));
sqlRestore.ReplaceDatabase = true;
sqlRestore.Complete +=new ServerMessageEventHandler(sqlRestore_Complete);
sqlRestore.SqlRestore(sqlServer);
db = sqlServer.Databases[databaseName];
db.SetOnline();
sqlServer.Refresh();
}
On calling this method the restore operation failed with this message
Restore failed for Server
'MDM04\SQLEXPRESS'.
mdm04 is my computer name
the inner exception is
"System.Data.SqlClient.SqlError:
Logical file 'vrv' is not part of
database 'vrv'. Use RESTORE
FILELISTONLY to list the logical file
names."
vrv is database name
What should I do to restore the file
Problem is here
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation));
here databaseName means, name of the database specified in db backup file. But you are specifying the destination db name.
Change it to original db name
here the sample code to read db names from backup file
DataTable dtFileList = sqlRestore.ReadFileList(serverName);
string dbLogicalName = dtFileList.Rows[0][0].ToString();
string dbPhysicalName = dtFileList.Rows[0][1].ToString();
string logLogicalName = dtFileList.Rows[1][0].ToString();
string logPhysicalName = dtFileList.Rows[1][1].ToString
Now Go to "Browse" Tab and browse the following path-
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies
OR
C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies
Now Select the following dlls
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SmoExtended.dll
Microsoft.SqlServer.SqlEnum.dll
public void RestoreDatabase(String databaseName, String filePath,
String serverName, String userName, String password,
String dataFilePath, String logFilePath)
{
Restore sqlRestore = new Restore();
BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = databaseName;
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlRestore.Action = RestoreActionType.Database;
String dataFileLocation = dataFilePath;
String logFileLocation = logFilePath;
db = sqlServer.Databases[databaseName];
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation));
sqlRestore.ReplaceDatabase = true;
sqlRestore.Complete +=new ServerMessageEventHandler(sqlRestore_Complete);
sqlRestore.SqlRestore(sqlServer);
db = sqlServer.Databases[databaseName];
db.SetOnline();
sqlServer.Refresh();
}

Categories