Monday, April 13, 2009

Copy Database

public static void CopyDataBaseAsFile() {

//Set Source SQL Server Instance Information
Server server = null;
Microsoft.SqlServer.Management.Smo.Database ddatabase = null;
Microsoft.SqlServer.Management.Smo.Database sdatabase = null;

try {
server = new Server(DBHelper.SourceSQLServer);
server.ConnectionContext.LoginSecure = false;
server.ConnectionContext.Login = Login;
server.ConnectionContext.Password = Password;

ddatabase = new Microsoft.SqlServer.Management.Smo.Database(server, DBHelper.DestinationDatabase);
sdatabase = new Microsoft.SqlServer.Management.Smo.Database(server, DBHelper.sourceDatabase);
}
catch {
FileActions.WriteToLog(@"" + backupLogFileLocation, "Server connection failed.");
FileActions.WriteToLog(@"" + restoreLogFileLocation, "Server connection failed.");
}

try {
/*
* Backup the target database to a .bak file.
*/
Backup bUp = new Backup();
bUp.Database = DBHelper.SourceDatabase;
bUp.Devices.AddDevice(@"" + BackupFileLocation, DeviceType.File);
bUp.Initialize = true;
bUp.Action = BackupActionType.Database;
bUp.PercentComplete += new PercentCompleteEventHandler(bUp_PercentComplete);
bUp.PercentCompleteNotification = 5;
bUp.SqlBackup(server);
}
catch (Exception ex) {

FileActions.WriteToLog(@"" + backupLogFileLocation, ex.ToString());
return;
}

try {
/*
* Restore the new db from the created db backup.
*/
bool verified = false;
string errorMsg = "";
Restore res = new Restore();
res.Database = DBHelper.DestinationDatabase;
res.Action = RestoreActionType.Database;
res.Devices.AddDevice(@"" + BackupFileLocation, DeviceType.File);
// res.Devices.AddDevice(@"C:\temp\copybakup.bak", DeviceType.File);

verified = res.SqlVerify(server, out errorMsg);

//ddatabase.SetOffline();


if (verified) {
res.PercentCompleteNotification = 5;
res.ReplaceDatabase = true;
res.NoRecovery = false;

res.RelocateFiles.Add(new RelocateFile(DBHelper.SourceDatabase, @"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\" + DBHelper.DestinationDatabase + ".mdf"));
res.RelocateFiles.Add(new RelocateFile(DBHelper.SourceDatabase + "_Log", @"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\" + DBHelper.DestinationDatabase + ".ldf"));

res.PercentComplete += new PercentCompleteEventHandler(res_PercentComplete);
res.SqlRestore(server);
}
else {
FileActions.WriteToLog(@"" + RestoreLogFileLocation, "Backup set could not be verified.");
}

//ddatabase.SetOnline();
}
catch (Exception ex) {
FileActions.WriteToLog(@"" + RestoreLogFileLocation, ex.ToString());
//ddatabase.SetOnline;
return;
}
}

No comments:

Post a Comment