Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to take a backup of my database in asp.net application.
When i save it, it should replace with previous one.
How can i do this?
Posted
Updated 23-May-11 4:43am
v2

Class BackupDbTask.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;


    public class BackupDbTask
    {


        private string _sqlserverUser;
        public string SQLServerUser
        {
            get { return _sqlserverUser; }
            set { _sqlserverUser = value; }
        }
        private string _sqlserverPassword;
        public string SQLServerPassword
        {
            get { return _sqlserverPassword; }
            set { _sqlserverPassword = value; }
        }
        private string _sqlserverInstanceName;
        public string SqlServerInstanceName
        {
            get { return _sqlserverInstanceName; }
            set { _sqlserverInstanceName = value; }
        }
        private string _sqlserverDBName;
        public string SqlServerDBName
        {
            get { return _sqlserverDBName; }
            set { _sqlserverDBName = value; }
        }

        private string _databaseBackupFolder;

        public string DatabaseBackupFolder
        {
            get { return _databaseBackupFolder; }
            set { _databaseBackupFolder = value; }
        }

        private string _backupFile;

        public string BackupFile
        {
            get { return _backupFile; }
            set { _backupFile = value; }
        }
        #endregion Properties

        public void Execute()
        {

            // Backup Db
            try
            {
                ServerConnection conn = new ServerConnection();
                conn.LoginSecure = false;
                conn.DatabaseName = this.SqlServerDBName;
                conn.ServerInstance = this.SqlServerInstanceName;
                conn.Login = this.SQLServerUser;
                conn.Password = this.SQLServerPassword;
                Server svr = new Server(conn);
                Database BuildDB = svr.Databases[this.SqlServerDBName];

                string dbbackupfile = this.DatabaseBackupFolder + @"\" + this.SqlServerDBName + ".bak"; ;


                Backup backup = new Backup();
                backup.Database = this.SqlServerDBName;
                backup.MediaName = "FileSystem";
                BackupDeviceItem bkpDeviceItem = new BackupDeviceItem();
                bkpDeviceItem.DeviceType = DeviceType.File;
                bkpDeviceItem.Name = dbbackupfile;
                backup.Devices.Add(bkpDeviceItem);
                backup.Initialize = true;
                backup.SqlBackup(svr);

                this.BackupFile = dbbackupfile;
            }
            catch (Exception ex)
            {


            }


        }
    }
Class RestoreDBTask.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

    public class RestoreDBTask 
    {
        #region Properties
       
        private string _sqlserverUser;
        
        public string SQLServerUser
        {
            get { return _sqlserverUser; }
            set { _sqlserverUser = value; }
        }
        private string _sqlserverPassword;
        public string SQLServerPassword
        {
            get { return _sqlserverPassword; }
            set { _sqlserverPassword = value; }
        }
        private string _sqlserverInstanceName;
      
        public string SqlServerInstanceName
        {
            get { return _sqlserverInstanceName; }
            set { _sqlserverInstanceName = value; }
        }
        private string _sqlserverDBName;
      
        public string SqlServerDBName
        {
            get { return _sqlserverDBName; }
            set { _sqlserverDBName = value; }
        }
        
        private string _backupFileFolder;
        public string BackupFileFolder
        {
            get { return _backupFileFolder; }
            set { _backupFileFolder = value; }
        }
       
        
        private string _backupFile;
        public string BackupFile
        {
            get { return _backupFile; }
            set { _backupFile = value; }
        }
        #endregion Properties
        public bool Execute()
        {
           

            ServerConnection conn = new ServerConnection();
            conn.LoginSecure = false;
            conn.DatabaseName = "Master";
            conn.ServerInstance = this.SqlServerInstanceName;
            conn.Login = this.SQLServerUser;
            conn.Password = this.SQLServerPassword;
            Server svr = new Server(conn);
            Database db = svr.Databases["Master"];
            string dbbackupfile = string.Empty;
            if (this.BackupFile == string.Empty)
                dbbackupfile = this.BackupFileFolder + @"\" + this.SqlServerDBName + ".bak";
            else
                dbbackupfile = this.BackupFile; 
            try
            {
                // Restore Database
                Restore restore = new Restore();
                restore.Database = this.SqlServerDBName;
                restore.RestrictedUser = true; 
                restore.Action = RestoreActionType.Database;
                restore.ReplaceDatabase = true;
                restore.Devices.AddDevice(dbbackupfile, DeviceType.File);
                svr.KillAllProcesses(this.SqlServerDBName);
                restore.Wait();  
                restore.SqlRestore(svr);
            }
            catch (Exception ex)
            {
                "Database restore failed", ex.InnerException.Message)
            }
            
        }
    }
 
Share this answer
 
v2
Comments
OsoJames 24-Apr-13 16:30pm    
Can you please give me this code in VB?
Here is a simple codesnippet which displays a list of databases in a listbox.
The BackupNow() method backups the selected database in the disk. The backup path is specified in
the appsettings section in the web.config.
 GetConnection conn = new GetConnection();
 
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadHeader();
            PopulateDatabaseTables();             
            GetBackupList();
           
        }
    }
 private void PopulateDatabaseTables()
    {
        string tableName = string.Empty;
        string sql = "select distinct db_name(s_mf.database_id) AS database_name"+    
                        " from sys.master_files s_mf where s_mf.state = 0 ";
        using (SqlConnection DBConn = conn.GetDBCon())
        {
            using (DataTable databases = new DataTable())
            {
                using (SqlDataAdapter dAd = new SqlDataAdapter(sql, DBConn))
                {
                    dAd.Fill(databases);
                }
                ListBox1.DataSource = databases;
                ListBox1.DataTextField = "database_name";
                ListBox1.DataBind();
            }
        }
    }
	
	protected void BackUpNow(object sender, EventArgs e)
    {
        string tableName = this.ListBox1.SelectedItem.ToString();
        string date = DateTime.Now.ToShortDateString();
        date = date.Replace("/", "-");
        date = date.Replace(" ", ":");
		
        string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();        
           
        using ( SqlConnection DBConn = conn.GetDBCon())
        {
            string query = "backup database @tableName To Disk='" + path + "\\" + tableName + "[" + date + "]" + ".bak'";
            SqlCommand cmd = new SqlCommand(query, DBConn);
            cmd.Parameters.Add(new SqlParameter("@tableName", tableName));           
            cmd.ExecuteNonQuery();  
        }
        GetBackupList();
        lblMessage.Text = "Backup for  <b>Database</b> successful!";
    }
	
	public void GetBackupList()
    {
        string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();
        DirectoryInfo diFiles = new DirectoryInfo(path);        
        backupList.DataSource = diFiles.GetFiles("*.bak");       
        backupList.DataBind(); 
    }
 
Share this answer
 
Comments
OsoJames 24-Apr-13 16:30pm    
Can you please give me this code in VB?
Here is a simple codesnippet which displays a list of databases in a listbox.
The BackupNow() method backups the selected database in the disk. The backup path is specified in
the appsettings section in the web.config.

 GetConnection conn = new GetConnection();
 
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadHeader();
            PopulateDatabaseTables();             
            GetBackupList();
           
        }
    }
 private void PopulateDatabaseTables()
    {
        string tableName = string.Empty;
        string sql = "select distinct db_name(s_mf.database_id) AS database_name"+    
                        " from sys.master_files s_mf where s_mf.state = 0 ";
        using (SqlConnection DBConn = conn.GetDBCon())
        {
            using (DataTable databases = new DataTable())
            {
                using (SqlDataAdapter dAd = new SqlDataAdapter(sql, DBConn))
                {
                    dAd.Fill(databases);
                }
                ListBox1.DataSource = databases;
                ListBox1.DataTextField = "database_name";
                ListBox1.DataBind();
            }
        }
    }
	
	protected void BackUpNow(object sender, EventArgs e)
    {
        string tableName = this.ListBox1.SelectedItem.ToString();
        string date = DateTime.Now.ToShortDateString();
        date = date.Replace("/", "-");
        date = date.Replace(" ", ":");
		
        string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();        
           
        using ( SqlConnection DBConn = conn.GetDBCon())
        {
            string query = "backup database @tableName To Disk='" + path + "\\" + tableName + "[" + date + "]" + ".bak'";
            SqlCommand cmd = new SqlCommand(query, DBConn);
            cmd.Parameters.Add(new SqlParameter("@tableName", tableName));           
            cmd.ExecuteNonQuery();  
        }
        GetBackupList();
        lblMessage.Text = "Backup for  <b>Database</b> successful!";
    }
	
	public void GetBackupList()
    {
        string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();
        DirectoryInfo diFiles = new DirectoryInfo(path);        
        backupList.DataSource = diFiles.GetFiles("*.bak");       
        backupList.DataBind(); 
    }
 
Share this answer
 
Comments
OsoJames 24-Apr-13 16:30pm    
Can you please give me this code in VB?
Here is a simple codesnippet which displays a list of databases in a listbox.
The BackupNow() method backups the selected database in the disk. The backup path is specified in
the appsettings section in the web.config.

protected void BackUpNow(object sender, EventArgs e)
{
    string tableName = this.ListBox1.SelectedItem.ToString();
    string date = DateTime.Now.ToShortDateString();
    date = date.Replace("/", "-");
    date = date.Replace(" ", ":");

    string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();

    using ( SqlConnection DBConn = conn.GetDBCon())
    {
        string query = "backup database @tableName To Disk='" + path + "\\" + tableName + "[" + date + "]" + ".bak'";
        SqlCommand cmd = new SqlCommand(query, DBConn);
        cmd.Parameters.Add(new SqlParameter("@tableName", tableName));
        cmd.ExecuteNonQuery();
    }
    GetBackupList();
    lblMessage.Text = "Backup for  <b>Database</b> successful!";
}

public void GetBackupList()
{
    string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();
    DirectoryInfo diFiles = new DirectoryInfo(path);
    backupList.DataSource = diFiles.GetFiles("*.bak");
    backupList.DataBind();
}
 
Share this answer
 
Comments
OsoJames 24-Apr-13 16:30pm    
Can you please give me this code in VB?
Here is a simple codesnippet which displays a list of databases in a listbox.
The BackupNow() method backups the selected database in the disk. The backup path is specified in
the appsettings section in the web.config.

GetConnection conn = new GetConnection();


private void PopulateDatabaseTables()
   {
       string tableName = string.Empty;
       string sql = "select distinct db_name(s_mf.database_id) AS database_name"+
                       " from sys.master_files s_mf where s_mf.state = 0 ";
       using (SqlConnection DBConn = conn.GetDBCon())
       {
           using (DataTable databases = new DataTable())
           {
               using (SqlDataAdapter dAd = new SqlDataAdapter(sql, DBConn))
               {
                   dAd.Fill(databases);
               }
               ListBox1.DataSource = databases;
               ListBox1.DataTextField = "database_name";
               ListBox1.DataBind();
           }
       }
   }

   protected void BackUpNow(object sender, EventArgs e)
   {
       string tableName = this.ListBox1.SelectedItem.ToString();
       string date = DateTime.Now.ToShortDateString();
       date = date.Replace("/", "-");
       date = date.Replace(" ", ":");

       string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();

       using ( SqlConnection DBConn = conn.GetDBCon())
       {
           string query = "backup database @tableName To Disk='" + path + "\\" + tableName + "[" + date + "]" + ".bak'";
           SqlCommand cmd = new SqlCommand(query, DBConn);
           cmd.Parameters.Add(new SqlParameter("@tableName", tableName));
           cmd.ExecuteNonQuery();
       }
       GetBackupList();
       lblMessage.Text = "Backup for  <b>Database</b> successful!";
   }

   public void GetBackupList()
   {
       string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();
       DirectoryInfo diFiles = new DirectoryInfo(path);
       backupList.DataSource = diFiles.GetFiles("*.bak");
       backupList.DataBind();
   }
 
Share this answer
 
Comments
OsoJames 24-Apr-13 16:31pm    
Can you please give me this code in VB?
@ambarishtv Thanks for suggesting my blog post.
 
Share this answer
 
Database backup & Restore using T-SQL
Link[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900