Take Backup At your own Time

hi i am giving a very nice code to take backup at your own setting time.
1.Drag a Timer Control
2.make it Enabled is true.


VB.NET Code
Imports Microsoft.SqlServer.Server
Imports Microsoft.SqlServer.Management.Smo
Imports System.IO
Public Class TestForm
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim BackUpTime As Date = DateTime.Now
If BackUpTime.ToLongTimeString = "8:09:18 PM" Then
TakeBackUp("DMS", "D:\Mail\TestForU.bak") 'DMS is the correct database name exist in server
End If
End Sub
Private Sub TakeBackUp(ByVal BackupDBName As String, ByVal FileNamePath As String)
Try
Dim sqlServerInstance As New Server(New Microsoft.SqlServer.Management.Common.ServerConnection _
(New System.Data.SqlClient.SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=;Data Source=SANTOSH\SQLEXPRESS"))) 'This is only for connection if u give Initial Catalog null it will work
Dim objBackup As New Backup
objBackup.Devices.AddDevice(FileNamePath, DeviceType.File)
objBackup.Database = BackupDBName
objBackup.Action = BackupActionType.Database
objBackup.SqlBackup(sqlServerInstance)
MessageBox.Show("The backup of database " & "'" & BackupDBName & "'" & " completed sccessfully", "Microsoft SQL Server Management Studio", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

C#.NET Code
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Management.Smo;
using System.IO;
public class TestForm
{
//TODO: INSTANT C# TODO TASK: Insert the following converted event handler wireups at the end of the 'InitializeComponent' method for forms, 'Page_Init' for web pages, or into a constructor for other classes:
Timer1.Tick += Timer1_Tick;

private void Timer1_Tick(object sender, System.EventArgs e)
{
System.DateTime BackUpTime = DateTime.Now;
if (BackUpTime.ToLongTimeString() == "8:09:18 PM")
{
TakeBackUp("DMS", "D:\\Mail\\TestForU.bak"); //DMS is the correct database name exist in server
}
}
private void TakeBackUp(string BackupDBName, string FileNamePath)
{
try
{
Server sqlServerInstance = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection (new System.Data.SqlClient.SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=;Data Source=SANTOSH\\SQLEXPRESS"))); //This is only for connection if u give Initial Catalog null it will work
Backup objBackup = new Backup();
objBackup.Devices.AddDevice(FileNamePath, DeviceType.File);
objBackup.Database = BackupDBName;
objBackup.Action = BackupActionType.Database;
objBackup.SqlBackup(sqlServerInstance);
MessageBox.Show("The backup of database " + "'" + BackupDBName + "'" + " completed sccessfully", "Microsoft SQL Server Management Studio", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

OUTPUT:-

Regards
Santosh

1 comment: