Ejemplo n.º 1
0
        /// <summary>
        /// <para/>Writes an error log file when something went wrong while writing a file with WriteFile(...).
        /// <para/>The error log will be saved in the format "[fileName]_error_yyyy-MM-dd_HH-mm-ss.log" in the filePath directory.
        /// </summary>
        /// <param name="filePath">Where the file should be saved.</param>
        /// <remarks>Writes down all inner exceptions of the FileWriteException. When this process also fails, no exception will be thrown but just ignored.</remarks>
        private void WriteErrorLog(FileWriteException exception, string filePath)
        {
            // Change from written file to [...]_error_yyyy-MM-dd_HH-mm-ss.log
            string fileDateTimeFormat = "yyyy-MM-dd_HH-mm-ss";
            string onlyFilePath       = System.IO.Path.GetDirectoryName(filePath);            //FileInfo.ExtractFilePath(filePath);
            string onlyFileName       = System.IO.Path.GetFileNameWithoutExtension(filePath); //FileInfo.ExtractFileName(filePath);
            string newFilePath        = (onlyFilePath + System.IO.Path.DirectorySeparatorChar + onlyFileName + "_error_" + DateTime.Now.ToString(fileDateTimeFormat) + ".log");

            // Create error log content
            StringBuilder sb = new StringBuilder();

            {
                sb.AppendLine(Program.ProgramHeader + " | Error log | " + DateTime.Now.ToString(Program.ICul));
                sb.AppendLine("The file \"" + filePath + "\" couldn't be written properly.");
                sb.AppendLine("Below is a list of errors that occured:\n");
                sb.AppendLine("----------[Start error list]-------------------------");
                sb.Append(exception.ToString());
                sb.AppendLine("----------[End error list]---------------------------");
                sb.AppendLine("\nFor more information, visit: \"https://sunburst275.jimdofree.com/about-1/contact\" and/or contact Sunburst275 directly.");
            }

            try
            {
                WriteFile(sb.ToString(), newFilePath);
            }
            catch (Exception)
            {
                // Ignore
            }
        }
Ejemplo n.º 2
0
        /// <summary>Writes all lines in a List<string> into a file specified by filePath and closes the file.</summary>
        /// <param name="content">List of strings that are to be written into the file. The order is the same as the content of the list itself.</param>
        /// <param name="filePath">Path and name and extension of the file that should be written.</param>
        /// <exception cref="FileWriteException">Can throw the dedicated exception that indicates something went wrong with this file writing process.</exception>
        private void WriteFile(List <string> content, string filePath)
        {
            // TODO: Inform youself: How to best handle problems of file writing/reading
            var errorOccured = false;
            FileWriteException fileWriteException = new FileWriteException();

            if (string.IsNullOrEmpty(filePath) || content == null || content.Count <= 0)
            {
                throw new FileWriteException("File is empty.");
            }

            // Write file
            try
            {
                using (StreamWriter sW = new StreamWriter(new FileStream(filePath, FileMode.Create), Encoding.UTF8))
                {
                    for (int index = 0; index < content.Count; index++)
                    {
                        sW.WriteLine(content.ElementAt(index));
                    }
                }
            }
            catch (Exception ex)
            {
                fileWriteException.AddInnerException(ex);
                errorOccured = true;
            }

            // Verify file content and check whether file writing was done successfully
            List <string> testContent = new List <string>();

            try
            {
                using (StreamReader sR = new StreamReader(new FileStream(filePath, FileMode.Open), Encoding.UTF8))
                {
                    while (!sR.EndOfStream)
                    {
                        testContent.Add(sR.ReadLine());
                    }
                }
            }
            catch (Exception ex)
            {
                fileWriteException.AddInnerException(ex);
                errorOccured = true;
            }
            // If read file is empty
            if (testContent.Count <= 0)
            {
                fileWriteException.AddInnerException(new Exception("Written file was empty."));
                errorOccured = true;
            }
            // Check whether every line in file corresponds to the same line in content
            if (testContent.Count != content.Count)
            {
                fileWriteException.AddInnerException(new Exception("Written content is not the same as the generated content."));
                errorOccured = true;
            }
            else
            {
                for (int i = 0; i < testContent.Count; i++)
                {
                    if (testContent[i] != content[i])
                    {
                        fileWriteException.AddInnerException(new Exception("Written content is not the same as the generated content."));
                        errorOccured = true;
                        break;
                    }
                }
            }

            if (errorOccured)
            {
                throw fileWriteException;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// <para/>Is called when StartButton was clicked.
        /// <para/>Starts the removing of selected columns and proceeds to write the result to a file.
        /// </summary>
        private void StartButton_Click(object sender, EventArgs e)
        {
            if (!file.IsValid())
            {
                MessageBox.Show("File is not valid!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var fromAndTo = CalculateSelectedSection();
            int realFrom  = fromAndTo.Item1;
            int realTo    = fromAndTo.Item2;

            using (SaveFileDialog svd = new SaveFileDialog())
            {
                var pathAndName = file.GetPathAndName();
                if (pathAndName == string.Empty)
                {
                    svd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
                }
                else
                {
                    svd.InitialDirectory = FileInfo.ExtractFilePath(pathAndName);
                }
                svd.Filter           = "Input file type " + "(*." + file.GetFileTypeString() + ")|*." + file.GetFileTypeString();
                svd.FilterIndex      = 1;
                svd.RestoreDirectory = true;
                svd.CheckPathExists  = true;

                bool errorOccured        = false;
                FileWriteException error = null;
                DialogResult       dr    = svd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    // Start new thread and show MessageBox "done" when done
                    ChangeGuiLockingState(GuiLockingState.Lock);
                    ShowProcessingDialog();
                    try
                    {
                        // FYI: Because of the exceptions, this cant be done in another thread...
                        //writingThread = new Thread(() =>
                        //{
                        //    WriteFile(RemoveColumSpanInContent(file.GetContent(), realFrom, realTo), svd.FileName);
                        //});
                        //writingThread.Start();
                        WriteFile(RemoveColumSpanInContent(file.GetContent(), realFrom, realTo), svd.FileName);
                    }
                    catch (FileWriteException ex)
                    {
                        error        = ex;
                        errorOccured = true;
                    }
                    catch (Exception)
                    {
                        errorOccured = true;
                    }

                    CloseProcessingDialog();
                    ChangeGuiLockingState(GuiLockingState.Release);
                    if (errorOccured)
                    {
                        if (error != null)
                        {
                            WriteErrorLog(error, svd.FileName);
                        }
                        ShowProcessingResult(ProcessingDialogResult.Failed);
                    }
                    else
                    {
                        ShowProcessingResult(ProcessingDialogResult.Success);
                    }
                    return;
                }
            }
        }