public static void RestaurarBanco(string servidor, string banco, string physical_device_name, string friendlyName)
        {
            var server  = new Server(servidor);
            var restore = new Microsoft.SqlServer.Management.Smo.Restore();

            restore.Database = banco;
            restore.Devices.AddDevice(physical_device_name, Microsoft.SqlServer.Management.Smo.DeviceType.File);
            server.KillAllProcesses(banco);
            restore.SqlRestore(server);
            MessageBox.Show(string.Format("Backup '{0}' restaurado com sucesso.", friendlyName), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Exemple #2
0
        private void button2_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog GET_BAK = new OpenFileDialog())
            {
                GET_BAK.InitialDirectory = @"C:\";
                GET_BAK.RestoreDirectory = true;
                GET_BAK.Title            = "Employee Documents";
                GET_BAK.Multiselect      = false;
                GET_BAK.CheckFileExists  = true;
                GET_BAK.CheckPathExists  = true;
                GET_BAK.DefaultExt       = "bak";
                GET_BAK.Filter           = "bak File (*.bak)|*.bak";
                GET_BAK.FilterIndex      = 1;
                if (GET_BAK.ShowDialog() == DialogResult.OK)
                {
                    progressBar1.Value = 0;

                    try
                    {
                        Server dbServer = new Server(new ServerConnection(txtServer.Text /*, txtUsername.Text, txtPassword.Text*/));

                        dbServer.KillDatabase(txtDatabase.Text);
                        //dbServer.ConnectionContext.Disconnect();
                        //Disable automatic disconnection.
                        //dbServer.ConnectionContext.AutoDisconnectMode = AutoDisconnectMode.NoAutoDisconnect;
                        ////Connect to the local, default instance of SQL Server.
                        //dbServer.ConnectionContext.Connect();
                        ////The actual connection is made when a property is retrieved.
                        //Console.WriteLine(dbServer.Information.Version);
                        ////Disconnect explicitly.
                        //dbServer.ConnectionContext.Disconnect();
                        Microsoft.SqlServer.Management.Smo.Restore dbRestore = new Microsoft.SqlServer.Management.Smo.Restore()
                        {
                            Action = RestoreActionType.Database, Database = txtDatabase.Text
                        };

                        dbRestore.Devices.AddDevice(GET_BAK.FileName, DeviceType.File);
                        dbRestore.PercentComplete += DbRestore_PercentComplete;
                        dbRestore.Complete        += DbRestore_Complete;

                        dbRestore.SqlRestore(dbServer);

                        MessageBox.Show("Restoration successful");
                        //this.Close();
                    }


                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "Messsage", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        private void llCreateDB_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (OpenFileDialog GET_BAK = new OpenFileDialog())
            {
                GET_BAK.InitialDirectory = @"C:\";
                GET_BAK.RestoreDirectory = true;
                GET_BAK.Title            = "Employee Documents";
                GET_BAK.Multiselect      = false;
                GET_BAK.CheckFileExists  = true;
                GET_BAK.CheckPathExists  = true;
                GET_BAK.DefaultExt       = "bak";
                GET_BAK.Filter           = "bak File (*.bak)|*.bak";
                GET_BAK.FilterIndex      = 1;
                if (GET_BAK.ShowDialog() == DialogResult.OK)
                {
                    progressBar1.Value = 0;

                    try
                    {
                        Server dbServer = new Server(new ServerConnection(txtServer.Text /*, txtUsername.Text, txtPassword.Text*/));
                        Microsoft.SqlServer.Management.Smo.Restore dbRestore = new Microsoft.SqlServer.Management.Smo.Restore()
                        {
                            Action = RestoreActionType.Database, Database = txtDatabase.Text
                        };

                        dbRestore.Devices.AddDevice(GET_BAK.FileName, DeviceType.File);
                        dbRestore.PercentComplete += DbRestore_PercentComplete;
                        dbRestore.Complete        += DbRestore_Complete;
                        dbRestore.SqlRestore(dbServer);

                        MessageBox.Show(" Click Close to get Login Details");
                        //this.Close();
                    }


                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "Messsage", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Exemple #4
0
        /// <summary>
        ///   Restores each of the backups. If the default file location is available it will move the files to there.
        /// </summary>
        /// <param name="backupOrder">An ordered list of backups to apply.</param>
        /// <param name="databaseName">Database to restore to.</param>
        /// <param name="fileRelocation">Option for renaming files during the restore.</param>
        public void Restore(IEnumerable <BackupMetadata> backupOrder, string databaseName,
                            Func <string, string> fileRelocation = null)
        {
            var restore = new Smo.Restore();
            var defaultFileLocations = DefaultFileLocations();

            foreach (var backup in backupOrder)
            {
                var backupDeviceItem = new Smo.BackupDeviceItem(backup.PhysicalDeviceName, Smo.DeviceType.File);
                restore.Devices.Add(backupDeviceItem);
                restore.Database   = databaseName;
                restore.NoRecovery = true;
                if (defaultFileLocations != null)
                {
                    restore.RelocateFiles.Clear();
                    foreach (var file in restore.ReadFileList(_server).AsEnumerable())
                    {
                        var physicalName = (string)file["PhysicalName"];
                        var fileName     = Path.GetFileName(physicalName) ??
                                           throw new InvalidBackupException($"Physical name in backup is incomplete: {physicalName}");

                        if (fileRelocation != null)
                        {
                            fileName = fileRelocation(fileName);
                        }

                        var path = (string)file["Type"] == "L" ? defaultFileLocations?.Log : defaultFileLocations?.Data;

                        path = path ?? Path.GetFullPath(physicalName);

                        var newFilePath = Path.Combine(path, fileName);

                        restore.RelocateFiles.Add(new Smo.RelocateFile((string)file["LogicalName"], newFilePath));
                    }
                }

                restore.SqlRestore(_server);
                restore.Devices.Remove(backupDeviceItem);
            }
        }
Exemple #5
0
        private void RestoreButtonClick(object sender, RoutedEventArgs e)
        {
            var address = chooseRestoreFile();

            DetachDatabase();
            try
            {
                Server dbServer = new Server(new ServerConnection(System.Environment.MachineName));
                Microsoft.SqlServer.Management.Smo.Restore dbRestore = new Microsoft.SqlServer.Management.Smo.Restore()
                {
                    Action = RestoreActionType.Database, Database = "School"
                };
                dbRestore.Devices.AddDevice(@address, DeviceType.File);
                dbRestore.ReplaceDatabase = true;

                dbRestore.SqlRestore(dbServer);
                this.ShowMessageAsync("Restored", "Database restored successfully.");
            }
            catch (Exception err)
            {
                System.Windows.MessageBox.Show(address);
                System.Windows.MessageBox.Show(err.ToString());
            }
        }
    static public void Main(string[] args)
    {
        SqlConnection connection = new SqlConnection(Config.ConnectionString);
        SqlCommand    cmd        = new SqlCommand("", connection);

        string[]      databases   = null;
        List <string> dbDatabases = new List <string>();

        try
        {
            connection.Open();

            Console.WriteLine("Connected to server " + Config.DbServer + ".");
            Console.WriteLine("==========================================");

            Server server = new Server(Config.DbServer);

            cmd.CommandText = "SELECT name FROM master.dbo.sysdatabases WHERE name NOT IN ('master', 'model', 'msdb', 'tempdb')";

            using (IDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    dbDatabases.Add(dr[0].ToString());
                }
            }

            databases = System.IO.File.ReadAllLines("databases.txt");
            List <string> fileDatabases = new List <string>(databases);



            foreach (var db in fileDatabases)
            {
                if (!db.StartsWith("-") && !dbDatabases.Contains(db))
                {
                    Microsoft.SqlServer.Management.Smo.Restore restore = new Microsoft.SqlServer.Management.Smo.Restore();
                    restore.Action   = RestoreActionType.Database;
                    restore.Database = db;
                    restore.Devices.AddDevice(Config.BackupFolder + db + ".bak", DeviceType.File);
                    restore.ReplaceDatabase = true;
                    restore.NoRecovery      = false;
                    restore.SqlRestore(server);

                    Console.WriteLine("Database " + db + " restored.");
                }
            }


            cmd.Dispose();
            connection.Close();
            connection.Dispose();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error!");
            Console.WriteLine(ex.ToString());
        }

        Console.WriteLine("==========================================");
        Console.ReadKey();
    }