0

Goal:

My goal is to create a MySQL query using C#, and on successful query I'd like to use File.Copy... and vice versa.

This is my current code:

//Try run code
try
{
    //Add record to MySQL
    using (var conn = new MySqlConnection(ConnectionString.ConnString))
    {
        using (var cmd = new MySqlCommand("INSERT INTO files (document_name, path, version, section, user_modified, date_modified)" +
                                        " values (@doc, @path, @version, @section, @user, NOW());", conn))
        {
            conn.Open();
            cmd.Parameters.AddWithValue("@doc", docName.Text);
            cmd.Parameters.AddWithValue("@path", $"{finalPath}Section {Section.Text}\\{docName.Text}{Path.GetExtension(fileName)}");
            cmd.Parameters.AddWithValue("@version", versionNumber.Text);
            cmd.Parameters.AddWithValue("@section", Section.Text);
            cmd.Parameters.AddWithValue("@user", UserDetails.userId);
            cmd.ExecuteNonQuery();
        }

    }

    //Copy file into new directory
    File.Copy(fileName, $"{finalPath}Section {Section.Text}\\{docName.Text}{Path.GetExtension(fileName)}");
}

catch (Exception ex)
{
    MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
}

Question:

What is a good method to achieve the following..

  • If MySQL query not successful then do not do anything and stop and return to where the error was.
  • If MySQL query was successful and File.Copy wasn't (Ran into an error for any reason) - then recover the query, delete whatever was inserted and go back all the way to step one.

How can this be achieved?

Edit 10/06/2020

I have managed to get the following code :

 //Try run MySQL query with roll back function if failed.
        public void RunTransaction(string myConnString)
        {
            MySqlConnection myConnection = new MySqlConnection(ConnectionString.ConnString);
            myConnection.Open();

            MySqlCommand myCommand = myConnection.CreateCommand();
            MySqlTransaction myTrans;

            // Start a local transaction
            myTrans = myConnection.BeginTransaction();
            // Must assign both transaction object and connection
            // to Command object for a pending local transaction
            myCommand.Connection = myConnection;
            myCommand.Transaction = myTrans;

            try
            {
                myCommand.CommandText = "INSERT INTO files (document_name, path, version, section, user_modified, date_modified, review_date)" +
                                        " values (@doc, @path, @version, @section, @user, NOW(), NOW() + interval 12 month);";
                myCommand.Parameters.AddWithValue("@doc", docName.Text);
                myCommand.Parameters.AddWithValue("@path", $"{finalPath}Section {Section.Text}\\{docName.Text}{Path.GetExtension(fileName)}");
                myCommand.Parameters.AddWithValue("@version", versionNumber.Text);
                myCommand.Parameters.AddWithValue("@section", Section.Text);
                myCommand.Parameters.AddWithValue("@user", UserDetails.userId);
                myCommand.ExecuteNonQuery();
                myTrans.Commit();
            }
            catch (Exception e)
            {
                try
                {
                    myTrans.Rollback();
                }
                catch (MySqlException ex)
                {
                    if (myTrans.Connection != null)
                    {
                        Console.WriteLine("An exception of type " + ex.GetType() +
                        " was encountered while attempting to roll back the transaction.");
                    }
                }

                Console.WriteLine("An exception of type " + e.GetType() +
                " was encountered while inserting the data.");
                Console.WriteLine("Neither record was written to database.");
            }
            finally
            {
                myConnection.Close();
            }
        }

Question..

How would I then implement the File.Copy function to suit my goal?

I have this source.. https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo.copyto?view=netcore-3.1

but not sure where to code in my current code?

  • the easiest solution is just to await for FileCopying and then insert record to db – sTrenat Jun 09 '20 at 15:02
  • @sTrenat something like this you mean?... https://stackoverflow.com/questions/882686/asynchronous-file-copy-move-in-c-sharp – HowdyCowboy Jun 09 '20 at 15:06
  • if not, then put Sql Insertion and FileCopying into separate classes, write some transactionInterface that both classes implement with methods like Commit and Rollback, Both classes should have some transaction manager which will try to call commit on all of these, and if fail then manager will try to rollback both – sTrenat Jun 09 '20 at 15:07
  • @sTrenat See my edited question. Is that what you meant? – HowdyCowboy Jun 10 '20 at 08:02

0 Answers0