Advertisement
Guest User

Code Review

a guest
Feb 25th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 15.17 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using System.Threading;
  6. using System.Windows.Forms;
  7.  
  8. namespace PublishForQA
  9. {
  10.     public partial class FormProgressBar : Form
  11.     {
  12.         static FormPublisher formPublisher = (FormPublisher)Form.ActiveForm;
  13.         static FormProgressBar formProgressBar;
  14.         static List<TextBox> debugTextBoxes = formPublisher.DebugTextBoxesList;
  15.         static BackgroundWorker backgroundWorker = new BackgroundWorker();
  16.         static DoWorkEventArgs WorkArgs;
  17.         static int TotalOperationsCount;
  18.         static int CurrentOpeartionCount;
  19.  
  20.         public FormProgressBar()
  21.         {
  22.             TotalOperationsCount = 0;
  23.             CurrentOpeartionCount = 0;
  24.             InitializeComponent();
  25.             formProgressBar = this;
  26.             backgroundWorker.DoWork += backgroundWorker_DoWork;
  27.             backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
  28.             backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
  29.             backgroundWorker.WorkerReportsProgress = true;
  30.             backgroundWorker.WorkerSupportsCancellation = true;
  31.             backgroundWorker.RunWorkerAsync();
  32.         }
  33.  
  34.         private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  35.         {
  36.             WorkArgs = e;
  37.             pbMain.Maximum = GetOperationsCount();
  38.             CopyFilesAndDirectories();
  39.         }
  40.  
  41.         private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
  42.         {
  43.             pbMain.Value = e.ProgressPercentage;
  44.         }
  45.  
  46.         private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  47.         {
  48.             if (e.Error != null)
  49.             {
  50.                 MessageBox.Show("An error occurred during copying:" + Environment.NewLine + e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  51.                 Cleanup();
  52.             }
  53.             else if (e.Cancelled)
  54.             {
  55.                 MessageBox.Show("Copy operation aborted.", "Abort", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  56.                 Cleanup();
  57.             }
  58.             else
  59.             {
  60.                 MessageBox.Show("Copy operation completed successfully!", "Operation success", MessageBoxButtons.OK, MessageBoxIcon.Information);
  61.                 Cleanup();
  62.             }
  63.         }
  64.  
  65.         private void btnCancel_Click(object sender, EventArgs e)
  66.         {
  67.             backgroundWorker.CancelAsync();
  68.         }
  69.  
  70.         /// <summary>
  71.         /// Checks if "CancellationPending" is true and if it is aborts the thread and sets
  72.         /// the DoWorkEventArgs's Cancel property to true.
  73.         /// </summary>
  74.         static void CheckForCancel()
  75.         {
  76.             if (backgroundWorker.CancellationPending)
  77.             {
  78.                 WorkArgs.Cancel = true;
  79.                 Thread.CurrentThread.Abort();
  80.             }
  81.         }
  82.  
  83.         /// <summary>
  84.         /// Marks the BackgroundWorker to be disposed and closes the progress bar form.
  85.         /// </summary>
  86.         static void Cleanup()
  87.         {
  88.             backgroundWorker.Dispose();
  89.             formProgressBar.Close();
  90.         }
  91.  
  92.         /// <summary>
  93.         /// Counts all the directories that need to be created and all the
  94.         /// files that need to be copied from each designated folder.
  95.         /// </summary>
  96.         /// <returns></returns>
  97.         public static int GetOperationsCount()
  98.         {
  99.             formProgressBar.lblCurrentOperation.Text = "Counting the total number of operations...";
  100.             foreach (var tb in debugTextBoxes)
  101.             {
  102.                 CheckForCancel();
  103.                 TotalOperationsCount += Directory.GetFiles(tb.Text, "*", SearchOption.AllDirectories).Length;
  104.                 CheckForCancel();
  105.                 TotalOperationsCount += Directory.GetDirectories(tb.Text, "*", SearchOption.AllDirectories).Length;
  106.                 formProgressBar.lblCurrentPath.Text = tb.Text;
  107.             }
  108.  
  109.             return TotalOperationsCount;
  110.         }
  111.  
  112.         /// <summary>
  113.         /// Recreates the directory structure at the target location and copies all files from the source recursively.
  114.         /// </summary>
  115.         public static void CopyFilesAndDirectories()
  116.         {
  117.             foreach (var tb in debugTextBoxes)
  118.             {
  119.                 CheckForCancel();
  120.                 //If there is a task name provided we add a backslash, otherwise the QA Folder path's
  121.                 //last backslash will suffice.
  122.                 string destinationPath = formPublisher.tbQAFolderPath.Text + ((formPublisher.tbTaskName.Text.Length > 0) ? formPublisher.tbTaskName.Text + "\\" : string.Empty);
  123.  
  124.                 //We set the name of the destination folder, depending
  125.                 //on the TextBox we are iterating over.
  126.                 switch (tb.Name)
  127.                 {
  128.                     case "tbECheckPath":
  129.                         destinationPath += "E-Check\\";
  130.                         break;
  131.                     case "tbCorePath":
  132.                         destinationPath += "E-CheckCore\\";
  133.                         break;
  134.                     case "tbServicePath":
  135.                         destinationPath += "E-CheckService\\";
  136.                         break;
  137.                     default:
  138.                         break;
  139.                 }
  140.  
  141.                 if (!CreateDirectoryStructure(tb.Text, destinationPath)) return;
  142.                 if (!CopyFiles(tb.Text, destinationPath)) return;
  143.             }
  144.         }
  145.  
  146.         /// <summary>
  147.         /// Gets all the directories in a target path and recreates the same
  148.         /// directory structure in the destination path.
  149.         /// </summary>
  150.         /// <param name="sourcePath">The path from which to read the directory structure.</param>
  151.         /// <param name="destinationPath">The path where to recreate the directory structure.</param>
  152.         /// <returns>"True" if the operation was successful, "false" if an exception was raised.</returns>
  153.         public static bool CreateDirectoryStructure(string sourcePath, string destinationPath)
  154.         {
  155.             formProgressBar.lblCurrentOperation.Text = "Creating directory structure...";
  156.             //These variables will hold the current source and target path of the "for" iteration.
  157.             //They will be used to show more information in the exception catching.
  158.             string sourceDir = FormPublisher.ErrorBeforeDirectoryLoop;
  159.             string targetDir = FormPublisher.ErrorBeforeDirectoryLoop;
  160.             try
  161.             {
  162.                 //First we create the directory structure.
  163.                 Directory.CreateDirectory(destinationPath);
  164.                 foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
  165.                 {
  166.                     CheckForCancel();
  167.                     sourceDir = dirPath;
  168.                     targetDir = dirPath.Replace(sourcePath, destinationPath);
  169.                     formProgressBar.lblCurrentPath.Text = targetDir;
  170.                     Directory.CreateDirectory(targetDir);
  171.                     CurrentOpeartionCount++;
  172.                     backgroundWorker.ReportProgress(CurrentOpeartionCount);
  173.                 }
  174.                 return true;
  175.             }
  176.             #region catch block
  177.             catch (UnauthorizedAccessException ex)
  178.             {
  179.                 MessageBox.Show(ExceptionMessageBuilder.Directory("The caller does not have the required permission for \"" + targetDir + "\".", sourceDir, targetDir, ex), "Unauthorized Access Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  180.                 return false;
  181.             }
  182.             catch (ArgumentNullException ex)
  183.             {
  184.                 MessageBox.Show(ExceptionMessageBuilder.Directory("The path passed for directory creation is null.", sourceDir, targetDir, ex), "Argument Null Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  185.                 return false;
  186.             }
  187.             catch (ArgumentException ex)
  188.             {
  189.                 MessageBox.Show(ExceptionMessageBuilder.Directory("The path passed for directory creation is invalid.", sourceDir, targetDir, ex), "Argument Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  190.                 return false;
  191.             }
  192.             catch (PathTooLongException ex)
  193.             {
  194.                 MessageBox.Show(ExceptionMessageBuilder.Directory("Cannot create target directory, path is too long.", sourceDir, targetDir, ex), "Path Too Long Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  195.                 return false;
  196.             }
  197.             catch (DirectoryNotFoundException ex)
  198.             {
  199.                 MessageBox.Show(ExceptionMessageBuilder.Directory("The path passed for directory creation could not be found.", sourceDir, targetDir, ex), "Directory Not Found Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  200.                 return false;
  201.             }
  202.             catch (IOException ex)
  203.             {
  204.                 //IO Exception can be either the passed path is a file or the network name is not known.
  205.                 //Since we have previous checks in place to make sure the path is a directory,
  206.                 //the second possible error is shown.
  207.                 MessageBox.Show(ExceptionMessageBuilder.Directory("The network name is not known.", sourceDir, targetDir, ex), "IO Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  208.                 return false;
  209.             }
  210.             catch (NotSupportedException ex)
  211.             {
  212.                 MessageBox.Show(ExceptionMessageBuilder.Directory("The path passed contains an illegal colon character.", sourceDir, targetDir, ex), "Not Supported Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  213.                 return false;
  214.             }
  215.             catch (ThreadAbortException)
  216.             {
  217.                 Thread.ResetAbort();
  218.                 return false;
  219.             }
  220.             catch (Exception ex)
  221.             {
  222.                 MessageBox.Show(ExceptionMessageBuilder.Directory("Unexpected exception occurred:" + Environment.NewLine + ex.Message, sourceDir, targetDir, ex), "Unexpected Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  223.                 return false;
  224.             }
  225.             #endregion
  226.         }
  227.  
  228.         /// <summary>
  229.         /// Copies all files from the target path to the destination path,
  230.         /// overriding any existing ones.
  231.         /// </summary>
  232.         /// <param name="sourcePath">The path from which to copy all the files.</param>
  233.         /// <param name="destinationPath">The path where to copy all the files.</param>
  234.         /// <returns>"True" if the operation was successful, "false" if an exception was raised.</returns>
  235.         public static bool CopyFiles(string sourcePath, string destinationPath)
  236.         {
  237.             formProgressBar.lblCurrentOperation.Text = "Copying files...";
  238.             //These variables will hold the current source and target path of the "for" iteration.
  239.             //They will be used to show more information in the exception catching.
  240.             //But first they are set to the string used to indicate an error before the loop.
  241.             string sourceFile = FormPublisher.ErrorBeforeFileLoop;
  242.             string targetFileDir = FormPublisher.ErrorBeforeFileLoop;
  243.             try
  244.             {
  245.                 //We copy all files, overwriting any existing ones.
  246.                 foreach (string filePath in Directory.GetFiles(sourcePath, "*", SearchOption.AllDirectories))
  247.                 {
  248.                     CheckForCancel();
  249.                     sourceFile = filePath;
  250.                     targetFileDir = filePath.Replace(sourcePath, destinationPath);
  251.                     formProgressBar.lblCurrentPath.Text = filePath;
  252.                     File.Copy(filePath, targetFileDir, true);
  253.                     CurrentOpeartionCount++;
  254.                     backgroundWorker.ReportProgress(CurrentOpeartionCount);
  255.                 }
  256.                 return true;
  257.             }
  258.             #region catch block
  259.             catch (UnauthorizedAccessException ex)
  260.             {
  261.                 MessageBox.Show(ExceptionMessageBuilder.File("The caller does not have the required permission for \"" + targetFileDir + "\".", sourceFile, targetFileDir, ex), "Unauthorized Access Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  262.                 return false;
  263.             }
  264.             catch (ArgumentNullException ex)
  265.             {
  266.                 MessageBox.Show(ExceptionMessageBuilder.File("Either the source or destination file paths are null.", sourceFile, targetFileDir, ex), "Argument Null Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  267.                 return false;
  268.             }
  269.             catch (ArgumentException ex)
  270.             {
  271.                 MessageBox.Show(ExceptionMessageBuilder.File("Either the source or destination file paths are invalid.", sourceFile, targetFileDir, ex), "Argument Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  272.                 return false;
  273.             }
  274.             catch (PathTooLongException ex)
  275.             {
  276.                 MessageBox.Show(ExceptionMessageBuilder.File("Either the source or destination file paths are too long.", sourceFile, targetFileDir, ex), "Path Too Long Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  277.                 return false;
  278.             }
  279.             catch (DirectoryNotFoundException ex)
  280.             {
  281.                 MessageBox.Show(ExceptionMessageBuilder.File("Either the source or destination file paths could not be found.", sourceFile, targetFileDir, ex), "Directory Not Found Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  282.                 return false;
  283.             }
  284.             catch (NotSupportedException ex)
  285.             {
  286.                 MessageBox.Show(ExceptionMessageBuilder.File("Either the source or destination file paths are invalid.", sourceFile, targetFileDir, ex), "Not Supported Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  287.                 return false;
  288.             }
  289.             catch (FileNotFoundException ex)
  290.             {
  291.                 MessageBox.Show(ExceptionMessageBuilder.File("\"" + sourceFile + "\" was not found.", sourceFile, targetFileDir, ex), "File Not Found Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  292.                 return false;
  293.             }
  294.             catch (IOException ex)
  295.             {
  296.                 MessageBox.Show(ExceptionMessageBuilder.File("An I/O error has occurred.", sourceFile, targetFileDir, ex), "IO Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  297.                 return false;
  298.             }
  299.             catch (ThreadAbortException)
  300.             {
  301.                 Thread.ResetAbort();
  302.                 return false;
  303.             }
  304.             catch (Exception ex)
  305.             {
  306.                 MessageBox.Show(ExceptionMessageBuilder.File("An unexpected exception has occurred:" + Environment.NewLine + ex.Message, sourceFile, targetFileDir, ex), "Unexpected Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  307.                 return false;
  308.             }
  309.             #endregion
  310.         }
  311.     }
  312. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement