⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 frmbackuprestore.cs

📁 < SQL Server2005程序设计>
💻 CS
字号:
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 SMODemos
{
	public partial class frmBackupRestore : Form
	{
		public frmBackupRestore()
		{
			InitializeComponent();
		}

		private void btnOpenFile_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog1 = new OpenFileDialog();

			openFileDialog1.InitialDirectory = "c:\\";
			openFileDialog1.Filter = "bak files (*.bak)|*.txt|All files (*.*)|*.*";
			openFileDialog1.FilterIndex = 2;
			openFileDialog1.RestoreDirectory = true;

			if (openFileDialog1.ShowDialog() == DialogResult.OK)
			{
				txtFileName.Text = openFileDialog1.FileName.ToString();
		
			}
		}

		private void btnBackup_Click(object sender, EventArgs e)
		{
			//use the server selected in the Server ComboBox
            //this server can be typed in as well to the Cbo
            Server svr = new Server(cboServers.Text.ToString());
			Backup bkp = new Backup();

			Cursor = Cursors.WaitCursor;
			dataGridView1.DataSource = "";

            //attempt the backup and show a progress meter
            //a lot can go wrong here from file access
            //to DBCC issues so it is important to handle all
            //errors that may rise
			try
			{
				string strFileName = txtFileName.Text.ToString();
                string strDatabaseName = cboDatabase.Text.ToString();
				
				bkp.Action = BackupActionType.Database;
				bkp.Database = strDatabaseName;

				//set the device: File, Tape, etc
				bkp.Devices.AddDevice(strFileName, DeviceType.File);
				//set this when you want to do Incremental
				bkp.Incremental = chkIncremental.Checked;
 
				//progress meter stuff
				progressBar1.Value = 0;
				progressBar1.Maximum = 100;
				progressBar1.Value = 10;

				//this gives us the % complete by handling the event
				//provided by SMO on the percent complete, we will
				//update the progress meter in the event handler

				//set the progress meter to 10% by default
				bkp.PercentCompleteNotification = 10;
				//call to the event handler to incriment the progress meter

				bkp.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);
				//this does the backup
				bkp.SqlBackup(svr);
				//alert the user when it is all done
				MessageBox.Show("Database Backed Up To: " + strFileName, "SMO Demos");
			
				
			}
			catch (SmoException exSMO)
			{
				MessageBox.Show(exSMO.ToString());

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}

			finally
			{
				Cursor = Cursors.Default;
				progressBar1.Value = 0;
			}
			

		}

		private void btnBackupLog_Click(object sender, EventArgs e)
		{
			Server svr = new Server();//assuming local server
			Backup bkp = new Backup();

			Cursor = Cursors.WaitCursor;
			dataGridView1.DataSource = "";

			try
			{
				string strFileName = txtFileName.Text.ToString();
                string strDatabaseName = cboDatabase.SelectedValue.ToString();

				bkp.Action = BackupActionType.Log;
				bkp.Database = strDatabaseName;

				//set the device: File, Tape, etc
				bkp.Devices.AddDevice(strFileName, DeviceType.File);

				//progress meter stuff
				//progress meter stuff
				progressBar1.Value = 0;
				progressBar1.Maximum = 100;
				progressBar1.Value = 10;

				//for notification to immediate window of % complete
				bkp.PercentCompleteNotification = 10;
				bkp.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);

				bkp.SqlBackup(svr);
				MessageBox.Show("Log Backed Up To: " + strFileName, "SMO Demos");
			}
			catch (SmoException exSMO)
			{
				MessageBox.Show(exSMO.ToString());

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}

			finally
			{
				Cursor = Cursors.Default;
				progressBar1.Value = 0;
			}

			
		}

		private void btnVerify_Click(object sender, EventArgs e)
		{
			Server svr = new Server();
			Restore rest = new Restore();
			bool blnVerify;
			DataTable dt=new DataTable();


			Cursor = Cursors.WaitCursor;
			dataGridView1.DataSource = "";

			try
			{
				string strFileName = txtFileName.Text.ToString();

				rest.Devices.AddDevice(strFileName, DeviceType.File);
				blnVerify = rest.SqlVerify(svr);

				if (blnVerify == true)
				{
					MessageBox.Show("Backup Verified!", "SMO Demos");
					dt = rest.ReadFileList(svr);
					dataGridView1.DataSource = dt;
				}
				else
				{
					MessageBox.Show("Backup NOT Verified!", "SMO Demos");
				}
			}
			catch (SmoException exSMO)
			{
				MessageBox.Show(exSMO.ToString());

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}

			finally
			{
				Cursor = Cursors.Default;
			}
		}

private void btnRestore_Click(object sender, EventArgs e)
{
    Server svr = new Server(cboServers.Text.ToString());
	Restore res = new Restore();

	Cursor = Cursors.WaitCursor;
	dataGridView1.DataSource = "";

	try
	{
		string strFileName = txtFileName.Text.ToString();
        string strDatabaseName = cboDatabase.SelectedValue.ToString();

		res.Database = strDatabaseName;
		res.Action = RestoreActionType.Database;
		//use for restore of the log
		//res.Action = RestoreActionType.Log;
		res.Devices.AddDevice(strFileName, DeviceType.File);

		//progress meter stuff
		progressBar1.Value = 0;
		progressBar1.Maximum = 100;
		progressBar1.Value = 10;

		res.PercentCompleteNotification = 10;
		res.ReplaceDatabase = true;
		res.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);

		//use below if you want to relocate the mdf files
		//res.RelocateFiles.Add(new RelocateFile("aw_data", @"c:\aw_dat.mdf"));
		
		//preform the restore
		res.SqlRestore(svr);

		MessageBox.Show("Restore of " + strDatabaseName + " Complete!", "SMO Demos");
	}
	catch (SmoException exSMO)
	{
		MessageBox.Show(exSMO.ToString());

	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.ToString());
	}

	finally
	{
		Cursor = Cursors.Default;
		progressBar1.Value = 0;
	}
}

		public void ProgressEventHandler(object sender, PercentCompleteEventArgs e)
		{
			//increase the progress bar up by the percent
			progressBar1.Value = e.Percent; 
			//for debugging
			Console.WriteLine(e.Percent.ToString() + "% Complete");
		}

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            //get a DataTable of the servers
			DataTable dtList = SMOUtilities.ListAllKnownInstances();

			foreach (DataRow dr in dtList.Rows)
			{
				String ServerName;
				ServerName = dr["Server"].ToString();

				if (dr["Instance"] != null && dr["Instance"].ToString().Length > 0)
					ServerName += @"\" + dr["Instance"].ToString();

				if (cboServers.Items.IndexOf(ServerName) < 0)
					cboServers.Items.Add(ServerName);
			}

			//  By default select the local server
			Server LocalServer = new Server();
			String LocalServerName = LocalServer.Name;

			if (LocalServer.InstanceName != null && LocalServer.InstanceName.Length > 0)
				LocalServerName += @"\" + LocalServer.InstanceName;

			int intCboIndex = cboServers.FindStringExact(LocalServerName);
			if (intCboIndex >= 0)
				cboServers.SelectedIndex = intCboIndex;

            Cursor = Cursors.Default;
		}

        private void btnSSPI_Click(object sender, EventArgs e)
        {
            try
            {
                //use an hourglass
                Cursor = Cursors.WaitCursor;
                //clear out the items, if you don't do this then
                //the combobox will have dupes when you click on
                //the show system database box
                cboDatabase.Items.Clear();

                //this is a reusable function that fills the 
                //combobox with the available databases on a 
                //particular server, passing in the cbo by reg
                //we will reuse this in a later example
                SMOUtilities.FillComboWithDatabases(cboServers.Text.ToString(), true, ref cboDatabase);

            }
            catch (SmoException exSMO)
            {
                MessageBox.Show(exSMO.Message.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                Cursor = Cursors.Default;
            }

        }
        }



	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -