예제 #1
0
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            DocumentGenerationModel model = (DocumentGenerationModel)e.Argument;

            using (StreamWriter logger = File.CreateText(model.OutputPath + ".log"))
                using (ExcelReader.RowReader rowReader = model.Reader.CreateRowReader(model.Sheet))
                {
                    uint       errors = 0;
                    WordWriter writer = new WordWriter();
                    IDictionary <string, string> rows = null;
                    for (int i = 0; (rows = rowReader.ReadNextRow()) != null; i++)
                    {
                        try
                        {
                            LoadingService.SetLoadingText($"Processing row {i}...");
                            if (!rows.TryGetValue(model.Header, out string templateName))
                            {
                                throw new LibraryException($"No value exists for template key \"{model.Header}\"", i, rows);
                            }

                            if (string.IsNullOrWhiteSpace(templateName))
                            {
                                throw new LibraryException($"Cell for \"{model.Header}\" is blank", i, rows);
                            }

                            string templatePath = null;
                            try
                            {
                                templatePath = Path.Combine(model.TemplatesPath, $"{templateName}.docx");
                            }
                            catch (ArgumentException ex)
                            {
                                throw new LibraryException("Failed to combine specified TemplateDirectory and TemplateKey. The result was an invalid path\n" +
                                                           $"Key used: \"{model.Header}\"\n" +
                                                           $"Value retrieved: \"{templateName}\"",
                                                           ex, i, rows);
                            }

                            if (!File.Exists(templatePath))
                            {
                                throw new LibraryException($"Could not find template using calculated path: {templatePath}", i, rows);
                            }

                            byte[] rawTemplate = File.ReadAllBytes(templatePath);
                            using (MemoryStream templateStream = new MemoryStream())
                            {
                                templateStream.Write(rawTemplate, 0, rawTemplate.Length);
                                try
                                {
                                    writer.GenerateAndAppendTemplate(templateStream, rows, i);
                                }
                                catch (DocumentWriterException ex)
                                {
                                    throw new LibraryException("Parse error", ex, i, rows);
                                }
                            }
                        }
                        catch (LibraryException ex)
                        {
                            logger.WriteLine($"A row was skipped while processing: {ex.ToString()}");

                            if (!model.IgnoreErrors)
                            {
                                string msg = $"An error occurred while attempting to use the Loop Check Library: \"{ex.Message}\"";
                                if (ex.InnerException != null)
                                {
                                    msg += $"\nThe inner exception's message is: \"{ex.InnerException.Message}\"";
                                }

                                msg += "\nDo you wish to continue execution? This row will be ignored.";

                                _worker.ReportProgress(0, new DocumentGenerationState(msg, DocumentGenerationStateType.BlockingMessage));
                                _mutex.WaitOne();

                                if (_worker.CancellationPending)
                                {
                                    e.Cancel = true;
                                    return;
                                }
                            }

                            errors++;
                        }
                    }

                    LoadingService.SetLoadingText("Writing file to disk...");
                    using (MemoryStream export = writer.ExportDocument())
                    {
                        File.WriteAllBytes(model.OutputPath, export.ToArray());
                    }

                    e.Result = errors;
                }
        }
예제 #2
0
        /// <summary>
        /// Generates a document via LoopCheckTool.Lib.
        /// </summary>
        /// <returns>Return code</returns>
        public int Execute()
        {
            try
            {
                ExcelReader           reader = new ExcelReader(InputFilePath);
                ExcelReader.Worksheet sheet  = reader.GetWorksheets().Where(ws => Sheet.Equals(ws.Name)).FirstOrDefault();

                if (sheet != default(ExcelReader.Worksheet))
                {
                    using (ExcelReader.RowReader rowReader = reader.CreateRowReader(sheet))
                    {
                        WordWriter writer = new WordWriter();
                        IDictionary <string, string> rows = null;
                        for (int i = 0; (rows = rowReader.ReadNextRow()) != null; i++)
                        {
                            try
                            {
                                if (!rows.TryGetValue(TemplateKey, out string templateName))
                                {
                                    throw new LibraryException($"No value exists template key \"{TemplateKey}\".", i, rows);
                                }

                                if (string.IsNullOrWhiteSpace(templateName))
                                {
                                    throw new LibraryException($"Cell for \"{TemplateKey}\" is blank.", i, rows);
                                }

                                string templatePath = null;
                                try
                                {
                                    templatePath = Path.Combine(TemplateDirectory, $"{templateName}.docx");
                                }
                                catch (ArgumentException ex)
                                {
                                    throw new LibraryException("Failed to combine specified TemplateDirectory and TemplateKey. The result was an invalid path.\n" +
                                                               $"Key used: \"{TemplateKey}\".\n" +
                                                               $"Value retrieved: \"{templateName}\".",
                                                               ex, i, rows);
                                }

                                if (!File.Exists(templatePath))
                                {
                                    throw new LibraryException($"Could not find template using calculated path: {templatePath}.", i, rows);
                                }

                                byte[] rawTemplate = File.ReadAllBytes(templatePath);
                                using (MemoryStream templateStream = new MemoryStream())
                                {
                                    templateStream.Write(rawTemplate, 0, rawTemplate.Length);
                                    try
                                    {
                                        writer.GenerateAndAppendTemplate(templateStream, rows, i);
                                    }
                                    catch (DocumentWriterException ex)
                                    {
                                        throw new LibraryException("Parse error", ex, i, rows);
                                    }
                                }
                            }
                            catch (LibraryException ex)
                            {
                                System.Console.Error.WriteLine($"An error occurred while attempting to use the Loop Check Library: \"{ex.Message}\"");
                                System.Console.Error.WriteLine($"IO List row {ex.AffectedRow}.");
                                if (ex.InnerException != null)
                                {
                                    System.Console.Error.WriteLine($"The inner exception's message is: \"{ex.InnerException.Message}\"");
                                }

                                if (!IgnoreErrors)
                                {
                                    throw ex;
                                }
                            }
                        }

                        using (MemoryStream export = writer.ExportDocument())
                        {
                            File.WriteAllBytes(OutputFilePath, export.ToArray());
                        }
                    }
                }
                else
                {
                    System.Console.WriteLine("The specified sheet does not exist.");

                    return(1);
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Stopping due to error.");
                System.Console.WriteLine("Run with the '--ignoreErrors' flag to attempt to bypass this error.");
                System.Console.Error.WriteLine(ex.StackTrace);

                if (ex is LibraryException libEx)
                {
                    foreach (KeyValuePair <string, string> pair in libEx.RowData)
                    {
                        System.Console.Error.WriteLine($"{pair.Key}: {pair.Value}");
                    }
                }

                return(1);
            }

            return(0);
        }