Subversion Repositories Code-Repo

Rev

Rev 11 | Blame | Compare with Previous | Last modification | View Log | RSS feed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;

namespace SWAT_Office_App
{
    class Reimage_USB_Drives
    {
        public static List<string> allSwatUSBDrivesx32 = new List<string>();
        public static List<string> allSwatUSBDrivesx64 = new List<string>();
        public static BackgroundWorker bwThread = null;
        public static Reimage_USB_Drive_Progress_Form progressForm = null;
        public static List<BackgroundWorker> backgroundWorkerList = new List<BackgroundWorker>();
        public static bool threadsRunning = false;
        private static bool allThreadsCompleted = false;
        private static bool threadsCancelled = false;
        private static DateTime startTime;
        private static DateTime endTime;
        public static void getDriveLetters()
        {
            allSwatUSBDrivesx32.Clear();
            allSwatUSBDrivesx64.Clear();
            backgroundWorkerList.Clear();
            string pathToSWATDrive;
            // Pulls information from all drives on the running computer
            DriveInfo[] allDrives = DriveInfo.GetDrives();
            // Looks for a drive with the correct label, updates pathToSWATDrive with the drive letter
            foreach (DriveInfo drive in allDrives)
            {
                if (drive.IsReady == true)
                {
                    // Drive label for the USB drives is set here.
                    if (drive.VolumeLabel.ToUpper() == "SWAT DRIVE X32" && drive.DriveType == DriveType.Removable)
                    {
                        pathToSWATDrive = drive.Name;
                        allSwatUSBDrivesx32.Add(pathToSWATDrive);
                    }
                    if (drive.VolumeLabel.ToUpper() == "SWAT DRIVE X64" && drive.DriveType == DriveType.Removable)
                    {
                        pathToSWATDrive = drive.Name;
                        allSwatUSBDrivesx64.Add(pathToSWATDrive);
                    }
                }
            }
            // Prompts for drive to be inserted
            if ((allSwatUSBDrivesx32.Count == 0) && (allSwatUSBDrivesx64.Count == 0))
            {
                DialogResult result;
                result = MessageBox.Show("Unable to locate any SWAT USB drives.", "Error");
            }
        }
        public static void reimageUSBDrives()
        {
            try
            {
                if (Settings_Form.defaultSettings == false)
                {
                    if ((File.Exists(Settings_Form.usbMasterx32CopyLocation + "\\boot\\bootsect.exe")) &&
                        (File.Exists(Settings_Form.usbMasterx64CopyLocation + "\\boot\\bootsect.exe")))
                    {
                        startTime = DateTime.Now;
                        getDriveLetters();
                        if ((allSwatUSBDrivesx32.Count != 0) || (allSwatUSBDrivesx64.Count != 0))
                        {
                            threadsRunning = true;
                            bwThread = new BackgroundWorker();
                            bwThread.WorkerSupportsCancellation = true;
                            bwThread.DoWork += new DoWorkEventHandler(bwThread_DoWork);
                            bwThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwThread_RunWorkerCompleted);
                            bwThread.RunWorkerAsync();
                            progressForm = new Reimage_USB_Drive_Progress_Form();
                            progressForm.Show(); 
                        }
                    }
                    else
                    {
                        MessageBox.Show("bootsect.exe is missing from the master image location");
                    }
                }
                else
                {
                    MessageBox.Show("Settings have not been changed yet.\nPlease verify settings before continuing.", "Warning!");
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        private static void bwThread_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                //Reimage_USB_Drives.wipeUSBDrives(worker, e);
                Thread.Sleep(1000);
                // Reformats all SWAT USB Drives
                foreach (string drive in allSwatUSBDrivesx32)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    progressForm.updateStatus("Reformatting Drive " + drive);
                    Process proc = new Process();
                    proc.StartInfo.FileName = "DISKPART";
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.RedirectStandardInput = true;
                    proc.StartInfo.CreateNoWindow = true;
                    proc.Start();

                    StreamWriter procInput = proc.StandardInput;
                    procInput.WriteLine("SELECT VOLUME=" + drive);
                    procInput.WriteLine("FORMAT FS=NTFS LABEL=\"SWAT Drive x32\" QUICK");
                    procInput.WriteLine("EXIT");
                    proc.WaitForExit();
                }
                foreach (string drive in allSwatUSBDrivesx64)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    progressForm.updateStatus("Reformatting Drive " + drive);
                    Process proc = new Process();
                    proc.StartInfo.FileName = "DISKPART";
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.RedirectStandardInput = true;
                    proc.StartInfo.CreateNoWindow = true;
                    proc.Start();

                    StreamWriter procInput = proc.StandardInput;
                    procInput.WriteLine("SELECT VOLUME=" + drive);
                    procInput.WriteLine("FORMAT FS=NTFS LABEL=\"SWAT Drive x64\" QUICK");
                    procInput.WriteLine("EXIT");
                    proc.WaitForExit();
                }
                getDriveLetters();

                //Reimage_USB_Drives.callBootsect();

                // Runs bootsect.exe on each drive to install the bootloader
                foreach (string drive in allSwatUSBDrivesx32)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    progressForm.updateStatus("Writing Bootsector on Drive " + drive);
                    Process proc = new Process();
                    proc.StartInfo.FileName = Settings_Form.usbMasterx32CopyLocation + "\\boot\\bootsect.exe";
                    proc.StartInfo.Arguments = "/NT60 " + drive.Substring(0, 2) + " /FORCE";
                    proc.Start();
                    proc.WaitForExit();
                }
                foreach (string drive in allSwatUSBDrivesx64)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    progressForm.updateStatus("Writing Bootsector on Drive " + drive);
                    Process proc = new Process();
                    proc.StartInfo.FileName = Settings_Form.usbMasterx32CopyLocation + "\\boot\\bootsect.exe";
                    proc.StartInfo.Arguments = "/NT60 " + drive.Substring(0, 2) + " /FORCE";
                    proc.Start();
                    proc.WaitForExit();
                }

                //Reimage_USB_Drives.copyMasterImage();

                // Copies the master image to each USB Drive
                foreach (string drive in allSwatUSBDrivesx32)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    BackgroundWorker fileCopyThread = new BackgroundWorker();
                    backgroundWorkerList.Add(fileCopyThread);
                    fileCopyThread.WorkerSupportsCancellation = true;
                    fileCopyThread.DoWork += new DoWorkEventHandler(fileCopyThread32_DoWork);
                    fileCopyThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(fileCopyThread_RunWorkerCompleted);
                    fileCopyThread.RunWorkerAsync(drive);
                    //DirectoryCopy(Settings_Form.usbMasterx32CopyLocation, drive, true, worker, e);
                }
                foreach (string drive in allSwatUSBDrivesx64)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    BackgroundWorker fileCopyThread = new BackgroundWorker();
                    backgroundWorkerList.Add(fileCopyThread);
                    fileCopyThread.WorkerSupportsCancellation = true;
                    fileCopyThread.DoWork += new DoWorkEventHandler(fileCopyThread64_DoWork);
                    fileCopyThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(fileCopyThread_RunWorkerCompleted);
                    fileCopyThread.RunWorkerAsync(drive);
                    //DirectoryCopy(Settings_Form.usbMasterx64CopyLocation, drive, true, worker, e);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        static void fileCopyThread32_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string drive = (string)e.Argument;
            DirectoryCopy(Settings_Form.usbMasterx32CopyLocation, drive, true, worker, e);
            progressForm.updateStatus("Finished Copying Files to " + drive);
        }
        static void fileCopyThread64_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string drive = (string)e.Argument;
            DirectoryCopy(Settings_Form.usbMasterx64CopyLocation, drive, true, worker, e);
            progressForm.updateStatus("Finished Copying Files to " + drive);
        }
        static void fileCopyThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                threadsCancelled = true;
                bool threadsStillRunning = false;
                foreach (BackgroundWorker bw in backgroundWorkerList)
                {
                    if (bw.IsBusy)
                        threadsStillRunning = true;
                }
                if (threadsStillRunning)
                    allThreadsCompleted = false;
                else
                    allThreadsCompleted = true;
            }
            else
            {
                bool threadsStillRunning = false;
                foreach (BackgroundWorker bw in backgroundWorkerList)
                {
                    if (bw.IsBusy)
                        threadsStillRunning = true;
                }
                if (threadsStillRunning)
                    allThreadsCompleted = false;
                else
                    allThreadsCompleted = true;
            }
            if (threadsCancelled)
            {
                threadsRunning = false;
                MessageBox.Show("File Copy Operation Cancelled");
                progressForm.closeForm();
            }
            else if (allThreadsCompleted)
            {
                threadsRunning = false;
                endTime = DateTime.Now;
                MessageBox.Show("Operation was started at " + startTime.ToShortTimeString() + " and ended successfully at " + endTime.ToShortTimeString());
                progressForm.closeForm();
            }
        }
        private static void bwThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                threadsRunning = false;
                MessageBox.Show("Operation was canceled");
                progressForm.Close();
            }
        }
        private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, BackgroundWorker worker, DoWorkEventArgs e)
        {
            try
            {
                progressForm.updateStatus("Copying Files to " + destDirName);
                DirectoryInfo dir = new DirectoryInfo(sourceDirName);
                DirectoryInfo[] dirs = dir.GetDirectories();

                // If the destination directory does not exist, create it.
                if (!Directory.Exists(destDirName))
                {
                    Directory.CreateDirectory(destDirName);
                }
                // Get the file contents of the directory to copy.
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    // Create the path to the new copy of the file.
                    string tempPath = Path.Combine(destDirName, file.Name);
                    // Copy the file.
                    file.CopyTo(tempPath, false);
                }
                // If copySubDirs is true, copy the subdirectories.
                if (copySubDirs)
                {
                    foreach (DirectoryInfo subdir in dirs)
                    {
                        if (worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }
                        // Create the subdirectory.
                        string tempPath = Path.Combine(destDirName, subdir.Name);
                        // Copy the subdirectories.
                        DirectoryCopy(subdir.FullName, tempPath, copySubDirs, worker, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}