Пример #1
0
        public Task <Stream> OpenRead(BackupItem item)
        {
            string constring = $"server={Server};user={Username};pwd={Password};database={Database};SslMode=none;";

            // Important Additional Connection Options
            constring += "charset=utf8;convertzerodatetime=true;";

            memoryStream = new MemoryStream();

            using (MySqlConnection conn = new MySqlConnection(constring))
            {
                using (MySqlCommand cmd = new MySqlCommand {
                    Connection = conn
                })
                {
                    using (MySqlBackup mb = new MySqlBackup(cmd))
                    {
                        conn.Open();
                        mb.ExportToMemoryStream(memoryStream);
                    }
                }
            }

            memoryStream.Seek(0, SeekOrigin.Begin);

            return(Task.FromResult(memoryStream as Stream));
        }
        public string Backup(string password = "", bool DropDatabaseFirst = true)
        {
            try
            {
                if (this.Connection != null)
                {
                    if (this.Connection is SqlConnection)
                    {
                    }
                    else if (this.Connection is MySqlConnection)
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (MySqlCommand cmd = new MySqlCommand())
                            {
                                using (MySqlBackup mb = new MySqlBackup(cmd))
                                {
                                    cmd.Connection = this.Connection;
                                    this.Connection.Open();
                                    mb.ExportInfo.AddDropDatabase      = DropDatabaseFirst;
                                    mb.ExportInfo.AddCreateDatabase    = true;
                                    mb.ExportInfo.ExportTableStructure = true;
                                    mb.ExportInfo.ExportRows           = true;
                                    mb.ExportToMemoryStream(ms);

                                    var dt   = DateTime.Now.ToString("yyyyMMddHmmssfff");
                                    var file = "Database_Backup" + "_" + dt + ".zip";

                                    using (ZipFile zip = new ZipFile())
                                    {
                                        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                                        if (!string.IsNullOrEmpty(password))
                                        {
                                            zip.Password = password;
                                        }
                                        zip.Encryption = EncryptionAlgorithm.PkzipWeak; // the default: you might need to select the proper value here
                                        zip.StatusMessageTextWriter = Console.Out;
                                        zip.AddEntry(@"db.sql", ms.ToArray());
                                        zip.Save(file);
                                        this.Connection.Close();
                                        return(file);
                                    }
                                }
                            }
                        }
                    }
                    else if (this.Connection is SQLiteConnection)
                    {
                    }
                }
            }
            catch (Exception ex) {
                this.Connection.Close();
                Log.Trace(ex.Message, ex.StackTrace);
            }

            return(null);
        }
Пример #3
0
        public void TakeBackup(bool compress = false)
        {
            try
            {
                using (MySqlBackup mySqlBackup = new MySqlBackup(this.Command))
                {
                    string path = Path.Combine(Environment.CurrentDirectory, "Backups");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    mySqlBackup.ExportProgressChanged              += new MySqlBackup.exportProgressChange(this.ExportProgressStatusChanged);
                    mySqlBackup.GetTotalRowsProgressChanged        += new MySqlBackup.getTotalRowsProgressChange(this.GetTotalRowsProgressStatusChanged);
                    mySqlBackup.ExportInfo.GetTotalRowsBeforeExport = true;

                    if (compress)
                    {
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                            {
                                ZipArchiveEntry zipArchiveEntry = zipArchive.CreateEntry(DateTime.Now.ToString().Replace(':', '-') + ".sql"); //we need replace : with - becase windows dont support : on file names
                                using (Stream zipArchiveEntryStream = zipArchiveEntry.Open())
                                {
                                    using (BinaryWriter binaryWriter = new BinaryWriter(zipArchiveEntryStream))
                                    {
                                        MemoryStream memoryStream2 = new MemoryStream();
                                        using (memoryStream2)
                                        {
                                            mySqlBackup.ExportToMemoryStream(memoryStream2);
                                        }
                                        binaryWriter.Write(memoryStream2.ToArray());
                                    }
                                }
                            }

                            using (FileStream file = File.Create(path + @"\" + DateTime.Now.ToString("d.M.yyyy HH-mm") + ".zip")) //we need replace : with - becase windows dont support : on file names
                            {
                                memoryStream.Seek(0, SeekOrigin.Begin);
                                memoryStream.CopyTo(file);
                            }
                        }
                    }
                    else
                    {
                        mySqlBackup.ExportToFile(path + @"\" + DateTime.Now.ToString("d.M.yyyy HH-mm") + ".sql"); //we need replace : with - becase windows dont support : on file names
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("CRITICAL ERROR WHEN TRYING GET BACKUPS! " + ex.ToString());
            }
        }
Пример #4
0
    protected void GuardaButton_Click(object sender, EventArgs e)
    {
        string       constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        MemoryStream ms     = new MemoryStream();

        using (MySqlConnection conn = new MySqlConnection(constr))
        {
            MySqlCommand cmd = new MySqlCommand();
            MySqlBackup  mb  = new MySqlBackup(cmd);
            cmd.Connection = conn;
            conn.Open();
            mb.ExportToMemoryStream(ms);
        }

        Response.ContentType = "text/plain";
        Response.AppendHeader("Content-Disposition", "attachments; filename=*.sql");
        Response.BinaryWrite(ms.ToArray());
        Response.End();
    }
Пример #5
0
 private void btExport_Click(object sender, EventArgs e)
 {
     try
     {
         MemoryStream    ms   = new MemoryStream();
         MySqlConnection conn = new MySqlConnection(Program.ConnectionString);
         MySqlCommand    cmd  = new MySqlCommand();
         MySqlBackup     mb   = new MySqlBackup(cmd);
         cmd.Connection = conn;
         conn.Open();
         mb.ExportToMemoryStream(ms);
         conn.Close();
         LoadIntoMemory(ms.ToArray());
         MessageBox.Show("Finished.");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
 }
Пример #6
0
        public static MemoryStream Download()
        {
            MemoryStream stream = new MemoryStream();

            using (MySqlConnection connection = new MySqlConnection(ConnectionString))
            {
                using MySqlCommand command = new MySqlCommand();
                using MySqlBackup backup   = new MySqlBackup(command);
                try
                {
                    command.Connection = connection;
                    connection.Open();
                    backup.ExportToMemoryStream(stream, true);
                    connection.Close();
                    stream.Position = 0;
                }
                catch (Exception)
                {
                    return(null);
                }
            }

            return(stream);
        }
Пример #7
0
        void FazerBackup(Propriedades item)
        {
            try
            {
                string nomeArquivo = "", constring = "", pathDestinoArquivo = "", nomeArquivoCompactado = "";
                foreach (string b in item.ListaBancos)
                {
                    constring = "server=" + item.IpBanco + ";port=" + item.PortaBanco + ";user id=" + item.UsuarioBanco + ";Password="******";database=" + b + ";Convert Zero Datetime=True;pooling=false; Allow User Variables=True;";
                    using (MySqlConnection conn = new MySqlConnection(constring))
                    {
                        using (MySqlCommand cmd = new MySqlCommand())
                        {
                            cmd.CommandTimeout = 7200;
                            using (MySqlBackup mb = new MySqlBackup(cmd))
                            {
                                cmd.Connection = conn;
                                if (conn.State != ConnectionState.Open)
                                {
                                    conn.Open();
                                }

                                mb.ExportInfo.AddCreateDatabase    = true;
                                mb.ExportInfo.ExportTableStructure = true;
                                mb.ExportInfo.ExportRows           = true;
                                mb.ExportInfo.ExportProcedures     = true;
                                mb.ExportInfo.ExportFunctions      = true;
                                mb.ExportInfo.ExportTriggers       = true;
                                mb.ExportInfo.ExportViews          = true;

                                mb.ExportProgressChanged += new MySqlBackup.exportProgressChange(mb_ExportProgressChange);

                                if (item != null && item.Destinos.Length > 0)
                                {
                                    string destino = item.Destinos[0];
                                    if (!string.IsNullOrWhiteSpace(destino))
                                    {
                                        MemoryStream ms = new MemoryStream();
                                        nomeArquivo = item.Nome.RemoveCaracteresEspeciais().RemoveWhitespace() + "_" + b + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".sql";
                                        mValorMSG   = "Fazendo backup de " + b + " para \r\nPasta: " + destino + "\r\nArquivo: " + nomeArquivo;
                                        if (item.Compactar)
                                        {
                                            mb.ExportToMemoryStream(ms);
                                        }
                                        else
                                        {
                                            pathDestinoArquivo = destino + "\\" + nomeArquivo;
                                            mb.ExportToFile(pathDestinoArquivo);
                                            Log("log.txt", "FazerBackup", item.Nome, b, destino, "Backup efetuado com sucesso!");
                                        }
                                        if (item.Compactar)
                                        {
                                            byte[] data = ms.ToArray();
                                            using (MemoryStream stream = new MemoryStream(data))
                                            {
                                                using (ZipFile zip = new ZipFile())
                                                {
                                                    zip.AddEntry(nomeArquivo, stream);
                                                    nomeArquivoCompactado = Path.GetFileNameWithoutExtension(nomeArquivo) + "." + item.Compactador;
                                                    pathDestinoArquivo    = destino + "\\" + nomeArquivoCompactado;
                                                    zip.Save(pathDestinoArquivo);
                                                    Log("log.txt", "FazerBackup", item.Nome, b, destino, "Backup em " + item.Compactador + " efetuado com sucesso!");
                                                }
                                            }
                                            File.Delete(destino + "\\" + nomeArquivo);
                                        }
                                        ConfigFtp host = new ConfigFtp()
                                        {
                                            UtilizarHostFtp          = item.UtilizarHostFtp,
                                            FilePath                 = pathDestinoArquivo,
                                            MostrarJanelaNotificacao = item.MostrarJanelaNotificacao,
                                            NomeBanco                = item.Nome
                                        };
                                        mFilaEnviarFtp.Enqueue(host);

                                        foreach (string outroDestino in item.Destinos)
                                        {
                                            if (outroDestino == destino)
                                            {
                                                continue;
                                            }
                                            try
                                            {
                                                if (File.Exists(pathDestinoArquivo))
                                                {
                                                    File.Copy(pathDestinoArquivo, outroDestino + "\\" + nomeArquivoCompactado);
                                                }
                                            }
                                            catch { }
                                        }
                                    }
                                }
                                conn.Close();
                            }
                        }
                    }
                }
                try
                {
                    ApagarBackupAntigos(item);
                }
                catch (Exception ex)
                {
                    LogErro("LOGERRO.TXT", "ApagarBackupAntigo", ex.Message);
                }
            }
            catch (Exception ex)
            {
                LogErro("LOGERRO.TXT", "FazerBackup", ex.Message);
            }
        }
Пример #8
0
        public static Task Backup(string file_name)
        {
            return(Task.Run(async() =>
            {
                DateTime now_is = DateTime.Now;



                using (MemoryStream zip_stream = new MemoryStream())
                    using (ZipOutputStream zos = new ZipOutputStream(zip_stream))
                    {
                        zos.SetLevel(9);

                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (MySqlConnection sqlconn = new MySqlConnection(MCv2Persistance.Instance.Config.DatabaseConfiguration.DatabaseConnectionProperties.ConnectionString))
                                using (MySqlCommand cmd = new MySqlCommand())
                                    using (MySqlBackup mb = new MySqlBackup(cmd))
                                    {
                                        cmd.Connection = sqlconn;
                                        await sqlconn.OpenAsync();
                                        mb.ExportToMemoryStream(ms);
                                    }

                            ZipEntry ze = new ZipEntry("dbbak.sql");

                            ze.DateTime = now_is;
                            ze.Size = ms.Length;

                            zos.PutNextEntry(ze);

                            ms.Position = 0;

                            StreamUtils.Copy(ms, zos, new byte[4096]);

                            zos.CloseEntry();
                            await zos.FlushAsync();
                        }

                        //

                        using (MemoryStream ms = new MemoryStream())
                        {
                            var backprop = new BackupProperties();
                            backprop.Timestamp = now_is;
                            var corrected_var = MCv2Persistance.Instance.Config.DatabaseConfiguration.DatabaseConnectionProperties;
                            corrected_var.UID = "";
                            corrected_var.Password = "";
                            backprop.Database = corrected_var;

                            var bytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(backprop));
                            ms.Write(bytes, 0, bytes.Length);

                            ZipEntry ze = new ZipEntry("properties.json");

                            ze.DateTime = DateTime.Now;
                            ze.Size = ms.Length;

                            zos.PutNextEntry(ze);

                            ms.Position = 0;

                            StreamUtils.Copy(ms, zos, new byte[4096]);


                            zos.CloseEntry();
                            await zos.FlushAsync();
                        }



                        zos.Finish();

                        File.WriteAllBytes(file_name, zip_stream.ToArray());
                    }
            }));
        }
Пример #9
0
        private void FazerBackup(Propriedades item)
        {
            try
            {
                string nomeArquivo = "", constring = "";

                string pathDestinoArquivo = string.Empty;

                foreach (string b in item.ListaBancos)
                {
                    constring = "server=" + item.IpBanco + ";port=" + item.PortaBanco + ";user id=" + item.UsuarioBanco + ";Password="******";database=" + b + ";Convert Zero Datetime=True;pooling=false; Allow User Variables=True;";

                    using (MySqlConnection conn = new MySqlConnection(constring))
                    {
                        using (MySqlCommand cmd = new MySqlCommand())
                        {
                            using (MySqlBackup mb = new MySqlBackup(cmd))
                            {
                                cmd.Connection = conn;
                                conn.Open();

                                mb.ExportProgressChanged += new MySqlBackup.exportProgressChange(mb_ExportProgressChange);

                                foreach (string destino in item.Destinos)
                                {
                                    MemoryStream ms = new MemoryStream();

                                    nomeArquivo = item.Nome.RemoveCaracteresEspeciais().RemoveWhitespace() + "_" + b + "_" + DateTime.Now.ToString("ddMMyyyyHHmmssfff") + ".sql";
                                    mValorMSG   = "Fazendo backup de " + b + " para \r\nPasta: " + destino + "\r\nArquivo: " + nomeArquivo;

                                    if (item.Compactar)
                                    {
                                        mb.ExportToMemoryStream(ms);
                                    }

                                    else
                                    {
                                        pathDestinoArquivo = destino + "\\" + nomeArquivo;
                                        mb.ExportToFile(pathDestinoArquivo);
                                        Log("log.txt", "FazerBackup", item.Nome, b, destino, "Backup efetuado com sucesso!");
                                    }


                                    if (item.Compactar)
                                    {
                                        byte[] data = ms.ToArray();
                                        using (MemoryStream stream = new MemoryStream(data))
                                        {
                                            using (ZipFile zip = new ZipFile())
                                            {
                                                zip.AddEntry(nomeArquivo, stream);
                                                pathDestinoArquivo = destino + "\\" + Path.GetFileNameWithoutExtension(nomeArquivo) + "." + item.Compactador;
                                                zip.Save(pathDestinoArquivo);
                                                Log("log.txt", "FazerBackup", item.Nome, b, destino, "Backup em " + item.Compactador + " efetuado com sucesso!");
                                            }
                                        }

                                        File.Delete(destino + "\\" + nomeArquivo);
                                    }

                                    ConfigFtp host = new ConfigFtp()
                                    {
                                        UtilizarHostFtp          = item.UtilizarHostFtp,
                                        FilePath                 = pathDestinoArquivo,
                                        MostrarJanelaNotificacao = item.MostrarJanelaNotificacao,
                                        NomeBanco                = item.Nome
                                    };

                                    mFilaEnviarFtp.Enqueue(host);
                                }

                                conn.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogErro("LOGERRO.TXT", "FazerBackup", ex.Message);
            }
        }