private void btImport_Click(object sender, EventArgs e)
        {
            if (!Program.SourceFileExists())
                return;

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

                            mb.ImportFromFile(Program.TargetFile);

                            conn.Close();
                        }
                    }
                }

                MessageBox.Show("Done.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #2
0
        public static void importBackUp(String filename)
        {
            try
            {

                var connection = System.Configuration.ConfigurationManager.ConnectionStrings["admEntities"].ConnectionString;//.Replace(""", "'");
                string constring = connection.Remove(0, connection.IndexOf("server=")).Replace("\"", "");// "server=localhost;user id=root;port=3300;database=adm";// connection;
                string file = filename;
                using (MySqlConnection conn = new MySqlConnection(constring))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        using (MySqlBackup mb = new MySqlBackup(cmd))
                        {
                            cmd.Connection = conn;
                            conn.Open();
                            mb.ImportFromFile(file);
                            conn.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Log.write(e.Message + " " + e.InnerException?.Message);
                throw e;

            }
        }
Beispiel #3
0
 /// <summary>
 /// Back up a MySql database from the specified file.
 /// </summary>
 public static void Restore(string path, string conectionString)
 {
     using (MySqlConnection conn = new MySqlConnection(conectionString))
     {
         using (MySqlCommand cmd = new MySqlCommand("", conn))
         {
             conn.Open();
             var backup = new MySqlBackup(cmd);
             backup.ImportFromFile(path);
             conn.Close();
         }
     }
 }
        public static void importDataBase()
        {
            try
            {
                // On demande le fichier à l'utilisateur
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Title = "Rechercher un fichier";
                openFileDialog1.FileName = "backup_gestionstock.sql";
                openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                openFileDialog1.Filter = "SQL files (*.sql)|*.sql|All files (*.*)|*.*";
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // On affecte le chemin de l'utilisateur et son fichier puis on utilise le fichier pour la restauration
                        string fileimport = openFileDialog1.FileName;

                        // On définit les variables
                        MySqlCommand cmdimport = new MySqlCommand();
                        MySqlBackup mbimport = new MySqlBackup(cmdimport);

                        // On ouvre la connexion, utilise la fonction du package et on ferme la connexion
                        cmdimport.Connection = M_connexion.Gestion;
                        M_connexion.Gestion.Open();
                        mbimport.ImportInfo.DatabaseDefaultCharSet = "utf8";
                        mbimport.ImportFromFile(fileimport);
                        M_connexion.Gestion.Close();
                        MessageBox.Show("Base de données importée." + Environment.NewLine + "A partir du fichier situé dans le chemin : " + fileimport);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Erreur: " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Impossible de lire le fichier à partir du disque. Erreur: " + ex.Message);
            }
        }
Beispiel #5
0
        private void button2_Click(object sender, EventArgs e)
        {
            MySqlConnection conn = new MySqlConnection(Rstring);
            MySqlCommand cmd;
            string s0;

            try
            {
                conn.Open();
                s0 = "CREATE DATABASE IF NOT EXISTS `esalon`;";
                cmd = new MySqlCommand(s0, conn);
                cmd.ExecuteNonQuery();
                conn.Close();
                MessageBox.Show("CREATE SUCCESS");
            }
            catch (Exception fe)
            {
                MessageBox.Show(fe.ToString());
            }
            try
            {
                string constring = "server=localhost;user=root;pwd=root;database=esalon;";
                using (MySqlConnection conn1 = new MySqlConnection(constring))
                {
                    using (MySqlCommand cmd1 = new MySqlCommand())
                    {
                        using (MySqlBackup mb = new MySqlBackup(cmd1))
                        {
                            cmd1.Connection = conn1;
                            conn1.Open();
                            mb.ImportFromFile(file);
                            conn1.Close();
                        }
                    }
                }
                MessageBox.Show("RESTORE SUCCESS");
            }
            catch (Exception fe)
            {
                MessageBox.Show(fe.ToString());
            }
        }
Beispiel #6
0
 public void Restore()
 {
     string constring = "server=localhost;user=quizuser;pwd=quizpassword;database=quizappmysql;";
     string file = "backup.sql";
     using (MySqlConnection conn = new MySqlConnection(constring))
     {
         using (MySqlCommand cmd = new MySqlCommand())
         {
             using (MySqlBackup mb = new MySqlBackup(cmd))
             {
                 cmd.Connection = conn;
                 conn.Open();
                 mb.ImportFromFile(file);
                 conn.Close();
             }
         }
     }
 }
        private void button_Restore_Click(object sender, EventArgs e)
        {
            if (!Program.SourceFileExists())
                return;

            Exception error = null;

            try
            {
                using (MySqlConnection conn = new MySqlConnection(Program.ConnectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        cmd.Connection = conn;
                        conn.Open();

                        using (MySqlBackup mb = new MySqlBackup(cmd))
                        {
                            mb.ImportInfo.EnableEncryption = cbImEnableEncryption.Checked;
                            mb.ImportInfo.EncryptionPassword = txtImPwd.Text;
                            mb.ImportInfo.IgnoreSqlError = cbImIgnoreSqlErrors.Checked;
                            mb.ImportInfo.TargetDatabase = txtImTargetDatabase.Text;
                            mb.ImportInfo.DatabaseDefaultCharSet = txtImDefaultCharSet.Text;
                            mb.ImportInfo.ErrorLogFile = txtImErrorLogFile.Text;
                            
                            mb.ImportFromFile(Program.TargetFile);

                            error = mb.LastError;
                        }

                        conn.Close();
                    }
                }

                if (error == null)
                    MessageBox.Show("Finished.");
                else
                    MessageBox.Show("Finished with errors." + Environment.NewLine + Environment.NewLine + error.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #8
0
        public static void RestoreSystemTables(string fileName)
        {
            fileName = fileName.Replace('/', '_');
                fileName = fileName.Replace(':', '-');

                using (var cmd = new MySqlCommand())
                {
                    using (var mb = new MySqlBackup(cmd))
                    {
                        cmd.Connection = _connectionSystem;
                        mb.ImportFromFile(BackUpFilePath+"\\"+fileName);

                    }
                }
        }
Beispiel #9
0
        private void btImportUnzipFile_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog of = new OpenFileDialog();
                of.Filter = "Zip|*.zip";
                of.Title = "Select the Zip file";
                of.Multiselect = false;
                if (of.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                string zipfile = of.FileName;

                FolderBrowserDialog f = new FolderBrowserDialog();
                f.Description = "Extract the dump file to which folder?";
                if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                string folder = f.SelectedPath;
                string dumpFile = "";

                using (ZipStorer zip = ZipStorer.Open(zipfile, FileAccess.Read))
                {
                    List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                    dumpFile = folder + "\\" + dir[0].FilenameInZip;
                    zip.ExtractFile(dir[0], dumpFile);
                }

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

                            mb.ImportFromFile(dumpFile);

                            conn.Close();
                        }
                    }
                }

                MessageBox.Show("Finished.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #10
0
 public static void Restore(string dir)
 {
     using (MySqlConnection connect = new MySqlConnection(AppProperties.ConnectionString()))
     {
         using (MySqlCommand command = new MySqlCommand())
         {
             command.Connection = connect;
             using (MySqlBackup backup = new MySqlBackup(command))
             {
                 try
                 {
                     connect.Open();
                     backup.ExportInfo.EnableEncryption = true;
                     backup.ExportInfo.EncryptionPassword = "******";
                     backup.ImportFromFile(dir);
                 }
                 catch (Exception ex)
                 {
                     XtraMessageBox.Show(ex.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 }
             }
         }
     }
 }
        private void buttonX2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofRestore = new OpenFileDialog();
            ofRestore.Filter = "sql files (*.sql)|*.sql|All files (*.*)|*.*";
            ofRestore.RestoreDirectory = true;

            Database dbc = new Database();
            string strconnect = dbc.getString();
            MySqlConnection connect = new MySqlConnection(strconnect);
            connect.Open();

            if (ofRestore.ShowDialog() == DialogResult.OK)
            {

                try
                {
                    using (MySqlConnection conn = new MySqlConnection(strconnect))
                    {
                        using (MySqlCommand cmd = new MySqlCommand())
                        {
                            using (MySqlBackup mb = new MySqlBackup(cmd))
                            {
                                cmd.Connection = conn;
                                conn.Open();
                                mb.ImportFromFile(ofRestore.FileName);
                                conn.Close();
                                MessageBox.Show("Restore berhasil", "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                }
                catch (SystemException ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
        }
Beispiel #12
0
 public static bool RestoreDb(string file)
 {
     try
     {
         if (!connect()) return false;
         if (!File.Exists(file)) return false;
         MySqlBackup mb = new MySqlBackup(cmd);
         mb.ImportFromFile(file);
         return true;
     }
     catch (Exception ex)
     {
         ErrorHandler.Errors.displayError("We were unable to restore the database.", ErrorHandler.ErrorCode.RestoreDb, ErrorHandler.ErrorAction.Continue, ex);
         return false;
     }
 }
Beispiel #13
0
 public void MySqlImport(bool sve, List<string> tablice, bool pogledi, bool procedure, bool okidaci, string ConnectionString, string pohrana)
 {
     using (MySqlConnection con = new MySqlConnection(ConnectionString))
     {
         using (MySqlCommand cmd = new MySqlCommand())
         {
             using (MySqlBackup mb = new MySqlBackup(cmd))
             {
                 cmd.Connection = con;
                 con.Open();
                 if (sve == true)
                 {
                     mb.ImportFromFile(pohrana);
                 }
                 else if (tablice != null)
                 {
                     mb.ImportFromFile(pohrana);
                 }
                 else if (pogledi == true)
                 {
                     mb.ImportFromFile(pohrana);
                 }
                 else if (procedure == true)
                 {
                     mb.ImportFromFile(pohrana);
                 }
                 else if (okidaci == true)
                 {
                     mb.ImportFromFile(pohrana);
                 }
             }
         }
         con.Close();
     }
 }
        public static void importer()
        {
            string filei = "C:\\Users\\Rodaxfck\\Desktop";

            using (MySqlCommand cmdi = new MySqlCommand())
            {
                using (MySqlBackup mbi = new MySqlBackup(cmdi))
                {
                    cmdi.Connection = M_connexion.Gestion;
                    M_connexion.Gestion.Open();
                    mbi.ImportFromFile(filei);
                    M_connexion.Gestion.Close();
                }
            }
        }
        //Import database
        private void importDB_Btn_Click(object sender, EventArgs e)
        {
            String database = null;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Select directory to import SQL";
            ofd.Filter = "SQL Files (.sql)|*.sql";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                database = ofd.FileName;
            }

            String connStr = "Server=localhost; Port=3306; Uid=root; Pwd=admin;";
            MySqlConnection connection = new MySqlConnection(connStr);
            try
            {
                MySqlCommand cmd = new MySqlCommand();
                MySqlBackup backup = new MySqlBackup(cmd);
                cmd.Connection = connection;
                connection.Open();
                backup.ImportInfo.TargetDatabase = splitDir(database);
                backup.ImportInfo.DatabaseDefaultCharSet = "utf8";
                backup.ImportFromFile(database);
                MessageBox.Show("Backup has been imported");
            }
            catch (Exception)
            {
                if (database == null)
                {
                    MessageBox.Show("Please select a database to export");
                }
            }
            finally
            {
                if (connection == null)
                {
                    //Do nothing !
                }
                else if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    listBox1.Items.Clear();
                    showDBList();
                }
            }
        }
    protected void Button3_Click(object sender, EventArgs e)
    {
        Button1.Enabled = true;
        commit.Enabled = false;
        rollback.Enabled = false;
        GridView1.DataSource = null;
        GridView1.DataBind();
        msg.Text = "";
        //SqlConnection.ClearAllPools();
        switch (DropDownList1.SelectedItem.Text)
        {
            case "SQL Server":
                string s = "Data Source=localhost;Initial Catalog=master" + "; User ID=sa; Password=***;";
                SqlConnection ProcConn = new SqlConnection(s);

                try
                {
                    ProcConn.Open();
                    SqlCommand cmd = new SqlCommand("spCreateUserDb", ProcConn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(
                            new SqlParameter("@sourceDb", DropDownList2.SelectedItem.Text));
                    cmd.Parameters.Add(
                            new SqlParameter("@destDb", User.Identity.Name + DropDownList2.SelectedItem.Text));
                    cmd.ExecuteNonQuery();
                    //msg.Text += "Database Created: " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";

                }
                catch (Exception)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database "+ DropDownList2.Text + " creation failed');</script>"));
                }
                finally
                {
                    if (ProcConn != null)
                    {
                        ProcConn.Close();
                    }

                }
                break;
            case "Access":

                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                try
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
                    {
                        runspace.Open();
                        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                        Pipeline pipeline = runspace.CreatePipeline();
                        string scriptfile = "C:\\SourceDatabase\\Access\\powershellCreateDB.ps1";
                        //add a new script with arguments
                        Command myCommand = new Command(scriptfile);
                        CommandParameter SourceParam = new CommandParameter("source", DropDownList2.SelectedItem.Text);
                        CommandParameter TargetParam = new CommandParameter("target", User.Identity.Name);
                        myCommand.Parameters.Add(SourceParam);
                        myCommand.Parameters.Add(TargetParam);
                        pipeline.Commands.Add(myCommand);
                        // Execute PowerShell script; powershell should set-executionpolicy remotesigned.
                        // Otherwise Error: "File C:\SourceDatabase\Access\powershellCreateDB.ps1 cannot be loaded because running scripts is disabled on this system.
                        // For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170."
                        // error "AuthorizationManager check failed" caused by the version of 32bit or 64 bit, solution : resave it.
                        pipeline.Invoke();

                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    msg.Text = ex.Message;
                }
                break;
            case "MySQL":
                string str = "server=localhost;Database=" + DropDownList2.SelectedItem.Text + ";Uid=root;Pwd=***;";
                string file = "C:\\SourceDatabase\\MySQL\\" + DropDownList2.SelectedItem.Text + ".sql";
                try
                {
                    using (MySqlConnection conn = new MySqlConnection(str))
                    {
                        using (MySqlCommand cmd = new MySqlCommand())
                        {
                            cmd.CommandText = "DROP DATABASE IF EXISTS " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                            cmd.Connection = conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            using (MySqlBackup mb = new MySqlBackup(cmd))
                            {
                                //cmd.Connection = conn;
                                //conn.Open();
                                mb.ImportInfo.TargetDatabase = User.Identity.Name + DropDownList2.SelectedItem.Text;
                                mb.ImportFromFile(file);
                            }
                        }
                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    output.Text = ex.Message;
                }
                break;

            case "PostgreSQL":
                string ps = "Server=127.0.0.1;Port=5432;Database=template1;User Id=postgres; Password=***;Pooling=false;";
                try
                {
                    using (NpgsqlConnection conn = new NpgsqlConnection(ps))
                    {
                        using (NpgsqlCommand cmd = new NpgsqlCommand())
                        {
                            cmd.CommandText = "DROP DATABASE IF EXISTS " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                            cmd.Connection = conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            cmd.CommandText = "CREATE DATABASE " + User.Identity.Name + DropDownList2.SelectedItem.Text + " TEMPLATE " + DropDownList2.SelectedItem.Text;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    output.Text = ex.Message;
                }
                break;
            case "SQLite":
                RunspaceConfiguration SQLiterunspaceConfiguration = RunspaceConfiguration.Create();
                try
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(SQLiterunspaceConfiguration))
                    {
                        runspace.Open();
                        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                        Pipeline pipeline = runspace.CreatePipeline();
                        string scriptfile = "C:\\SourceDatabase\\SQLite\\powershellCreateDB.ps1";
                        //add a new script with arguments
                        Command myCommand = new Command(scriptfile);
                        CommandParameter SourceParam = new CommandParameter("source", DropDownList2.SelectedItem.Text);
                        CommandParameter TargetParam = new CommandParameter("target", User.Identity.Name);
                        myCommand.Parameters.Add(SourceParam);
                        myCommand.Parameters.Add(TargetParam);
                        pipeline.Commands.Add(myCommand);
                        // Execute PowerShell script; powershell should set-executionpolicy remotesigned.
                        // Otherwise Error: "File C:\SourceDatabase\Access\powershellCreateDB.ps1 cannot be loaded because running scripts is disabled on this system.
                        // For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170."
                        // error "AuthorizationManager check failed" caused by the version of 32bit or 64 bit, solution : resave it.
                        pipeline.Invoke();

                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    msg.Text = ex.Message;
                }
                break;
            case "Oracle":
            case "DB2":
                Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Error\\nDataBase already exists, no need to create.');</script>"));
                break;
            default:
                //msg.Text = "no such database";
                Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Error\\nPlease choose a database');</script>"));
                break;
        }
    }
        //this function will import from the user chosen file to the MySQL DB.
        /// <summary>
        /// Handles the Click event of the Import_button control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void Import_button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.DefaultExt = ".sql"; // Default file extension
            dialog.Filter = "SQL File (.sql)|*.sql";   // |Text documents (.txt)|*.txt| Filter files by extension

            // Show save file dialog box
            Nullable<bool> result = dialog.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                string Connectionstring = "Server=localhost; UId=root;Password=1234 ";
                string from = dialog.FileName;
                try
                {
                    using (MySqlConnection conn = new MySqlConnection(Connectionstring))
                        {
                            using (MySqlCommand cmd = new MySqlCommand())
                                {
                                        using (MySqlBackup mb = new MySqlBackup(cmd))
                                        {
                                            cmd.Connection = conn;
                                            conn.Open();
                                            MessageBox.Show(" מאגר הנתונים יעודכן מהקובץ הנבחר\n.בסיום התהליך תופיע הודעה\n.לחץ אישור להתחלת התהליך", "אנא לחץ אישור", MessageBoxButton.OK, MessageBoxImage.Information);
                                            mb.ImportFromFile(from);
                                            conn.Close();
                                            MessageBox.Show(".SQL - מאגר הנתונים עודכן מקובץ ה", "!הצלחה", MessageBoxButton.OK, MessageBoxImage.Information);
                                        }
                                }
                        }

                  }// end try
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    MessageBox.Show("SQL - התרחשה שגיאה בייבוא מקובץ ה", "!שים לב", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }