Geekpedia Programming Tutorials






Backup and restore SQL databases

Programming tutorial that shows you how to backup a SQL database to a BAK file and then restore it from the same file using C#. First we list all running SQL Server 2005 instances, then we connect to one of them and retrieve all the databases from that server, finally we create the backup and restore operations; everything is done using SQL Management Objects (SMO).

On Friday, April 21st 2006 at 06:47 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.8 with 42 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

SQL Server 2005 Backup

The application we're going to create here will only work with SQL Server 2005, since we'll be using SQL Management Objects (SMO) which were introduced in this new version of SQL: 2005. If you would like to create a backup application like the one we are creating here, but you want to make it work with both SQL Server 2005 and older versions of SQL Server - such as 2000 - you should use SQL-DMO instead of SMO. However, for your application to work in SQL Server 2005, when setting up the server you will need to install the Legacy Components, as shown in the screenshot below:

SQL-DMO

Since in this tutorial we'll be using SQL SMO only, there's no need to install anything extra aside from the typical SQL Server 2005 setup.

Let's start building the C# application in Visual Studio 2005.
Start by creating a new Windows Form application, and design a form such as the one below:

SQL Backup

If we ignore the labels on the form, which are not crucial for the application, in the first groupbox we have 4 controls: cmbServer, txtUsername, txtPassword and btnConnect. In the second groupbox we have 3 controls: cmbDatabase, btnCreate and btnRestore. It should be easy for you to figure which one's which, but there's also the Visual Studio project attached to this tutorial if you need help.
There's two more things we need to add: an OpenFileDialog and a SaveFileDialog entitled openBackupDialog and saveBackupDialog.

Open / Save dialog

These two will be used for opening the backup file and restoring it, and for saving the backup file to a location on the hard drive.

Adding Microsoft.SqlServer references to our project

Right click your project and choose "Add Reference". In the .NET tab you should see multiple Microsoft.SqlServer objects. We are interested in only two of them, Microsoft.SqlServer.ConnectionInfo and Microsoft.SqlServer.Smo, as shown in the screenshot below. If you don't see these objects in the list, you probably don't have SQL Server 2005 installed on the system where you are developing this application.

Add SQL Reference

Now that you added the two references to the project we are ready to code.
Switch to code view, and let's start by adding the using statement for the SQL namespaces we're going to use. Add the following two lines after the already existent using statements.


using Microsoft.SqlServer.Management.Smo;

using Microsoft.SqlServer.Management.Common;


Most of the objects we're going to use in this tutorial will have a local scope, they will only be used in a specific method or event, so we'll create them on spot. But one of these objects needs to be declared directly inside the class, and this is the Server object, part of Microsoft.SqlServer.Management.Smo. The reason is that we're going to verify this object to see if a connection to a server has been made, in several events.

Before writing the code that executes the backup, the first thing we need to do is to connect to the database; the controls in the first group box will be used for doing that. But even before we add functionality to the "Connect" button, there's one other thing we need to do: populate the "Server" combobox with the servers available on the user's machine.

Getting a list of available SQL Servers

As I said, the very first thing we need to do is to populate the combobox cmbServer with the available SQL servers when the application (and thus the form) is loading. Therefore, doubleclick the titlebar of the form in Visual Studio's Form Designer and you will get to the Load event of the form (Form1_Load). Inside this event, use the following code:


// Create a DataTable where we enumerate the available servers

DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);

// If there are any servers at all

if (dtServers.Rows.Count > 0)

{

   // Loop through each server in the DataTable

   foreach (DataRow drServer in dtServers.Rows)

   {

      // Add the name to the combobox

      cmbServer.Items.Add(drServer["Name"]);

   }

}


In the code above we are using EnumAvailableSqlServers() to get a list of servers that we then loop through. The true parameter that we are passing to EnumAvailableSqlServers() tells it to list only the local SQL Server instances, and not the ones on the network. Why would we want to do that? Because as far as I know, there is no way to remotely backup the SQL Server and save the file to the remote computer. You can backup remotely, but the file must be saved on the same computer as where the server is running. Of course, if you want to develop this type of functionality, you can always write the code to save the file on the server and then download it to the remote computer.

You can now compile and run the SQL Backup application, and after it loads you should see a list of servers in the cmbServer combobox. If you have one instance of SQL Server 2005 installed typically, you should see one server that has the same name as your computer.

Connecting to SQL Server

Now that we got the server list, let's take care of connecting to one of the servers in that list. And that will happen when the "Connect" (btnConnect) button is clicked. Along with connecting, we're also going to retrieve a list of databases from that server.
Thus, inside the Visual Studio form designer, double click the btnConnect button and the Click event will be automatically created. Inside it, use the following code:


// If a server was selected at all from the combobox

if (cmbServer.SelectedItem != null && cmbServer.SelectedItem.ToString() != "")

{

   // Create a new connection to the selected server name

   ServerConnection srvConn = new ServerConnection(cmbServer.SelectedItem.ToString());

   // Log in using SQL authentication instead of Windows authentication

   srvConn.LoginSecure = false;

   // Give the login username

   srvConn.Login = txtUsername.Text;

   // Give the login password

   srvConn.Password = txtPassword.Text;

   // Create a new SQL Server object using the connection we created

   srvSql = new Server(srvConn);

   // Loop through the databases list

   foreach (Database dbServer in srvSql.Databases)

   {

      // Add database to combobox

      cmbDatabase.Items.Add(dbServer.Name);

   }

}

else

{

   // A server was not selected, show an error message

   MessageBox.Show("Please select a server first", "Server Not Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}


In the code above, before taking any serious action we check to see if a server was selected from the combobox. If a selection was made, we create a ServerConnection object to connect to the selected server. We don't use Windows Authentication for the server, thus we set LoginSecure to false. This requires that we log in to the SQL server using an username and a password. If the Windows account that we were running this application from had SQL Server credentials, and the server accepted Windows Authentication, we could set LoginSecure to true and there wouldn't be a need to provide a login and a password. However, using SQL Authentication instead of Windows Authentication normally increases the chances of a successful connection.
After we successfully connect, we assign the Server object and loop through each database so that we can add it to the combobox.

At this point, if you compile the application and connect to the SQL server with the appropriate credentials, you should see a list of databases in the combobox. Now all that's left to do is to backup and restore the selected database.

How to backup a SQL database

What you should do at this step is to double click the Create Backup button in the form designer, and you will get to the Click event of btnCreate where you need to use the following code:


// If there was a SQL connection created

if (srvSql != null)

{

   // If the user has chosen a path where to save the backup file

   if (saveBackupDialog.ShowDialog() == DialogResult.OK)

   {

      // Create a new backup operation

      Backup bkpDatabase = new Backup();

      // Set the backup type to a database backup

      bkpDatabase.Action = BackupActionType.Database;

      // Set the database that we want to perform a backup on

      bkpDatabase.Database = cmbDatabase.SelectedItem.ToString();

 

      // Set the backup device to a file

      BackupDeviceItem bkpDevice = new BackupDeviceItem(saveBackupDialog.FileName, DeviceType.File);

      // Add the backup device to the backup

      bkpDatabase.Devices.Add(bkpDevice);

      // Perform the backup

      bkpDatabase.SqlBackup(srvSql);

   }

}

else

{

   // There was no connection established; probably the Connect button was not clicked

   MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}


First we check to see if a connection was made, then we prompt the user to choose a path where he wants to save the backup file (BAK extension). The backup object is then created and a few properties are set to define a few required values. As you probably well know, a backup can be made to an external device such as tapes, or ZIP drives, but here we choose to save the backup to a file.

Right now, you should be able to compile this project and perform a backup on one of your databases. The backup file that is now created, is ready to be restored.

How to restore a SQL database from a backup

Restoring a database from a previously created BAK file is similar to creating a backup, instead that of a Backup object we use a Restore object. Double click the Restore button (btnRestore) to get the Click event created, and inside it use the following code:


// If there was a SQL connection created

if (srvSql != null)

{

   // If the user has chosen the file from which he wants the database to be restored

   if (openBackupDialog.ShowDialog() == DialogResult.OK)

   {

      // Create a new database restore operation

      Restore rstDatabase = new Restore();

      // Set the restore type to a database restore

      rstDatabase.Action = RestoreActionType.Database;

      // Set the database that we want to perform the restore on

      rstDatabase.Database = cmbDatabase.SelectedItem.ToString();

 

      // Set the backup device from which we want to restore, to a file

      BackupDeviceItem bkpDevice = new BackupDeviceItem(openBackupDialog.FileName, DeviceType.File);

      // Add the backup device to the restore type

      rstDatabase.Devices.Add(bkpDevice);

      // If the database already exists, replace it

      rstDatabase.ReplaceDatabase = true;

      // Perform the restore

      rstDatabase.SqlRestore(srvSql);

   }

}

else

{

   // There was no connection established; probably the Connect button was not clicked

   MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}


In the code above we are restoring the database from a backup device that we specify - which is a file, of course - and the name of the database that we want to restore to is also specified. Currently it is being restored to the database selected in the combobox, however that is not necessary because as implied by the ReplaceDatabase property, a database doesn't have to exist for the restore operation to work. This means that in the real-life application you'll be building, you will allow the user to specify the name of the database to restore to, and if it doesn't exist, it will be automatically created.
Moreover, before developing a real-life application you should know that the Microsoft.SqlServer namespace offers numerous classes, methods and properties that you can use to improve the code that we wrote here. This code was limited to just showing you, the reader, how to list all SQL Server 2005 instances, connect to one of them using SQL Authentication, retrieve a list of databases and perform backup / restore operations on these databases. However, there are many ways to improve your application; one of the first things you'll want to do is to implement a strong error prevention and handling system, since the current code only barely deals with errors.
It should be easy for you to extend the current code so that you can add new features to your application, such as a progress bar that shows how much of the backup or restoration was performed. Thanks to the Microsoft.SqlServer namespace, these features are very easy to develop, and perhaps a future tutorial will follow, where we will build a more advanced SQL Server backup application.

Below is the entire code of Form1.cs for our application, in case you want to have an overall look:


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using Microsoft.SqlServer.Management.Smo;

using Microsoft.SqlServer.Management.Common;

 

namespace SqlBackUp

{

    public partial class Form1 : Form

    {

        private static Server srvSql;

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            // Create a DataTable where we enumerate the available servers

            DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);

            // If there are any servers at all

            if (dtServers.Rows.Count > 0)

            {

                // Loop through each server in the DataTable

                foreach (DataRow drServer in dtServers.Rows)

                {

                    // Add the name to the combobox

                    cmbServer.Items.Add(drServer["Name"]);

                }

            }

        }

 

        private void btnConnect_Click(object sender, EventArgs e)

        {

            // If a server was selected at all from the combobox

            if (cmbServer.SelectedItem != null && cmbServer.SelectedItem.ToString() != "")

            {

                // Create a new connection to the selected server name

                ServerConnection srvConn = new ServerConnection(cmbServer.SelectedItem.ToString());

                // Log in using SQL authentication instead of Windows authentication

                srvConn.LoginSecure = false;

                // Give the login username

                srvConn.Login = txtUsername.Text;

                // Give the login password

                srvConn.Password = txtPassword.Text;

                // Create a new SQL Server object using the connection we created

                srvSql = new Server(srvConn);

                // Loop through the databases list

                foreach (Database dbServer in srvSql.Databases)

                {

                    // Add database to combobox

                    cmbDatabase.Items.Add(dbServer.Name);

                }

            }

            else

            {

                // A server was not selected, show an error message

                MessageBox.Show("Please select a server first", "Server Not Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }

        }

 

        private void btnCreate_Click(object sender, EventArgs e)

        {

            // If there was a SQL connection created

            if (srvSql != null)

            {

                // If the user has chosen a path where to save the backup file

                if (saveBackupDialog.ShowDialog() == DialogResult.OK)

                {

                    // Create a new backup operation

                    Backup bkpDatabase = new Backup();

                    // Set the backup type to a database backup

                    bkpDatabase.Action = BackupActionType.Database;

                    // Set the database that we want to perform a backup on

                    bkpDatabase.Database = cmbDatabase.SelectedItem.ToString();

 

                    // Set the backup device to a file

                    BackupDeviceItem bkpDevice = new BackupDeviceItem(saveBackupDialog.FileName, DeviceType.File);

                    // Add the backup device to the backup

                    bkpDatabase.Devices.Add(bkpDevice);

                    // Perform the backup

                    bkpDatabase.SqlBackup(srvSql);

                }

            }

            else

            {

                // There was no connection established; probably the Connect button was not clicked

                MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }

        }

 

        private void btnRestore_Click(object sender, EventArgs e)

        {

            // If there was a SQL connection created

            if (srvSql != null)

            {

                // If the user has chosen the file from which he wants the database to be restored

                if (openBackupDialog.ShowDialog() == DialogResult.OK)

                {

                    // Create a new database restore operation

                    Restore rstDatabase = new Restore();

                    // Set the restore type to a database restore

                    rstDatabase.Action = RestoreActionType.Database;

                    // Set the database that we want to perform the restore on

                    rstDatabase.Database = cmbDatabase.SelectedItem.ToString();

 

                    // Set the backup device from which we want to restore, to a file

                    BackupDeviceItem bkpDevice = new BackupDeviceItem(openBackupDialog.FileName, DeviceType.File);

                    // Add the backup device to the restore type

                    rstDatabase.Devices.Add(bkpDevice);

                    // If the database already exists, replace it

                    rstDatabase.ReplaceDatabase = true;

                    // Perform the restore

                    rstDatabase.SqlRestore(srvSql);

                }

            }

            else

            {

                // There was no connection established; probably the Connect button was not clicked

                MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }

        }

    }

}

Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Nick Gilbert on Friday, May 5th 2006 at 05:24 AM

Is there a way to obtain the backup image as a stream or binary object as opposed to telling SQL Server to write the backup directly to a file? I wish to compress the backup as it is being generated before it ever gets written to disk.

Thanks!

by PrabhaRaman on Friday, August 25th 2006 at 07:21 AM

very nice one.

by Radhika on Thursday, September 7th 2006 at 03:56 AM

Is there a way to restore based on a condition. i.e., if the records are already existing then a msgbox should popup saying "the record exists. Do You wish to overwrite". If yes then only those records should be restored else the old records should be maintained and only new records should be added.

by Sharad Sharma on Monday, September 18th 2006 at 07:24 AM

Hi Andrei,

Can i use this code for my environment (given as under)...

- I have 3 machines (M1, M2, M3) all are in one domain.

- M1 is the administration machine, where we have to run console application. This machine has VS.NET 2005 installed.

- M1 is the hosting machine where Sql server 2000 is installed, in which a number of databases are created by the clients.

- M2 is also a hosting machine where Sql server 2005 is installed.

My requirement is ...

- To create a console application in M1 which would be able to....
copy database from M2 into M3


Regards
Sharad Sharma (KAPS)

by Bhadra on Monday, October 9th 2006 at 04:58 PM

the article was of gr8 help for me. Thank you very much. I really appreciate your effort

by Chetan Ramanuj on Friday, February 23rd 2007 at 02:11 AM

Hi,

this will be usefull with SQL Server using C#.Net

by chintal on Wednesday, March 7th 2007 at 11:42 PM

Thanks for this article

by Bayani Carbone on Thursday, April 12th 2007 at 09:08 AM

Hi, unfortunately this doesn\'t work for me, I tried adapting the solution to my existing code and also your complete solution and in both case I get an error: Backup failed for server...

here is the error log for Sql server 2005:

spid52 Error: 18204, Severity: 16, State: 1.
spid52 BackupDiskFile::CreateMedia: Backup device \'C:\\...\\Desktop\\test.bk\' failed to create. Operating system error 5(Access is denied.).

Backup Error: 3041, Severity: 16, State: 1.
Backup BACKUP failed to complete the command BACKUP DATABASE DentInvoice. Check the backup application log for detailed messages.


can anyone help?

Thx

by Andrei Pociu on Thursday, April 12th 2007 at 10:11 AM

Are you running the application as an Administrator?

by Bayani Carbone on Thursday, April 12th 2007 at 03:34 PM

Ok, it works but I can only save the backup file in the default backup folder of SQL Server Express 2005:

C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup

otherwise I get the aforementioned errors.

by Darko on Tuesday, May 1st 2007 at 12:32 PM

Good job, simple, fast and effective example... But I am having the same problem as Bayani, restore function works only if I save the backup to SQLServer folder? Why is this so and how can it be avoided? Thanks

by sarath on Wednesday, May 23rd 2007 at 08:42 AM

Cool and excelent job, Is there any chance to add more option in this application, like create table, to write stored procedure, alater table from here, if we doing so ,one can control the sql server from this application while developing other application, After that it will be use as a thirty party tool while developing .net application

by Jai on Monday, July 23rd 2007 at 06:57 AM

Hello,
The code is throwing exception when i tried to take backup . Actually i have modified your code a bit and instead of taking backup of available servers to the localhost , i am trying to take backup of remote system by entering the ip address and in a textbox with authentication (i.e with username and pwd, and am loggedon as administrator ) .
I am able to connect to the remote server and can easily bind the dropdownlist containing all the database available on that server.
But when i tried to take the backup , it throws this exception:

Backup failed for Server 'w.x.y.z'

"System.Data.SqlClient.SqlError: Could not locate entry in sysdatabases for database '[Northwind]'. No entry found with that name. Make sure that the name is entered correctly."

Its throwing error on this line

bkpDatabase.SqlBackup(srvSql);

Please help me . Its urgent.

by T on Thursday, August 23rd 2007 at 05:50 PM

I have this exact same problem:
"Ok, it works but I can only save the backup file in the default backup folder of SQL Server Express 2005:

C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLBackup

otherwise I get the aforementioned errors. "
any help would be greatly appreciated! thanx

by hussam on Tuesday, September 18th 2007 at 07:53 PM

well
hello ,thank you but i have got problem with my project
how can i use the restore database in my project ,in other word
i want make this database defualt to use (table & storedprocedure ....) and user can control with it\'s

by xyz on Wednesday, September 19th 2007 at 04:43 AM

is there a way to take a backup of sql as script

by Louise Goward on Friday, November 16th 2007 at 07:05 AM

For those interested, I finally resolved the problem of saving to a non-default location giving the Error: 18204, Severity: 16, State: 1.
In my case I use Symantec Backup Exec which insists on backing up the SQL database to c:\program files\symantec\backup exec\data rather than the default. If you check the security on your default MSSQL installation folders you will find the SQL Server service account granted full control (in my case it was SQLSERVER2005MSSQLUser). Just add this account to the security permissions for the new folder you want to use for backups and it will work.

by nep lah on Monday, November 26th 2007 at 08:59 PM

Hi,

Is there anyway to take backup and restore the sql database (MySQL 5 database engine) from C# application(visual studio 2002 IDE)?


Thanks in advance

by Bui Dung on Friday, November 30th 2007 at 04:42 AM

Thank.

by poonam on Monday, December 31st 2007 at 05:51 AM

i m getting an error in btnCreate_Click at
bkpDatabase.SqlBackup(srvSql);

ERROR: Backup failed for Server \'MR8\\SQLEXPRESS\'.

Why is so?
reply

by gipda on Wednesday, January 2nd 2008 at 04:45 AM

Fine tool, but it´s not possible to restore a database that´s not allready in system. I´m writing a program thats need a database on install if its not there it needs to create it from a default backup file

by habeebur on Thursday, January 24th 2008 at 08:40 AM

help me plzzzz.....
while restoring, it show error.....

I'm using sql server 2000

rstDatabase.SqlRestore(srvSql);

by Ron on Thursday, February 14th 2008 at 07:24 AM

How can I cancel a backup/restore in progress

by DrASAG on Tuesday, May 6th 2008 at 09:48 PM

hi.. i convert this code to vb.net, and it's work. no errors at all. unfortunately, the database does not restore, even it not produce an error.. why this happens?

by Moahmmed on Friday, June 6th 2008 at 06:29 PM

Hi How i can deploy this application using MS Visual Studio Setup Project

by Arvit on Monday, July 14th 2008 at 11:15 PM

Excellent article mate

by andrew on Thursday, September 4th 2008 at 11:57 PM

there is an error message in my c# that says:

"Restore failed for Server 'ANDREW'."

code is highlighted:
rstDatabase.SqlRestore(srvSql);



ANDREW is the name of my server.

by Morne on Friday, November 14th 2008 at 01:28 AM

Hi

Does the above application only work for SQL Server 2005 or will it also work with SQL Server 2005 Express? I have SQL Server 2005 Express installed on my PC and it doesnt seem to pick up my Server on my machine.

Ive checked that "DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);" is correct in my code.

Plz let me know.
Thanx

by Mital on Monday, January 5th 2009 at 05:51 AM

only one word "AWESOME" :-)
thanks a lot

by MD Zakir Karim Khan Bhadeya Gaya on Tuesday, January 6th 2009 at 07:23 AM

Is there any way to backup database using asp.net(c#) and database is on another server and my asp.net web files are on another server.

by kennedy chongwo on Tuesday, February 10th 2009 at 02:06 AM

cool tutorial but, how come backup is only possible to C:Program Files\Microsoft SQL Server\MSSQL.1MSSQL\Backup directory

help..

by Sujit on Monday, February 16th 2009 at 04:40 AM

this is helpul

by jan on Sunday, February 22nd 2009 at 11:33 PM

how i can add this code in mysql server.

by jan on Monday, February 23rd 2009 at 12:12 AM

how i can use this code in mysql server.

by JimBob on Thursday, March 26th 2009 at 04:31 PM

Try using the following code. Note that it does not use windows authentication, if you want to do so make it try{ Server server = new Server(servername); ....

private string BackupDatabase(string userName, string password, string serverName, string databaseName, string backupFileLocation)
{
try
{
ServerConnection conn = new ServerConnection(serverName, userName, password);

Server server = new Server(conn);
server.ConnectionContext.Connect();


Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = databaseName;
backup.Initialize = true;
backup.Incremental = false;

BackupDeviceItem backupDeviceItem = new BackupDeviceItem(backupFileLocation, DeviceType.File);
backup.Devices.Add(backupDeviceItem);

//BACKUP
backup.SqlBackup(server);
backup.Devices.Remove(backupDeviceItem);

return string.Empty;
}
catch(Exception exception)
{
return exception.Message;
}
}

by deep on Thursday, May 7th 2009 at 05:55 AM

when am trying to restore it shows the following error

Restore failed for Server 'Localhost'.

how to solve tis

by deep on Thursday, May 7th 2009 at 05:56 AM

when am trying to restore it shows the following error

Restore failed for Server 'Localhost'.

how to solve tis

by test on Wednesday, May 13th 2009 at 02:53 AM

Use SqlRestoreAsync instead of SqlRestore

// Perform the restore
rstDatabase.SqlRestoreAsync(srvSql);


this error might be because of your db is used someware..

by test on Wednesday, May 13th 2009 at 02:53 AM

Use SqlRestoreAsync instead of SqlRestore

// Perform the restore
rstDatabase.SqlRestoreAsync(srvSql);


this error might be because of your db is used some ware..

by Shameej T on Wednesday, May 27th 2009 at 12:34 AM

Hi

While i run the application that i download from this page , it doesn't shows any server..
I would like to work it on both local machine and server
checked that "DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);" is

correct in my code.

Plz let me know.
Thanx

by Shameej T on Wednesday, May 27th 2009 at 12:34 AM

Hi

While i run the application that i download from this page , it doesn't shows any server..
I would like to work it on both local machine and server
checked that "DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);" is

correct in my code.

Plz let me know.
Thanx

by Newbie on Saturday, May 30th 2009 at 01:12 AM

My application run from client(there are many client connect to DB server in same time).

when i am trying to restore it shows the following error

Restore failed for Server 'DBSVR'.

I Used SqlRestoreAsync instead of SqlRestore

// Perform the restore
rstDatabase.SqlRestoreAsync(srvSql);

No errer, but DB don't restore.
Plz help me? thanks very much.

by Newbie on Saturday, May 30th 2009 at 01:13 AM

My application run from client(there are many client connect to DB server in same time).

when i am trying to restore it shows the following error

Restore failed for Server 'DBSVR'.

I Used SqlRestoreAsync instead of SqlRestore

// Perform the restore
rstDatabase.SqlRestoreAsync(srvSql);

No errer, but DB don't restore.
Plz help me? thanks very much.

by djsme026 on Monday, June 8th 2009 at 03:49 AM

lam sao de~ tao dc nick Backup zay? That lam nhuc dau`

by djsme026 on Monday, June 8th 2009 at 03:49 AM

lam sao de~ tao dc nick Backup zay? That lam nhuc dau`

by djsme026 on Monday, June 8th 2009 at 03:49 AM

lam sao de~ tao dc nick Backup zay? That lam nhuc dau`

by djsme026 on Monday, June 8th 2009 at 03:49 AM

lam sao de~ tao dc nick Backup zay? That lam nhuc dau`

by djsme026 on Monday, June 8th 2009 at 03:49 AM

lam sao de~ tao dc nick Backup zay? That lam nhuc dau`

by manas rana on Saturday, July 18th 2009 at 01:22 AM

private void btnCreate_Click(object sender, EventArgs e)
{
//if there was a SQL connection created
if (srvSql != null)
{
// If the user has chosen a path where to save the backup file
if (saveBackupDialog.ShowDialog() == DialogResult.OK)
{
// Create a new backup operation
Backup bkpDatabase = new Backup();
// Set the backup type to a database backup
bkpDatabase.Action = BackupActionType.Database;
// Set the database that we want to perform a backup on
bkpDatabase.Database = cmbDatabase.SelectedItem.ToString();

// Set the backup device to a file
BackupDeviceItem bkpDevice = new BackupDeviceItem(saveBackupDialog.FileName, DeviceType.File);


bkpDatabase.Initialize = true;
bkpDatabase.Checksum = true;
bkpDatabase.ContinueAfterError = true;
// Add the backup device to the backup
bkpDatabase.Devices.Add(bkpDevice);

bkpDatabase.Incremental = false;

bkpDatabase.ExpirationDate = DateTime.Now.AddDays(3);
bkpDatabase.LogTruncation = BackupTruncateLogType.Truncate;

bkpDatabase.FormatMedia = false;
// Perform the backup
try
{
bkpDatabase.SqlBackup(srvSql);
}
catch (Exception ex)
{
string s = ex.Message;
}

}
}
else
{
// There was no connection established; probably the Connect button was not clicked
MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

}


it's work properly for create the backup.This is the modified code.

by sunitha on Monday, September 7th 2009 at 03:47 AM

hi

can't Restore Sql Database in sqlServer2000,i tried but it display

Restore failed for Server 'Localhost'.

by mans on Monday, September 7th 2009 at 04:15 AM

Hi Sunita

this above code will work ,when u will try to restore the db then from backup db name and restore db name should same.otherwise it will show error.
try it!!

manas

by manas on Monday, September 7th 2009 at 04:15 AM

Hi Sunita

this above code will work ,when u will try to restore the db then from backup db name and restore db name should same.otherwise it will show error.
try it!!

manas

by Sunitha on Sunday, September 13th 2009 at 11:50 PM

hi

i tried the same db name ,but it shows the error.

SqlServerConnection not Initialized .


Thanks in advance.

by SAINTJAB on Tuesday, September 15th 2009 at 07:35 AM

Hi guys,am getting this error code: Backup failed for server "". Please help.

by SAINTJAB on Tuesday, September 15th 2009 at 07:35 AM

Hi guys,am getting this error code: Backup failed for server "". Please help.

by SAINTJAB on Tuesday, September 15th 2009 at 07:35 AM

Hi guys,am getting this error code: Backup failed for server "". Please help.

by SAINTJAB on Tuesday, September 15th 2009 at 07:35 AM

Hi guys,am getting this error code: Backup failed for server "". Please help.

by SAINTJAB on Tuesday, September 15th 2009 at 07:35 AM

Hi guys,am getting this error code: Backup failed for server "". Please help.

by SAINTJAB on Tuesday, September 15th 2009 at 07:35 AM

Hi guys,am getting this error code: Backup failed for server "". Please help.

by news on Friday, October 9th 2009 at 04:23 AM

ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

by ppwclev on Tuesday, November 17th 2009 at 10:55 PM

Great example. I am researching possible solution to problems reported. I always have problems when restoring databases after drive letter or disk space changes on hosting server. Using T-SQL Restore filelistonly will allow list of original database and log file location. This can be confirmed as a valid location or changed as necessary during restore. Will also see if management.smo supports filelistonly or headeronly option.
EnumAvailableSqlServers(); listing can time-out on large networks so limit to local search EnumAvailableSqlServers(true); is better option if the list is empty.

by Banai singh Gurjar on Thursday, November 26th 2009 at 07:47 AM

in this way backup is easly create but when i restore my bd it genrate excpen restore failed to server/xyz plz. help me urgently
sincerly,
Banai singh

by Banai singh Gurjar on Thursday, November 26th 2009 at 07:48 AM

in this way backup is easly create but when i restore my bd it genrate excpen restore failed to server/xyz plz. help me urgently
sincerly,
Banai singh

by Banai singh Gurjar on Thursday, November 26th 2009 at 07:48 AM

in this way backup is easly create but when i restore my bd it genrate excpen restore failed to server/xyz plz. help me urgently
sincerly,
Banai singh

by Banai singh Gurjar on Thursday, November 26th 2009 at 07:49 AM

in this way backup is easly create but when i restore my bd it genrate excpen restore failed to server/xyz plz. help me urgently
sincerly,
Banai singh

by Bilal on Wednesday, January 13th 2010 at 01:26 AM

Any one help me,

When i try to Restore SQL Sever 2005 DB, as same name used for BD.
It generate it does not Restore the Backup

I also used this statement:
rstDatabase.SqlRestoreAsync(srvSql);

Neither show progress bar...

What application do ?
(1)-It make connection with DB smoothly
(2)-It take BACKUP of BD as my own decided Drive
(3)-But does not Restore DB

I will be thankful to you ,
If you can help me to resolve my problem

You can write me hear :
mbilalpu@hotmail.com

Regards,
Bilal Zahid

by Sushil Mate on Wednesday, February 3rd 2010 at 02:14 AM

hi friends....
i find many of them dealing with the backup problem on without default sql path.

so here is the workaround
1) create the folder where you want to take backup or restore of database.
2)click right click goto properties
3)click on security give the full access to your account or if you confused give to all account full rights.
4)then take backup or restore in that folder. you will never find that error 'access is denied'

by Sushil Mate on Wednesday, February 3rd 2010 at 02:15 AM

hi friends....
i find many of them dealing with the backup problem on without default sql path.

so here is the workaround
1) create the folder where you want to take backup or restore of database.
2)click right click goto properties
3)click on security give the full access to your account or if you confused give to all account full rights.
4)then take backup or restore in that folder. you will never find that error 'access is denied'

by Sushil Mate on Wednesday, February 3rd 2010 at 02:15 AM

hi friends....
i find many of them dealing with the backup problem on without default sql path.

so here is the workaround
1) create the folder where you want to take backup or restore of database.
2)click right click goto properties
3)click on security give the full access to your account or if you confused give to all account full rights.
4)then take backup or restore in that folder. you will never find that error 'access is denied'

by Sushil Mate on Wednesday, February 3rd 2010 at 02:15 AM

hi friends....
i find many of them dealing with the backup problem on without default sql path.

so here is the workaround
1) create the folder where you want to take backup or restore of database.
2)click right click goto properties
3)click on security give the full access to your account or if you confused give to all account full rights.
4)then take backup or restore in that folder. you will never find that error 'access is denied'

by Sushil Mate on Wednesday, February 3rd 2010 at 02:15 AM

hi friends....
i find many of them dealing with the backup problem on without default sql path.

so here is the workaround
1) create the folder where you want to take backup or restore of database.
2)click right click goto properties
3)click on security give the full access to your account or if you confused give to all account full rights.
4)then take backup or restore in that folder. you will never find that error 'access is denied'

by Sushil Mate on Wednesday, February 3rd 2010 at 02:18 AM

ooppsssss...... sorrry for the repetitve comments...

by shiva on Thursday, February 4th 2010 at 04:33 AM

hi Thank u very nice..

These are run successfully in my machine.
But when i create exe or setup this application and run another machine i have a problem. backup failed(shiva\sqlexpress) in that servername.. Pls help me how to run successfully in other machine.
Other machine hav vs2005 sqlserver 2005 . but im gettin error..

by Sushil Mate on Thursday, February 4th 2010 at 11:39 PM

@shiva when you taking backup of database from another machine you should have right for the database.
do one thing goto start->control panel->administrative tools->services->sqlexpress
right click on that goto properties then goto log on tab...there you can mention the account name frm where you want to take the backup... but i suggest to use local system account in that you are not able to take backup from other machine...
why do u want to take backup frm another machine. when u are able to backup frm server or machine where DB actually presents....

by shiva on Friday, February 5th 2010 at 12:06 AM

im developing windows application. this code was successfully run and i got backup and restore it. but i want to take backup

by shiva on Friday, February 5th 2010 at 12:14 AM

im developing windows application. this code was successfully run and i got backup and restore it. but i want to take backup and Restore in another machine. every machine hav a sql server,DB. When i was create exe or setup file in this application and run another system i got error.. how can i fix the error..?

by Sushil Mate on Friday, February 5th 2010 at 12:40 AM

as i told you if u want to take backup of databace you should provide the access rights for the drive or machine...when u are running setup on another machine

by shiva on Friday, February 5th 2010 at 01:13 AM

After running successfully in my machine i create setup and installed another system.then i run the setup file i got error msgs backup failed (servername\sqlexpress)

by Shiva on Monday, February 8th 2010 at 11:43 PM

Hi this is nice code.. and this is working in my machine. In my machine hav management studio and some DB, i got backup and restore its successfully done.. but when i create this application exe and run client system its not rum im getting error "Cannot connect client server name ". Bcoz client system only installed express edition not in management studio I need all DB like project DBs(im installing new project in client system with DB.DB path c:\test\test1\test2\..)in this case how to get all DB name excluding system DB only software DB
and i want to take backup and restore all other machin.. Pls help me.. wat can i do..?

by Sushil Mate on Tuesday, February 9th 2010 at 12:12 AM

create the one procdure in database send there database

by ReX on Saturday, March 13th 2010 at 10:44 PM

Hi I used this code to backup file but it had a problem

I take the first time backup in D:\1.bak ,It's successful

In second times backup ,I couldn't backup overwrite the existing file 1.bak ,Backup failed

Pls help me


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons