Esempio n. 1
0
        private void BackupButtonClick(object sender, RoutedEventArgs e)
        {
            string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));

            makeVisible();
            progressBarr.Value = 0;
            try
            {
                Server dbServer = new Server(new ServerConnection(System.Environment.MachineName));
                Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
                {
                    Action = BackupActionType.Database, Database = "School"
                };
                dbBackup.Devices.AddDevice(@backupDirectory() + "\\" + fileName, DeviceType.File);
                dbBackup.Initialize = true;
                dbBackup.SqlBackupAsync(dbServer);

                progressBarr.Value = 100;
                this.ShowMessageAsync("Backup", "Backup Completed!");
                lastBackup.Content = DateTime.Now.ToString("yyyy-MM-dd h:mm tt");
            }
            catch (Exception err)
            {
                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;

        try
        {
            connection.Open();

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


            databases = System.IO.File.ReadAllLines("databases.txt");

            Server server = new Server(Config.DbServer);

            foreach (var db in databases)
            {
                if (!db.StartsWith("-"))
                {
                    Microsoft.SqlServer.Management.Smo.Backup backup = new Microsoft.SqlServer.Management.Smo.Backup();
                    backup.Action   = BackupActionType.Database;
                    backup.Database = db;
                    backup.Devices.AddDevice(Config.BackupFolder + db + ".bak", DeviceType.File);
                    backup.BackupSetName        = db + " database Backup";
                    backup.BackupSetDescription = db + " database - Full Backup";
                    backup.Initialize           = true;
                    //backup.SqlBackupAsync(server);
                    backup.SqlBackup(server);

                    Console.WriteLine("Database " + db + " backup created.");
                }
            }


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

        Console.WriteLine("==========================================");
        Console.ReadKey();
    }
Esempio n. 3
0
        public static void BackupBanco(string servidor, string banco)
        {
            var server = new Server(servidor);
            var backup = new Microsoft.SqlServer.Management.Smo.Backup();

            backup.Database    = banco;
            backup.Incremental = false;
            string nomeArquivoBackup = string.Format("{0}_{1:yyyyMMdd_HHmmss}.bak", banco, DateTime.Now);

            backup.Devices.AddDevice(nomeArquivoBackup, Microsoft.SqlServer.Management.Smo.DeviceType.File);
            backup.SqlBackup(server);
            MessageBox.Show(string.Format("Backup '{0}' concluído com sucesso.", nomeArquivoBackup), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 4
0
        public bool backupBanco(string sEnderecoArquivo, string sPath, string sDiretorioBackup)
        {
            bool bResposta = false;

            try
            {
                Conexao      cConexao      = new Conexao();
                DadosConexao cDadosConexao = new DadosConexao();
                cDadosConexao = cConexao.buscarDadosConexao(sEnderecoArquivo, 0);
                if (cDadosConexao != null)
                {
                    var filePath = (sPath);
                    var sc       = new ServerConnection(cDadosConexao.sServidor, cDadosConexao.sUsuario, cDadosConexao.sSenha);
                    var server   = new Server(sc);
                    if (server.Databases[cDadosConexao.sNomeBaseDados] != null)
                    {
                        //criando o diretorio do backup
                        if (!Directory.Exists(sDiretorioBackup))
                        {
                            Directory.CreateDirectory(sDiretorioBackup);
                        }

                        //criando o objeto backup
                        Microsoft.SqlServer.Management.Smo.Backup bak = new Microsoft.SqlServer.Management.Smo.Backup();
                        bak.Incremental   = false;
                        bak.Action        = BackupActionType.Database;
                        bak.BackupSetName = "estacionamento_Backup";

                        //definindo o banco a ser salvo
                        bak.Database = cDadosConexao.sNomeBaseDados;
                        bak.Checksum = true;

                        //adicionando o destino
                        bak.Devices.Add(new BackupDeviceItem(filePath, DeviceType.File));
                        //executando o backup
                        bak.SqlBackup(server);
                        bResposta = true;
                    }
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Nenhum dado encontrado!", "EstacionamentoFacil (Backup01)", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
            catch (Exception ex) {
                System.Windows.Forms.MessageBox.Show("Erro ao executar o backup!\n" + ex.Message, "EstacionamentoFacil (Backup02)", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }

            return(bResposta);
        }
Esempio n. 5
0
        private void Backup(string databaseName, string backupPathTemplate, Smo.BackupActionType backupActionType,
                            Smo.BackupTruncateLogType truncateType)
        {
            var backup = new Smo.Backup {
                Action = backupActionType, Database = databaseName, LogTruncation = truncateType
            };
            var bdi =
                new Smo.BackupDeviceItem(string.Format(backupPathTemplate,
                                                       databaseName,
                                                       DateTime.Now.ToString("yyyy_MM_dd_hhmmss_fff")),
                                         Smo.DeviceType.File);

            backup.Devices.Add(bdi);
            backup.SqlBackup(_server);
        }
Esempio n. 6
0
        private void button2_Click(object sender, EventArgs e)
        {
            string _instance             = "localhost";
            string _repertoireSauvegarde = @"C:\Documents and Settings\Guillaume\SQLSave";

            string _horodatage = DateTime.Now.ToString("yyyyMMdd_hhmmss");

            smoCommon.ServerConnection sc = new smoCommon.ServerConnection(_instance);
            sc.Connect();
            smo.Server myServer = new smo.Server(sc);
            foreach (smo.Database myDb in myServer.Databases)
            {
                if (myDb.Name == "GEST_INFIRMERIE")
                {
                    smo.Backup myBackup = new smo.Backup();
                    myBackup.Database = myDb.Name;

                    // Définit le type de sauvegarde à effectuer  (base ou log)
                    myBackup.Action = smo.BackupActionType.Database;

                    // Sauvegarde FULL = false, Sauvegarde DIFF = true
                    myBackup.Incremental = false;

                    // Activation de la compression de la sauvegarde
                    myBackup.CompressionOption = smo.BackupCompressionOptions.Default;

                    // Ajout du device. Ici il s'agit d'un fichier mais on pourrait envisager une sauvegarde sur bande
                    myBackup.Devices.AddDevice(_repertoireSauvegarde + myDb.Name + "_" + _horodatage + ".bak", smo.DeviceType.File);
                    try
                    {
                        myBackup.SqlBackup(myServer);
                        Console.WriteLine(myDb.Name + " sauvegardée à " + DateTime.Now.ToString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            sc.Disconnect();
        }
Esempio n. 7
0
 private void btnBackUp_Click(object sender, EventArgs e)
 {
     progressBar.Value = 0;
     try
     {
         Server DbServer = new Server(new ServerConnection(txtServer.Text));
         Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
         {
             Action = BackupActionType.Database, Database = txtDatabase.Text
         };
         dbBackup.Devices.AddDevice(@txtPath.Text + "RoshanTraders" + DateTime.Now.ToShortDateString() + ".bak", DeviceType.File);
         dbBackup.Initialize = true; dbBackup.PercentComplete += DbBackup_PercentComplete;
         dbBackup.Complete  += DbBackup_Complete;
         dbBackup.SqlBackupAsync(DbServer);
         MessageBox.Show("Backup Completed");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Esempio n. 8
0
        private void button2_Click(object sender, EventArgs e)
        {
            string _instance = "localhost";
            string _repertoireSauvegarde = @"C:\Documents and Settings\Guillaume\SQLSave";

            string _horodatage = DateTime.Now.ToString("yyyyMMdd_hhmmss");
            smoCommon.ServerConnection sc = new smoCommon.ServerConnection(_instance);
            sc.Connect();
            smo.Server myServer = new smo.Server(sc);
            foreach (smo.Database myDb in myServer.Databases)
            {
                if (myDb.Name == "GEST_INFIRMERIE")
                {
                    smo.Backup myBackup = new smo.Backup();
                    myBackup.Database = myDb.Name;

                    // Définit le type de sauvegarde à effectuer  (base ou log)
                    myBackup.Action = smo.BackupActionType.Database;

                    // Sauvegarde FULL = false, Sauvegarde DIFF = true
                    myBackup.Incremental = false;

                    // Activation de la compression de la sauvegarde
                    myBackup.CompressionOption = smo.BackupCompressionOptions.Default;

                    // Ajout du device. Ici il s'agit d'un fichier mais on pourrait envisager une sauvegarde sur bande
                    myBackup.Devices.AddDevice(_repertoireSauvegarde + myDb.Name + "_" + _horodatage + ".bak", smo.DeviceType.File);
                    try
                    {
                        myBackup.SqlBackup(myServer);
                        Console.WriteLine(myDb.Name + " sauvegardée à " + DateTime.Now.ToString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            sc.Disconnect();
        }
Esempio n. 9
0
 public Microsoft.SqlServer.Management.Smo.Backup BackupDb()
 {
     try
     {
         if (csTransactions.ServerItems.ConnectName == "Local")
         {
             srv             = new Server(ServerItems.svName);
             BackUp          = new Backup();
             BackUp.Action   = BackupActionType.Database;
             BackUp.Database = this.DataBaseName;
             BackUp.Devices.AddDevice(this.FileName, DeviceType.File);
             BackUp.SqlBackup(srv);
         }
         if (csTransactions.ServerItems.ConnectName == "Remote")
         {
             SqlBackup sqlbak = new SqlBackup(csTransactions.RemoteConnectString_Tables(this.DataBaseName), this.FileName, true);
             sqlbak.GetDBSize();
             int fnum = sqlbak.CreateBakupFiles();
             sqlbak.CreateTempDB();
             for (int i = 0; i < fnum; i++)
             {
                 sqlbak.InsertBakFile(i + 1);
                 sqlbak.DownloadBakFile(i + 1);
                 sqlbak.DeleteBakFile();
             }
             sqlbak.DeleteTempDB();
             sqlbak.Dispose();
         }
         MinuteBackup.Current.MinuteLog("Database backup successfully completed date : " + timeClass.GetServerTime().ToString("yyyy-MM-dd-HH-mm-ss") + "\nDataBase Name : " + this.DataBaseName, this.TxtName);
         return(BackUp);
     }
     catch (Exception ex)
     {
         MinuteBackup.Current.MinuteLog("database backup operation resulted in errors : " + ex.Message, this.TxtName); return(null);
     }
 }
Esempio n. 10
0
        private void CreateBackUp()
        {
            try
            {
                string name = "RETBACK";

                SqlConnection    sqlCon     = new SqlConnection(CDS.Server.Backup.Properties.Settings.Default.conn);
                ServerConnection connection = new ServerConnection(sqlCon);

                Microsoft.SqlServer.Management.Smo.Server svr = new Microsoft.SqlServer.Management.Smo.Server(connection);
                Microsoft.SqlServer.Management.Smo.Backup bkp = new Microsoft.SqlServer.Management.Smo.Backup();

                string extra = CDS.Server.Backup.Properties.Settings.Default.site;


                string backupDirectory = CDS.Server.Backup.Properties.Settings.Default.backupdirectory;

                string backUpFilename = backupDirectory + "\\" + "CDS_" + extra + DateTime.Now.ToString("yyyy_MM_dd_hh_mm") + ".bak";
                Console.WriteLine("File name set : " + backUpFilename);
                if (!Directory.Exists(backupDirectory))
                {
                    Directory.CreateDirectory(backupDirectory);
                }
                bkp.Devices.AddDevice(backUpFilename, DeviceType.File);
                bkp.BackupSetDescription = name;
                bkp.BackupSetName        = name;

                bkp.Database    = CDS.Server.Backup.Properties.Settings.Default.databasename;
                bkp.Action      = BackupActionType.Database;
                bkp.Initialize  = true;
                bkp.Incremental = false;

                bkp.SqlBackup(svr);
                try
                {
                    string   smsisdn = CDS.Server.Backup.Properties.Settings.Default.contacts;
                    string[] msisdn  = smsisdn.Split(new char[] { ',' });
                    for (int t = 0; t < msisdn.Length; t++)
                    {
                        if (msisdn[t].Substring(0, 2) != "27")
                        {
                            msisdn[t] = "27" + msisdn[t].Substring(1);
                        }
                        SMS(msisdn[t], "CDS: " + CDS.Server.Backup.Properties.Settings.Default.site + " backup completed." + DateTime.Now.ToString("yyyy-MM-dd"));
                    }
                }
                catch (Exception ex)
                {
                    string error = ex.ToString();
                }

                //if (DateTime.Now.DayOfWeek.ToString().CompareTo(CDS.Server.Backup.Properties.Settings.Default.remotebackday) == 0)
                //{
                //    eventLog1.WriteEntry("Registering JOB");
                //    CreateJob(backUpFilename, "CDS_" + extra + DateTime.Now.ToString("yyyy_MM_dd_hh_mm") + ".bak");

                //}
                //else if (DateTime.Now.Day.ToString().CompareTo(CDS.Server.Backup.Properties.Settings.Default.remotebackupdate) == 0)
                //{
                //    eventLog1.WriteEntry("Registering JOB");
                //    CreateJob(backUpFilename, "CDS_" + extra + DateTime.Now.ToString("yyyy_MM_dd_hh_mm") + ".bak");

                //}

                // Delete old backups
                int daysOld = 30;
                daysOld = Convert.ToInt32(CDS.Server.Backup.Properties.Settings.Default.daysOld);
                deleteOldFiles(backupDirectory, DateTime.Now.AddDays(-daysOld));
            }
            catch (Exception ex)
            {
                //if (EventLog.SourceExists(""))
                eventLog1.WriteEntry(ex.ToString());
                string   smsisdn = CDS.Server.Backup.Properties.Settings.Default.contacts;
                string[] msisdn  = smsisdn.Split(new char[] { ',' });
                for (int t = 0; t < msisdn.Length; t++)
                {
                    if (msisdn[t].Substring(0, 2) != "27")
                    {
                        msisdn[t] = "27" + msisdn[t].Substring(1);
                    }
                    SMS(msisdn[t], "CDS:There was a problem with the " + CDS.Server.Backup.Properties.Settings.Default.site + " backup!");
                }
            }
            finally
            {
                Thread.Sleep(3600000);
            }
        }
        /// <summary>
        /// Create database back up in Zip format and kept in path
        /// </summary>
        /// <returns>int 0 -not success, 1- success, 2 - already backkup available</returns>
        public int CreateSqlDatabaseBackUp(FactoryReset oFactoryResetEntity)
        {
            SqlConnection    SqlConn = null;
            ServerConnection svrConnServerConnection = null;
            Server           SqlSever = null;
            Backup           bak      = null;
            BackupDeviceItem bkpitem  = null;
            DateTime         dt       = DateTime.Now;
            int iResult = 0;

            String[] format      = { "ddMMMyyyyHHmm" };
            string   bkpFileName = "";
            string   Backuppath  = "";
            string   date        = "";
            string   zipFileName = "";

            try
            {
                date        = dt.ToString(format[0], DateTimeFormatInfo.InvariantInfo);
                Backuppath  = oFactoryResetEntity.strBackupPath;
                bkpFileName = Backuppath + "\\" + "[" + date + "]" + "_BAK_" + "[" +
                              CommonDataAccess.GetSettingValue("TICKET_LOCATION_CODE") + "]" +
                              "[" + BMC.Transport.Settings.SiteName + "]" + "_" +
                              oFactoryResetEntity.BackUpDataBase + ".BAK";
                oFactoryResetEntity.strBackupFileName = bkpFileName;
                if (Directory.Exists(Backuppath))
                {
                    if (File.Exists(bkpFileName) == false)
                    {
                        try
                        {
                            SqlConn = new SqlConnection(CommonDataAccess.ExchangeConnectionString);
                            svrConnServerConnection = new ServerConnection(SqlConn);
                            SqlSever = new Server(svrConnServerConnection);

                            if (SqlSever != null)
                            {
                                bak        = new Microsoft.SqlServer.Management.Smo.Backup();
                                bak.Action = BackupActionType.Database;
                                bkpitem    = new BackupDeviceItem(bkpFileName, DeviceType.File);
                                bak.Devices.Add(bkpitem);
                                bak.Database = oFactoryResetEntity.BackUpDataBase;
                                bak.SqlBackup(SqlSever);
                            }
                        }
                        catch (SqlException sqlex)
                        {
                            ExceptionManager.Publish(sqlex);
                            iResult = 0;
                        }
                        catch (TimeoutException tex)
                        {
                            ExceptionManager.Publish(tex);
                            iResult = 0;
                        }

                        zipFileName = Backuppath + "\\" + "bkp" + oFactoryResetEntity.BackUpDataBase + date + ".ZIP";
                        zipFileName = Backuppath + "\\" + "[" + date + "]" + "_BAK_" + "[" +
                                      CommonDataAccess.GetSettingValue("TICKET_LOCATION_CODE") + "]" +
                                      "[" + BMC.Transport.Settings.SiteName + "]" + "_" +
                                      oFactoryResetEntity.BackUpDataBase + ".ZIP";
                        oFactoryResetEntity.strZipFileName = zipFileName;
                        iResult = 1;
                    }
                    else
                    {
                        iResult = 2;
                    }
                }
                else
                {
                    Directory.CreateDirectory(Backuppath);
                    try
                    {
                        SqlConn = new SqlConnection(CommonDataAccess.ExchangeConnectionString);
                        svrConnServerConnection = new ServerConnection(SqlConn);
                        SqlSever = new Server(svrConnServerConnection);

                        if (SqlSever != null)
                        {
                            bak        = new Microsoft.SqlServer.Management.Smo.Backup();
                            bak.Action = BackupActionType.Database;
                            bkpitem    = new BackupDeviceItem(bkpFileName, DeviceType.File);
                            bak.Devices.Add(bkpitem);
                            bak.Database = oFactoryResetEntity.BackUpDataBase;
                            bak.SqlBackup(SqlSever);
                        }
                    }
                    catch (SqlException sqlex)
                    {
                        ExceptionManager.Publish(sqlex);
                        iResult = 0;
                    }
                    catch (TimeoutException tex)
                    {
                        ExceptionManager.Publish(tex);
                        iResult = 0;
                    }
                    zipFileName = Backuppath + "bkp" + oFactoryResetEntity.BackUpDataBase + date + ".zip";
                    oFactoryResetEntity.strZipFileName = zipFileName;
                    iResult = 1;
                }
            }
            catch (FileNotFoundException fex)
            {
                ExceptionManager.Publish(fex);
                iResult = 0;
            }
            catch (FileLoadException flx)
            {
                ExceptionManager.Publish(flx);
                iResult = 0;
            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(ex);
                iResult = 0;
            }
            return(iResult);
        }