SIGN UP MEMBER LOGIN:    
ARTICLE

BackUp Device in C# .Net

Posted by Kapil Soni Articles | Current Affairs April 21, 2009
The attached project is a utility that allows you to take a backup and restore to the previous state of a SQL Server database.
Reader Level:
Download Files:
 

Download the attached project for more details.

The code in this project looks like this.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//namespace import avaiable in Microsoft.SqlServer.ConnectionInfo and Microsoft.SqlServer.Smo
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace BackUp_Utility
{
    public partial class frmbackup : Form
    {
        //Object if server class
        public static Server srv;
        public frmbackup()
        {
            InitializeComponent();
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                //cmbsrv_name is name of combo box in which server name will be loaded
                if (cmbsrv_name.SelectedItem != null && cmbsrv_name.SelectedItem.ToString() != "")
                {

//ServerConnection Class to connect with sql server.
                    ServerConnection srvcon = new ServerConnection(cmbsrv_name.SelectedItem.ToString());
                    srvcon.LoginSecure = false;

//txtuserid is name of textbox to accept servr user name from user.
                    srvcon.Login = txtuserid.Text;

//txtpassword name of textbox to accept ppassword of server to be entered by user.
                    srvcon.Password = txtPassword.Text;
                    srv = new Server(srvcon);

//loop to load all database that are available in that particular server
                    foreach (Database db in srv.Databases)
                    {
                        //cmbdatabse in which all database realted to server willl be loaded
                        cmbDatabase.Items.Add(db.Name);
                    }
                }
                else
                {
                    MessageBox.Show("Please select a server first", "Server Not Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

//btnBackup is name of button to take backup

        private void btnBackup_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                if (srv != null)
                {
                    sfd.Title = "BackUp To...";
                    sfd.Filter = "Backup File|*.bak";
                    sfd.FileName = "Backup_" + DateTime.Now.ToLongDateString() + ".bak";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {

//Backup class allow programmatic access to sql server backup
                        Backup db_bk = new Backup();
                        db_bk.Action = BackupActionType.Database;
                        db_bk.Database = cmbDatabase.SelectedItem.ToString();

//BackupDeviceItem class allow to programmatic access to Named Sql server backup devices.
                        BackupDeviceItem bkitem = new BackupDeviceItem(sfd.FileName, DeviceType.File);
                        db_bk.Devices.Add(bkitem);
                        db_bk.SqlBackup(srv);
                    }
                }
                else
                {
                    MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

//btnrestore button to restore a database into last backup state

        private void btnrestore_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                if (srv != null)
                {
                    ofd.Title = "Restore BackUp...";
                    ofd.Filter = "Backup File|*.bak";
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {

//Restore class allow programatic access to sql server resoter operations.
                        Restore re_db = new Restore();

//RestoreActionType allow us to take which part restoration like database resote or files restore etc....
                        re_db.Action = RestoreActionType.Database;
                        re_db.Database = cmbDatabase.SelectedItem.ToString();

//BackupDeviceItem class aloow programatic acces to named sql server resotre operation
                        BackupDeviceItem bk_item = new BackupDeviceItem(ofd.FileName, DeviceType.File);
                        re_db.Devices.Add(bk_item);
                        re_db.ReplaceDatabase = true;
                        re_db.SqlRestore(srv);
                    }
                }
                else
                {
                    MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

//form load event

        private void Form1_Load(object sender, EventArgs e)
        {
            //SmoApplication is ava in Management.Smo namespace to list the server that is installed on machine
            DataTable dt = SmoApplication.EnumAvailableSqlServers(true);
            if (dt.Rows.Count > 0)
            {
                // Loop through each server in the DataTable
                foreach (DataRow dr in dt.Rows)
                {
                    cmbsrv_name.Items.Add(dr["Name"]);
                }
            }
        }
    }
}

 

Login to add your contents and source code to this article
Article Extensions
Contents added by Anusha Kolluri on May 28, 2009
share this article :
post comment
 

userid:sa
password:adminadmin

Posted by amal raj Oct 09, 2009

or if your server is configured to windows authentication then tell me or your server configured to accept user id and password
just tell me that and what error ocuring
then i will tell u ok
thnaks

Posted by Kapil Soni Aug 31, 2009

Hi
i receive your query and can u tell me your server name or give me some idea about error occured while backing up  database
thnks

Posted by Kapil Soni Aug 31, 2009

Error occured in this application, how can i solve it


{"Backup failed for Server '.\\SQLEXPRESS'. "}

Posted by Zeeshan Anwar Aug 31, 2009
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor