Referans olarak eklenecek dll’ler:

Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SmoExtended.dll

Referans ekleme penceresinde .NET tabında bu referanslar görünmüyor ise Browse tabından C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies lokasyonundan dll’leri referans olarak ekleyebilirsiniz.

Eklenecek namespaceler:

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

Backup:

public void BackupDatabase(String databaseName, String userName, String password, String serverName, String destinationPath)
{
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
Backup sqlBackup = new Backup();
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = “ArsivDataBase:” + DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = “Arsiv”;
sqlBackup.Database = databaseName;
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
}

Bu şekilde full backup alınır.Incremental backup almak için Incremental değerini true yapmalısınız.

Restore:

public void RestoreDatabase(String databaseName, String filePath, String serverName, String userName, String password, String dataFilePath)
{
String dataFileLocation = dataFilePath + databaseName + “.mdf”;
String logFileLocation = dataFilePath + databaseName + “_Log.ldf”;
BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
if (!sqlServer.Databases.Contains(databaseName))
{
sqlServer.Databases.Add(new Database(sqlServer, databaseName));
sqlServer.Refresh();
}

Restore sqlRestore = new Restore();
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = databaseName;
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + “_log”, logFileLocation));
sqlRestore.ReplaceDatabase = true;
sqlRestore.Action = RestoreActionType.Database;
sqlRestore.SqlRestore(sqlServer);
}

Backup ve Restore işlemlerinde, işlemi monitör etmek için PercentComplete ve Complete eventlerı kullanılabilir.

private static void CompletionStatusInPercent(object sender, PercentCompleteEventArgs args)
{
Console.Clear();
Console.WriteLine(“Percent completed: {0}%.”, args.Percent);
}
private static void Backup_Completed(object sender, ServerMessageEventArgs args)
{
Console.WriteLine(“Backup completed.” );
}

Reklamlar