//FindGodMotherByID
 //returns the index of the GodMother with the passes id value
 //Input: the ID of the godmother and a list that contains the god mother
 //Output: the index of the godmother or -1 if not found
 //preconsitions: the list cotains only godmothers
 //postconditions: either the index of the god mother is returned or -1 signifying none found is returned
 public int FindGodMotherByID(int ID, ref List<FairyGodmother> GodMotherQueue)//this ID will have been retreived from the request form
 {
     SQL_Queries debugging = new SQL_Queries();
     int index = 0;
     foreach (FairyGodmother GodMother in GodMotherQueue)
     {
         if (GodMother.getFairyID() == ID) //Gets the Fairy Godmother ID.
         {
             //returns index if a Fairy Godmother is found. [A fairy Godmother was found.]
             return index;
         }
         index += 1;
     }
     return -1;//If this line occurs then something has gone wrong. [No Fairy Godmother was found.] 
 }
        private void pairButton_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection personalShopper =  psDGVPairing.SelectedRows;
            DataGridViewSelectedRowCollection cinderella = cinderellaDGVPairing.SelectedRows;
            if ((psDGVPairing.SelectedRows.Count != 1) || (cinderellaDGVPairing.SelectedRows.Count != 1))
            {
                MessageBox.Show("You must select someone.");
                return;
            }
            SQL_Queries dbMagic = new SQL_Queries();
            //bool isPaired = false;
            //string query = dbMagic.getCinderellaStats(Convert.ToInt32(cinderella[0].Cells[0].Value));

            if (dbMagic.CinderellaCurrentStatus(Convert.ToInt32(cinderella[0].Cells[0].Value)) == 3)
            {
                dbMagic.undoFGPairFromCinderellaID(Convert.ToInt32(cinderella[0].Cells[0].Value));
            }
            if (dbMagic.CinderellaCurrentStatus(Convert.ToInt32(cinderella[0].Cells[0].Value)) != 3)
            {
                dbMagic.setCinderellaStatus(cinderella[0].Cells[0].Value.ToString(), 3);
            }
            if (dbMagic.FGCurrentStatus(Convert.ToInt32(personalShopper[0].Cells[0].Value)) == 2)
            {
                dbMagic.undoCinderellaPairFromFGID(Convert.ToInt32(personalShopper[0].Cells[0].Value));
            }
            if (dbMagic.FGCurrentStatus(Convert.ToInt32(personalShopper[0].Cells[0].Value)) != 2)
            {
                dbMagic.setFGStatus(personalShopper[0].Cells[0].Value.ToString(), 2);
            }
            dbMagic.pairCinderella(Convert.ToInt32(cinderella[0].Cells[0].Value),Convert.ToInt32(personalShopper[0].Cells[0].Value));

            /*
            string query = dbMagic.getFgPaired(Convert.ToInt32(Convert.ToInt32(cinderella[0].Cells[0].Value)));
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

            SqlCommand command = new SqlCommand(query, conn);
            conn.Open();
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                if (reader.FieldCount < 1)
                {
                    break;
                }
            dbMagic.setFGStatus(reader.GetInt32(0).ToString(), 4);
            //Thread.Sleep(1000);
            }
            string query2 = dbMagic.getCinderellaPaired(Convert.ToInt32(personalShopper[0].Cells[0].Value));
            SqlCommand command2 = new SqlCommand(query2, conn);
            reader.Close();
            dbMagic.setFGStatus(personalShopper[0].Cells[0].Value.ToString(), 4);
            dbMagic.setCinderellaStatus(Convert.ToInt32(cinderella[0].Cells[0].Value).ToString(), 2);
            dbMagic.clearCinderellaFairyGodmotherID(Convert.ToInt32(cinderella[0].Cells[0].Value));
            //Thread.Sleep(1000);
            SqlDataReader reader2 = command2.ExecuteReader();
            while (reader2.Read())
            {
                if (reader2.FieldCount < 1)
                {
                    break;
                }
                int id = reader2.GetInt32(0);
                dbMagic.setCinderellaStatus(id.ToString(), 2);
                dbMagic.clearCinderellaFairyGodmotherID(id);
              //  Thread.Sleep(1000);
            }
            reader2.Close();
            dbMagic.pairCinderella(Convert.ToInt32(cinderella[0].Cells[0].Value), Convert.ToInt32(personalShopper[0].Cells[0].Value));
            dbMagic.setCinderellaStatus(cinderella[0].Cells[0].Value.ToString(), 3);
            dbMagic.setFGStatus(personalShopper[0].Cells[0].Value.ToString(), 2);
               // Thread.Sleep(1000);
            conn.Close();*/

            MessageBox.Show("Pairing Complete");
            guiupdate();
        }
        private void submitButton_Click(object sender, EventArgs e)
        {
            MessageLabel.Text = "";
            if ((passwordBox.Text == "") || (usernameBox.Text == ""))
            {
                MessageLabel.Text = "Both a username and a password are required.";
                return;
            }
            if (passwordBox.Text.Length > 25)//password too long - the DB stores up to 25 characters
            {
                MessageLabel.Text = "Max Password length is 25 characters.";
                return;
            }
            if (usernameBox.Text.Length > 25)//username too long max length in the database is 25 characters
            {
                MessageLabel.Text = "Max Username length is 25 characters.";
            }

            // Just a backdoor login so we can navigate the program.
            // I don't care how this is written just as long as it works correctly.
            if (usernameBox.Text == "test" && passwordBox.Text == "test")
            {
                Thread mainMenu = new Thread(() => Application.Run(new MainMenu()));
                mainMenu.Start();

                dbServer = dbServerBox.Text;
                dbPort = dbPortBox.Text;
                dbUsername = dbUsernameBox.Text;
                dbPassword = dbPasswordBox.Text;
                dbDatabase = dbDatabaseBox.Text;

                this.WindowState = FormWindowState.Minimized;
            }

            //Validating their login information with the database
            SQL_Queries login = new SQL_Queries();
            int role = login.validateLogin(usernameBox.Text, passwordBox.Text);

            switch (role)
            {
                case 0:     //Invalid Login
                    MessageBox.Show("Invalid Login");
                    break;

                case 1:     //Admin
                    Thread mainMenuThread = new Thread(() => Application.Run(new AdminMenu()));
                    mainMenuThread.SetApartmentState(ApartmentState.STA);
                    mainMenuThread.Start();
                    this.WindowState = FormWindowState.Minimized;
                    break;

                default:
                    MessageBox.Show("Unknown Error");
                    break;
            }
        }
        public void readCinderellas()
        {
            //Values for the progress bar.
            //int overallPercent = 0;
            //int percentCounter = 0;

            //Creates a new array of objects called particulars where the values for a row are stored for analysis.
            object[] particulars_C = new object[7];

            //The following object Value_C will be defined later.
            object Value_C;

            //Creates a new query to move data into the database.
            SQL_Queries Cinderella_Add = new SQL_Queries();

            //Creates an array of strings for errors.
            string[] errors = { "No Good_C" };

            //Creates a new open file dialogue box called FileToBeRead.
            OpenFileDialog fileToBeRead_C = new OpenFileDialog();

            //Opens a new instance of Excel.
            ExcelReader.Application intermediary_C = new ExcelReader.Application();

            //Additional filtering for FileToBeRead.
            fileToBeRead_C.Filter = "Worksheets (*.xls;*.xlsx;*.xlsb;*.xlsm) | *.xls; *.xlsx; *.xlsb; *.xlsm";
            fileToBeRead_C.Multiselect = false;
            DialogResult selection = fileToBeRead_C.ShowDialog();

            //This loop checks that the selected file is an existing Excel file.
            if (selection == DialogResult.OK)
            {

                //Checks to make sure file exists.
                if (!(System.IO.File.Exists(fileToBeRead_C.FileName)))
                {
                    MessageBox.Show("Error: File Not Found.");
                    return;
                }

                //Places the path of the file into a string.
                string Name_of_File = fileToBeRead_C.FileName;

                //Places the extension of a file into a string.
                string Extension_of_File_C = Path.GetExtension(Name_of_File);

                //Checks to make sure that file selected is an Excel file.
                if (Extension_of_File_C == ".xls")
                {

                }

                else if (Extension_of_File_C == ".xlsb")
                {

                }

                else if (Extension_of_File_C == ".xlsm")
                {

                }

                else if (Extension_of_File_C == ".xlsx")
                {

                }

                else
                {
                    MessageBox.Show("Error: Invalid file Type.");
                    return;
                }

                //closetBook will refer to the entire workbook selected to be read.
                ExcelReader.Workbook closetBook_C = intermediary_C.Workbooks.Open(fileToBeRead_C.FileName, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing, true);

                //closetSheet will refer to the data sheet where the Cinderellas's infomation is stored.
                ExcelReader.Worksheet closetSheet_C = closetBook_C.Worksheets.get_Item(1);

                //closetTuples refers to only the used range of cells in the Excel sheet.
                ExcelReader.Range closetTuples_C = closetSheet_C.UsedRange;

                //The integer index will refer to the number of a cell in a column that is currently being processd.
                int index = 0;

                //The following variables Date and Time will represent the Date and Time of an Appointment.
                DateTime Appointment_DateTime = new DateTime();
                string ApptD;
                string ApptT;

                int NumRows = closetTuples_C.Rows.Count;

                //This loop begins reading values into the database.
                for (int rows = 2; rows <= closetTuples_C.Rows.Count; rows++)
                {

                    //This loop begins to read values for each specific column.
                    for (int columns = 1; columns <= closetTuples_C.Columns.Count; columns++)
                    {

                        //The object Value_C is now assigned to be the value of a certain cell in the closetSheet Excel sheet.
                        Value_C = closetSheet_C.Cells[rows, columns].Value;

                        //The integer correctIndex is assigned to a cell with a special character that needs to be replaced.
                        int correctIndex;

                        //Checks the first column for any cells with special characters and if it finds one, corrects it.
                        if (columns == 1)
                        {

                            particulars_C[index] = Value_C.ToString().Trim();
                            if (particulars_C[index].ToString().Contains("'"))
                            {
                                correctIndex = particulars_C[index].ToString().IndexOf("'");

                                particulars_C[index] = particulars_C[index].ToString().Replace("'", "''");
                                Console.WriteLine(particulars_C[index].ToString());
                                closetSheet_C.Cells[rows, 1] = particulars_C[index];
                            }
                            index++;
                        }

                        //Checks the second column for any cells with special characters and if it finds one, corrects it.
                        else if (columns == 2)
                        {
                            particulars_C[index] = Value_C.ToString().Trim();
                            if (particulars_C[index].ToString().Contains("'"))
                            {
                                correctIndex = particulars_C[index].ToString().IndexOf("'");

                                particulars_C[index] = particulars_C[index].ToString().Replace("'", "''");
                                Console.WriteLine(particulars_C[index].ToString());
                                closetSheet_C.Cells[rows, 2] = particulars_C[index];
                            }
                            index++;
                        }

                        //Checks the third column for any cells with special characters and if it finds one, corrects it.
                        else if (columns == 3)
                        {
                            particulars_C[index] = Value_C.ToString().Trim();
                            if (particulars_C[index].ToString().Contains("'"))
                            {
                                correctIndex = particulars_C[index].ToString().IndexOf("'");

                                particulars_C[index] = particulars_C[index].ToString().Replace("'", "''");
                                Console.WriteLine(particulars_C[index].ToString());
                                closetSheet_C.Cells[rows, 3] = particulars_C[index];
                            }
                            index++;
                        }

                        //Checks the fourth column for any cells with special characters and if it finds one, corrects it.
                        else if (columns == 4)
                        {
                            particulars_C[index] = Value_C.ToString().Trim();
                            if (particulars_C[index].ToString().Contains("'"))
                            {
                                correctIndex = particulars_C[index].ToString().IndexOf("'");

                                particulars_C[index] = particulars_C[index].ToString().Replace("'", "''");
                                Console.WriteLine(particulars_C[index].ToString());
                                closetSheet_C.Cells[rows, 4] = particulars_C[index];
                            }
                            index++;
                        }

                        //Checks the fifth column for any cells with special characters and if it finds one, corrects it.
                        else if (columns == 5)
                        {
                            particulars_C[index] = Value_C.ToString().Trim();
                            if (particulars_C[index].ToString().Contains("'"))
                            {
                                correctIndex = particulars_C[index].ToString().IndexOf("'");

                                particulars_C[index] = particulars_C[index].ToString().Replace("'", "''");
                                Console.WriteLine(particulars_C[index].ToString());
                                closetSheet_C.Cells[rows, 5] = particulars_C[index];
                            }
                            index++;
                        }

                        //Formats the sixth column into the Date and Time columns.
                        else if (columns == 6)
                        {
                            particulars_C[index] = Value_C.ToString().Trim();
                            Appointment_DateTime = Convert.ToDateTime(Value_C);

                            ApptD = Appointment_DateTime.Date.ToString();
                            ApptT = Appointment_DateTime.TimeOfDay.ToString();

                            //Potentially Obsolete Code
                            //The Value for particulars[index] is then split into two strings at the ' '.
                            //These two strings are then placed into an array of strings called DateandTime
                            //string[] DateandTime = particulars_C[index].ToString().Trim().Split(' ');

                            //Potentially Obsolete Code
                            //The string DateandTime[0], which contains the appointment date, is now placed in the correct spots.
                            //Appointment_DateTime = Convert.ToDateTime(Value_C);

                            //Potentially Obsolete Code
                            /*Console.WriteLine(particulars_C[index].ToString());
                            closetSheet_C.Cells[rows, 6] = particulars_C[index];
                            index++;*/

                            //Potentially Obsolete Code
                            //The string DateandTime[1], which contains the appointment time, is now placed in the correct spots.
                            //Appointment_Time = Convert.ToDateTime(DateandTime[1]);

                            //Potentially Obsolete Code
                            /*Console.WriteLine(particulars_C[index].ToString());
                            closetSheet_C.Cells[rows, 7] = particulars_C[index];
                            index++;*/
                        }

                    }
                    index = 0;
                    ApptD = Appointment_DateTime.Date.ToString();
                    ApptT = Appointment_DateTime.TimeOfDay.ToString();

                    //The query will finally begin to add the data from the Excel sheet to the database.
                    Cinderella_Add.addCinderellaAndReferral(closetSheet_C.Cells[rows, 3].Value.ToString() + " " + closetSheet_C.Cells[rows, 4].Value.ToString(), closetSheet_C.Cells[rows, 5].Value.ToString(), closetSheet_C.Cells[rows, 1].Value.ToString(), closetSheet_C.Cells[rows, 2].Value.ToString(), ApptD, ApptT, "");

                    //Code for progress bar.

                }

                //Closes out of Excel.
                closetBook_C.Close(false, Type.Missing, Type.Missing);
                intermediary_C.Quit();
                Marshal.FinalReleaseComObject(intermediary_C);
                Marshal.FinalReleaseComObject(closetBook_C);
                Marshal.FinalReleaseComObject(closetSheet_C);
                Marshal.FinalReleaseComObject(closetTuples_C);
                GC.Collect();

                //Code for Pop up Window which tells when the import is completed.
                Import_Wait popup = new Import_Wait();
                DialogResult dialogresult = popup.ShowDialog();
                if (dialogresult == DialogResult.OK)
                {
                    popup.Dispose();
                }
            }
        }
        //readGodmothers
        //reads the excel file containing the godmother information into the db
        //Input: the excel file containg the godmother information
        //Output: godmother's have been added to the db
        //precondition: the godmother excel file is in the proper format and the db is connectable and is in a working state
        //postcondition: the godmother's have been correctly added to the db
        //IMPORTANT NOTE: Excel rows and columns start at the value 1.
        public void readGodmothers()
        {
            //Values for the progress bar.
            //int overallPercent = 0;
            //int percentCounter = 0;

            //Creates a new array of objects called particulars_G where the values for a row are stored for analysis.
            object[] particulars_G = new object[8];

            //This string is specifically for the use of analysing the Fairy Godmother Roles for a shift.
            string particulars_Shift;

            //An integer that represents a shift.
            int shiftID = 0;

            //An integer that represents a role.
            int roleID = 0;

            //The following object Value_C will be defined later.
            object Value_G;

            //Creates a new query to move data into the database.
            SQL_Queries Godmother_Add = new SQL_Queries();

            //Creates an array of strings for errors.
            string[] errors = { "No Good_G" };

            //Creates a new open file dialogue box called FileToBeRead.
            OpenFileDialog fileToBeRead_G = new OpenFileDialog();

            //Opens a new instance of Excel.
            ExcelReader.Application intermediary_G = new ExcelReader.Application();

            //Additional filtering for FileToBeRead.
            fileToBeRead_G.Filter = "Worksheets (*.xls;*.xlsx;*.xlsb;*.xlsm) | *.xls; *.xlsx; *.xlsb; *.xlsm";
            fileToBeRead_G.Multiselect = false;
            DialogResult selection = fileToBeRead_G.ShowDialog();

            //This loop checks that the selected file is an existing Excel file.
            if (selection == DialogResult.OK)
            {

                //Checks to make sure file exists.
                if (!(System.IO.File.Exists(fileToBeRead_G.FileName)))
                {
                    MessageBox.Show("Error: File Not Found.");
                    return;
                }

                //Places the path of the file into a string.
                string Name_of_File = fileToBeRead_G.FileName;

                //Places the extension of a file into a string.
                string Extension_of_File_G = Path.GetExtension(Name_of_File);

                //Checks to make sure that file selected is an Excel file.
                if (Extension_of_File_G == ".xls")
                {

                }

                else if (Extension_of_File_G == ".xlsb")
                {

                }

                else if (Extension_of_File_G == ".xlsm")
                {

                }

                else if (Extension_of_File_G == ".xlsx")
                {

                }

                else
                {
                    MessageBox.Show("Error: Invalid file Type.");
                    return;
                }

                //closetBook will refer to the entire workbook selected to be read.
                ExcelReader.Workbook closetBook_G = intermediary_G.Workbooks.Open(fileToBeRead_G.FileName, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing, true);

                //closetSheet will refer to the data sheet where the Cinderellas's infomation is stored.
                ExcelReader.Worksheet closetSheet_G = closetBook_G.Worksheets.get_Item(1);

                //closetTuples refers to only the used range of cells in the Excel sheet.
                ExcelReader.Range closetTuples_G = closetSheet_G.UsedRange;

                //The integer index will refer to the number of a cell in a column that is currently being processd.
                int index = 0;

                //This loop begins reading values into the database.
                for (int rows = 2; rows <= closetTuples_G.Rows.Count; rows++)
                {

                    //This loop begins to read values for each specific column.
                    //It stops at column 8 due to columns 9 through 11 being shift related.
                    for (int columns = 1; columns <= 8; columns++)
                    {

                        //The object Value_C is now assigned to be the value of a certain cell in the closetSheet Excel sheet.
                        Value_G = closetSheet_G.Cells[rows, columns].Value;

                        //The integer correctIndex is assigned to a cell with a special character that needs to be replaced.
                        int correctIndex;

                        //Checks the first column for any cells with special characters and if it finds one, corrects it.
                        if (columns == 1)
                        {
                            particulars_G[index] = Value_G.ToString().Trim();
                            if (particulars_G[index].ToString().Contains("'"))

                            {
                                correctIndex = particulars_G[index].ToString().IndexOf("'");

                                particulars_G[index] = particulars_G[index].ToString().Replace("'", "''");
                                Console.WriteLine(particulars_G[index].ToString());
                                closetSheet_G.Cells[rows, 1] = particulars_G[index];
                            }

                            index++;
                        }

                        //Checks the second column for any cells with special characters and if it finds one, corrects it.
                        else if (columns == 2)
                        {
                            particulars_G[index] = Value_G.ToString().Trim();
                            if (particulars_G[index].ToString().Contains("'"))
                            {
                                correctIndex = particulars_G[index].ToString().IndexOf("'");

                                particulars_G[index] = particulars_G[index].ToString().Replace("'", "''");
                                Console.WriteLine(particulars_G[index].ToString());
                                closetSheet_G.Cells[rows, 2] = particulars_G[index];
                            }
                            index++;
                        }

                        //Places the contents of third column in a string.
                        else if (columns == 3)
                        {
                            if (Value_G == null)
                            {

                            }
                            else
                            particulars_G[index] = Value_G.ToString().Trim();
                            index++;
                        }

                        //Places the contents of fourth column in a string.
                        else if (columns == 4)
                        {
                            if (Value_G == null)
                            {
                                Value_G = "NULL";
                                Console.WriteLine(Value_G.ToString());
                                closetSheet_G.Cells[rows, 4] = Value_G;
                            }

                            if (Value_G.ToString().Trim().Contains('(') || Value_G.ToString().Trim().Contains(')') || Value_G.ToString().Trim().Contains('-') || Value_G.ToString().Trim().Contains(' '))
                            {
                                Value_G = "NULL";
                                Console.WriteLine(Value_G.ToString());
                                closetSheet_G.Cells[rows, 4] = Value_G;
                            }

                            particulars_G[index] = Value_G.ToString().Trim();
                            index++;

                        }

                        //Places the contents of fifth column in a string.
                        else if (columns == 5)
                        {
                            if (Value_G == null)
                            {
                                Value_G = "NULL";
                                Console.WriteLine(Value_G.ToString());
                                closetSheet_G.Cells[rows, 5] = Value_G;
                            }

                            particulars_G[index] = Value_G.ToString().Trim();
                            index++;

                        }

                        //Places the contents of sixth column in a string.
                        else if (columns == 6)
                        {
                            if (Value_G == null)
                            {
                                Value_G = "NULL";
                                Console.WriteLine(Value_G.ToString());
                                closetSheet_G.Cells[rows, 6] = Value_G;
                            }

                            particulars_G[index] = Value_G.ToString().Trim();
                            index++;

                        }

                        //Places the contents of seventh column in a string.
                        else if (columns == 7)
                        {
                            if (Value_G == null)
                            {
                                Value_G = "NULL";
                                Console.WriteLine(Value_G.ToString());
                                closetSheet_G.Cells[rows, 7] = Value_G;
                            }

                            particulars_G[index] = Value_G.ToString().Trim();
                            index++;

                        }

                        //Places the contents of eigth column in a string.
                        else if (columns == 8)
                        {
                            if (Value_G == null)
                            {
                                Value_G = "NULL";
                                Console.WriteLine(Value_G.ToString());
                                closetSheet_G.Cells[rows, 8] = Value_G;
                            }

                            particulars_G[index] = Value_G.ToString().Trim();

                            string Value_to_Check = particulars_G[index].ToString();

                            string Value_to_Compare = "0";

                            if (Value_to_Check == Value_to_Compare)
                            {
                                Value_to_Check = "NULL";
                                particulars_G[index] = Value_to_Check;
                                Console.WriteLine(particulars_G[index].ToString());
                                closetSheet_G.Cells[rows, 8] = particulars_G[index];
                            }

                            index++;

                        }
                    }
                    index = 0;

                    //The query will finally begin to add the data from the Excel sheet to the database.
                    Godmother_Add.NewGodMother(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), closetSheet_G.Cells[rows, 5].Value.ToString(), closetSheet_G.Cells[rows, 6].Value.ToString(), closetSheet_G.Cells[rows, 3].Value.ToString(), closetSheet_G.Cells[rows, 4].Value.ToString(), closetSheet_G.Cells[rows, 7].Value.ToString(), closetSheet_G.Cells[rows, 8].Value.ToString());

                    //Code for progress bar.

                }

                //This loop begins reading values into the database for the Fairy Godmother shifts.
                for (int rows = 2; rows <= closetTuples_G.Rows.Count; rows++)
                {

                    //This loop begins to read values for each of the three shift columns.
                    //It begins at column 9 because the Shift information begins at column 9.
                    for (int columns = 9; columns <= closetTuples_G.Columns.Count; columns++)
                    {

                        //The object Value_G is now assigned to be the value of a certain cell in the closetSheet Excel sheet.
                        Value_G = closetSheet_G.Cells[rows, columns].Value;

                        //The integer correctIndex is assigned to a cell with a special character that needs to be replaced.
                        //int correctIndex;

                        //Places the contents of column 9 (the shift and role IDs) into the particulars_Shift object.
                        if (columns == 9)
                        {
                            shiftID = 1;
                            particulars_Shift = Value_G.ToString().Trim();
                            string CompareRoles = particulars_Shift;

                            //The following strings represent any possible value for the role columns.
                            string NotVolunteering = "Not Volunteering";
                            string NullString = "NULL";
                            string EmptyString = "";
                            string PersonalShopper = "Personal Shopper";
                            string Alterations = "Alterations";

                            if (CompareRoles == NotVolunteering || CompareRoles == NullString || CompareRoles == EmptyString || CompareRoles == null)
                            {
                                continue;
                            }

                            else if (CompareRoles == PersonalShopper)
                            {
                                roleID = 4;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                            else if (CompareRoles == Alterations)
                            {
                                roleID = 5;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                            else
                            {
                                roleID = 6;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                        }

                        //Places the contents of column 10 (the shift and role IDs) into the particulars_Shift object.
                        else if (columns == 10)
                        {
                            shiftID = 2;
                            particulars_Shift = Value_G.ToString().Trim();
                            string CompareRoles = particulars_Shift;

                            //The following strings represent any possible value for the role columns.
                            string NotVolunteering = "Not Volunteering";
                            string NullString = "NULL";
                            string EmptyString = "";
                            string PersonalShopper = "Personal Shopper";
                            string Alterations = "Alterations";

                            if (CompareRoles == NotVolunteering || CompareRoles == NullString || CompareRoles == EmptyString || CompareRoles == null)
                            {
                                continue;
                            }

                            else if (CompareRoles == PersonalShopper)
                            {
                                roleID = 4;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                            else if (CompareRoles == Alterations)
                            {
                                roleID = 5;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                            else
                            {
                                roleID = 6;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                        }

                        //Places the contents of column 9 (the shift and role IDs) into the particulars_Shift object.
                        else if (columns == 11)
                        {
                            shiftID = 3;
                            particulars_Shift = Value_G.ToString().Trim();
                            string CompareRoles = particulars_Shift;

                            //The following strings represent any possible value for the role columns.
                            string NotVolunteering = "Not Volunteering";
                            string NullString = "NULL";
                            string EmptyString = "";
                            string PersonalShopper = "Personal Shopper";
                            string Alterations = "Alterations";

                            if (CompareRoles == NotVolunteering || CompareRoles == NullString || CompareRoles == EmptyString || CompareRoles == null)
                            {
                                continue;
                            }

                            else if (CompareRoles == PersonalShopper)
                            {
                                roleID = 4;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                            else if (CompareRoles == Alterations)
                            {
                                roleID = 5;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                            else
                            {
                                roleID = 6;
                                Godmother_Add.newFGShiftWorker(closetSheet_G.Cells[rows, 1].Value.ToString(), closetSheet_G.Cells[rows, 2].Value.ToString(), shiftID, roleID);
                            }

                        }

                    }

                    //Code for progress bar.

                }

                //Code to close out
                closetBook_G.Close(false, Type.Missing, Type.Missing);
                intermediary_G.Quit();
                Marshal.FinalReleaseComObject(intermediary_G);
                Marshal.FinalReleaseComObject(closetBook_G);
                Marshal.FinalReleaseComObject(closetSheet_G);
                Marshal.FinalReleaseComObject(closetTuples_G);
                GC.Collect();

                //Code for Pop up Window which tells when the import is completed.
                Import_Wait popup = new Import_Wait();
                DialogResult dialogresult = popup.ShowDialog();
                if (dialogresult == DialogResult.OK)
                {
                    popup.Dispose();
                }
            }
        }
        private void submitButton_Click(object sender, EventArgs e)
        {
            try
            {

                string id = alterationsCinderellasDGV.SelectedRows[0].Cells[0].Value.ToString();

                // Only way I could find to do this, seems somewhat odd...
                DataRow selectedDataRow = ((DataRowView)alteratorsDropDownList.SelectedItem).Row;
                alterator = selectedDataRow["id"].ToString();

                int iZipper = Convert.ToInt32(zipper);
                int iBust = Convert.ToInt32(bust);
                int iDarts = Convert.ToInt32(darts);
                int iMending = Convert.ToInt32(mending);
                int iTakeIn = Convert.ToInt32(takeIn);
                int iHem = Convert.ToInt32(hem);
                int iStraps = Convert.ToInt32(straps);

                notes = notesTextBox.Text;
                SQL_Queries dbMagic = new SQL_Queries();
                string query = dbMagic.checkAlterations(id);
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

                SqlCommand command = new SqlCommand(query, conn);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();

                bool exists = false;
                int rowCount = 0;
                while (reader.Read())
                {

                    rowCount++;
                }

                if (rowCount == 1)
                {
                    dbMagic.updateAlterations(id, notes, iStraps, iDarts, iZipper, iMending, iTakeIn, iBust, iHem, alterator);
                }
                else
                {
                    dbMagic.addAlterations(id);
                }

                alterationsCinderellasDGV.ClearSelection();
                strapsCheckBox.Checked = false;
                zipperCheckBox.Checked = false;
                bustCheckBox.Checked = false;
                dartsCheckBox.Checked = false;
                generalMendingCheckBox.Checked = false;
                generalTakeInCheckBox.Checked = false;
                hemCheckBox.Checked = false;
                notesTextBox.Text = "";

                //refresh left gridview
                SqlCommand refreshCommandAlt = new SqlCommand(dbMagic.CinderellasInAlteration());
                alterationsCinderellasDGVBindingSource.EndEdit();
                alterationsCinderellasDGVDataTable.Clear();

                alterationsCinderellasDGVDataAdapter.SelectCommand = refreshCommandAlt;
                alterationsCinderellasDGVDataAdapter.SelectCommand.Connection = connection;

                alterationsCinderellasDGVDataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
                alterationsCinderellasDGVDataAdapter.Fill(alterationsCinderellasDGVDataTable);

                alterationsCinderellasDGV.Refresh();
                alterationsCinderellasDGV.ClearSelection();
                // alterationsCinderellasDGV.AutoResizeColumns();
            }

            catch (Exception error)
            {
                MessageBox.Show("Input not valid");
            }
        }
        //main
        //Purpose: to handle the database interactions and the loops that occur for matchmaking.
        //input: Only the database interactions.
        //Output: Updates are sent back to the database.
        //preconditions: this program is not being made anywhere and the database is functional.
        //postconditions: the database has been left in a consistent state, all matches have been updated to the database, and matchmaking is no longer running.
        static void Main()
        {
            try
            {
                //creates two lists to keep track of cinderellas and godmothers who have been matched.
                List<int> oldCinderellas = new List<int>();
                List<int> oldGodMothers = new List<int>();
                while (true)
                {
                    //creates lists to hold the cinderellas/godmothers pulled down from the database.
                    //theese will be "deleted" at the start of each loop
                    List<CinderellaClass> Cinderella = new List<CinderellaClass>();
                    List<FairyGodmother> GodMother = new List<FairyGodmother>();
                    //holds the unsorted cinderellas
                    List<CinderellaClass> UnsortCinderella = new List<CinderellaClass>();
                    //creates an object to do the matchmaking
                    Program match = new Program();
                    //gets the cinderellas from the db
                    match.GetCinderellas(ref UnsortCinderella, Cinderella.Count, ref oldCinderellas);
                    //gets the godmothers from the db
                    match.GetGodMothers(ref GodMother, GodMother.Count, ref oldGodMothers);

                    //list to hold the matchedcinderellas from the DB
                    List<CinderellaClass> MatchedCinderella = new List<CinderellaClass>();
                    match.GetPairedCinderellas(ref MatchedCinderella); //get the matched cinderellas inorder to refreash the screen

                    List<FairyGodmother> MatchedGodMother = new List<FairyGodmother>();//get the cinderellas that have been matched from the DB
                    match.GetPairedGodMother(ref MatchedGodMother, ref MatchedCinderella);//show the godmother that has been matched to the cinderella
                    MatchMakingLogic Logic = new MatchMakingLogic();

                    int Cinderellacount = UnsortCinderella.Count;//loop control variable

                    //gets the difference between check-in and appointment time
                    foreach (CinderellaClass cinder in UnsortCinderella)
                    {
                        cinder.diffFromappTime = match.EarlyLateTime(cinder.appTime);
                    }

                    //sorts the cinderellas based on the difference between checkin and appointment time

                    Cinderella = match.SortCinderellas(ref UnsortCinderella);

                    for (int i = 0; i < Cinderellacount; i++)//makes the matches
                    {
                        Logic.MakeMatch(ref Cinderella, ref GodMother, ref MatchedCinderella, ref MatchedGodMother);
                    }
                    //create lists to hold the matched ids of the cinderellas and the god mothers
                    List<int> MatchedCinderellaID = new List<int>();
                    List<int> MatchedGodMotherID = new List<int>();
                    //fill each of the lists
                    foreach (CinderellaClass Cinder in MatchedCinderella)
                    {
                        MatchedCinderellaID.Add(Cinder.getCinderellaID());
                    }
                    foreach (FairyGodmother PersonalShopper in MatchedGodMother)
                    {
                        MatchedGodMotherID.Add(PersonalShopper.getFairyID());
                    }
                    if ((MatchedCinderellaID.Count > 0) && (MatchedGodMotherID.Count > 0))
                    {//update the matches to the database.
                        SQL_Queries queries = new SQL_Queries();
                        //loops through all the matches nd make the appropiate DB action
                        for (int i = 0; i < MatchedCinderellaID.Count; i++)
                        {
                            if (queries.FGCurrentStatus(MatchedGodMotherID[i]) == 4)
                            {
                                //update the list of cinderellas taht ahve been through matchmaking
                                oldCinderellas.Add(MatchedCinderellaID[i]);

                                //pair the cinderellas
                                queries.pairCinderella(MatchedCinderellaID[i], MatchedGodMotherID[i]);
                                //set the status of the cinderella and the fairy god mother
                                if (queries.CinderellaCurrentStatus(MatchedCinderellaID[i]) != 3)
                                {
                                    queries.setCinderellaStatus(MatchedCinderellaID[i].ToString(), 3);
                                }
                                if (queries.FGCurrentStatus(MatchedGodMotherID[i]) != 2)
                                {
                                    queries.setFGStatus(MatchedGodMotherID[i].ToString(), 2);
                                }
                            }

                        }
                    }
                    //clear the lists of ID's
                    MatchedGodMotherID.Clear();
                    MatchedCinderellaID.Clear();
                    //pause execution for 5 seconds
                    Thread.Sleep(5000);
                }

            }
            catch (Exception e)
            {
                //a last hope in order to possibly work around random crashes.
                Thread bug = new Thread(() => Main());
                bug.Start();
            }
        }