예제 #1
0
        /// <summary>
        /// Prepares to convert a delimited file to CSV and notifies the user of progress through the status display.
        /// </summary>
        /// <param name="file">The full path of the delimited file to be converted.</param>
        /// <param name="delimiter">The delimiting character used in the delimited file.</param>
        /// <returns>True if no errors were encountered, false otherwise.</returns>
        private bool BeginDelimitedToCsvConversion(List <string> files, char delimiter, string qualifier = "")
        {
            bool   noErrors    = true;
            string currentTime = DateTime.Now.ToString();

            foreach (string file in files)
            {
                // Print current activity in the status display
                string msg     = $"{Environment.NewLine}Converting {Path.GetFileName(file)} ...";
                string tooltip = $"Started {DateTime.Now.ToString()}";
                Dispatcher.Invoke(() => WriteToStatusDisplay(msg, tooltip, Brushes.DarkOrange), DispatcherPriority.Background);

                // Construct output file path and output a CSV file to the path
                string fullOutputPath = $"{_outputDirectory}\\{Path.GetFileNameWithoutExtension(file)}.csv";

                var error = CsvConverter.WriteCsvRowsToFile(delimiter, file, fullOutputPath, qualifier);
                if (error != null) // errors encountered during operation
                {
                    noErrors = false;
                    File.Delete(fullOutputPath);  // delete the incomplete CSV file
                    msg     = " Error!";
                    tooltip = $"Error on line {error.LineNumber}: {error.Message}";
                    Dispatcher.Invoke(() => WriteErrorToStatusDisplay(msg, tooltip), DispatcherPriority.Background);
                }
                else // no errors detected
                {
                    msg     = " Done!";
                    tooltip = $"This file was successfully processed at {DateTime.Now.ToString("T")}";
                    Dispatcher.Invoke(() => WriteToStatusDisplay(msg, tooltip, Brushes.Green), DispatcherPriority.Background);
                }
            }
            return(noErrors);
        }
예제 #2
0
        /// <summary>
        /// Prepares to convert a fixed length file to CSV and notifies the user of progress through the status display.
        /// </summary>
        /// <param name="file">The full path of the file to be converted.</param>
        /// <returns>True if no errors were encountered. False otherwise.</returns>
        private async Task <bool> BeginFixedLengthToCsvConversionAsync(List <string> files, string qualifier = "")
        {
            bool noErrors = false;
            // Get the field count and field lengths from user input
            int numFields = tbFieldLengths.Text.Split(',').Length;  // Number of field lengths entered in tbFieldLengths

            string[] fieldWidthsAsStrings = tbFieldLengths.Text.Split(',');
            int[]    fieldWidths          = Array.ConvertAll(fieldWidthsAsStrings, int.Parse);
            string   currentTime          = DateTime.Now.ToString();

            foreach (string file in files)
            {
                // Print current activity in the status display
                string msg     = $"{Environment.NewLine}Converting {Path.GetFileName(file)} ...";
                string tooltip = $"Started {DateTime.Now.ToString()}";
                WriteToStatusDisplay(msg, tooltip, Brushes.DarkOrange);

                // Construct output file path
                string fullOutputPath = $"{OutputDirectory}\\{Path.GetFileNameWithoutExtension(file)}.csv";

                // Start writing CSV rows to the file
                long resultCode = await Task.Run(() => CsvConverter.WriteCsvRowsToFile(fieldWidths, file, fullOutputPath, qualifier));

                if (resultCode != 0)  // Error converting file to CSV. At present, only a MalformedLineException will cause this.
                {
                    noErrors = true;
                    string errorMsg    = $"{Environment.NewLine}   Error converting {file}: {Environment.NewLine}   Line {resultCode} cannot be parsed with the given field lengths.";
                    string tooltipText = "Check that the field lengths you specified are correct for this file. Note that all selected files must have the same field lengths.";
                    WriteErrorToStatusDisplay(errorMsg, tooltipText);
                }
                else
                {
                    WriteToStatusDisplay(" Done!", "This file was successfully processed.", Brushes.Green);
                }
            }
            return(noErrors);
        }
예제 #3
0
        /// <summary>
        /// TO DO: IMPROVE STATUS OUTPUT!!!
        /// Prepares to convert an Excel file to CSV and notifies the user of progress through the status display.
        /// </summary>
        /// <param name="files">The full path of the file to be converted.</param>
        /// <param name="excelFileType">The type of excel file type. Value should be either ".xls" or ".xlsx".</param>
        /// <returns>True if no errors were encountered, false otherwise.</returns>
        private async Task <bool> BeginExcelToCsvConversionAsync(List <string> files, string excelFileType, string qualifier = "")
        {
            bool noErrors = true;  // false if any exceptions were caught

            foreach (string file in files)
            {
                // Print current activity in status display
                string msg     = $"{Environment.NewLine}Converting {Path.GetFileName(file)} ...";
                string tooltip = "Started " + DateTime.Now.ToString();
                WriteToStatusDisplay(msg, tooltip, Brushes.DarkOrange);

                // Form connection string for the Excel file
                string connectionString = null;
                switch (excelFileType.ToLower())
                {
                case ".xls":
                    connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.16.0; 
                                                            Data Source={0}; OLE DB Services=-1;
                                                            Extended Properties='Excel 8.0; HDR=Yes;'"
                                                     , file);
                    // HDR=Yes indicates that the first row contains column names, not data
                    break;

                case ".xlsx":
                    connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.16.0;
                                                            Data Source={0}; OLE DB Services=-1;
                                                            Extended Properties='Excel 12.0 Xml; HDR=YES; IMEX=1;'"
                                                     // IMEX=1 treats all data as text
                                                     , file);
                    break;

                default:
                    string errorMsg = "Fatal error: An Excel radio button was expected from parameter \"excelFileType\" in ConvertExcelFilesToCsv() but " +
                                      "not received. Please contact the developer.";
                    string caption = "Fatal error in ConvertExcelFilesToCsv()";
                    MessageBox.Show(errorMsg, caption);
                    break;
                }

                // Create new OleDB connection
                using (OleDbConnection connection = new OleDbConnection(connectionString))
                {
                    try
                    {
                        // Open the OleDB connection to the Excel sheet and execute query
                        await Task.Run(() => connection.Open());

                        string       queryString = "SELECT * FROM [Sheet1$]";
                        OleDbCommand command     = new OleDbCommand(queryString, connection);

                        string currentTime = DateTime.Now.ToString();

                        // Construct the output file path and begin writing CSV rows to that file
                        string fullOutputPath = OutputDirectory + @"\" + Path.GetFileNameWithoutExtension(file) + ".csv";
                        CsvConverter.WriteCsvRowsToFile(command, fullOutputPath, qualifier);
                    }
                    catch (OleDbException e)
                    {
                        noErrors = false;
                        string errorMsg = $"{Environment.NewLine}   Error: " + e.Message;
                        string tip      = "There is a problem with this Excel file. Please refer to the status display.";
                        WriteErrorToStatusDisplay(errorMsg, tip);
                    }
                    WriteToStatusDisplay(" Done!", "This file was successfully processed.", Brushes.Green);
                }
            }
            return(noErrors);
        }