Пример #1
0
        private void importFile(string fullFileName)
        {
            try
            {
                string fileName = Path.GetFileName(fullFileName);
                LoggerService.WriteLog(string.Format("Importando arquivo: {0}", fileName), LoggerService.LogType.info);

                using (StreamReader sr = new StreamReader(fullFileName))
                {
                    string      line        = null;
                    FileContent fileContent = new FileContent();
                    while ((line = sr.ReadLine()) != null)
                    {
                        processLine(fileContent, line);
                    }
                    sr.Close();
                    OutputFileContent outputFileContent = summarizeFile(fileContent);
                    saveReport(outputFileContent, fileName);
                    LoggerService.WriteLog(string.Format("Arquivo {0} processado", fileName), LoggerService.LogType.info);

                    string processedFile = Path.Combine(_fileImporterConfiguration.processedFilesDir, fileName);
                    moveAndReplaceFile(fullFileName, processedFile);
                }
            }
            catch (Exception ex)
            {
                LoggerService.WriteLog("Erro procesando arquivo.", LoggerService.LogType.error, ex);
            }
        }
Пример #2
0
        /// <summary>
        /// Gera dados do relatório
        /// * Quantidade de clientes no arquivo de entrada
        /// * Quantidade de vendedor no arquivo de entrada
        /// * ID da venda mais cara
        /// * O pior vendedor
        /// </summary>
        private OutputFileContent summarizeFile(FileContent fileContent)
        {
            OutputFileContent outputFileContent = new OutputFileContent();

            outputFileContent.CustomerCount = fileContent.Customers.Count;
            outputFileContent.SellerCount   = fileContent.Sellers.Count;

            //Pode haver mais de uma venda com o mesmo valor
            decimal bestSale = 0;

            if (fileContent.Sales.Count > 0)
            {
                bestSale = fileContent.Sales.Max(o => o.SalesTotalValue);
            }

            List <Sales> totalBySaller = (from s in fileContent.Sales
                                          group s by new { s.SalesmanName } into grp
                                          select new Sales
            {
                SalesmanName = grp.Key.SalesmanName,
                SalesTotalValue = grp.Sum(o => o.SalesTotalValue)
            }).ToList();

            decimal worstSale = 0;

            if (totalBySaller.Count > 0)
            {
                worstSale = totalBySaller.Min(o => o.SalesTotalValue);
            }

            outputFileContent.ExpensiveSaleId = fileContent.Sales.Where(o => o.SalesTotalValue == bestSale).Select(o => o.SaleId).ToArray();
            outputFileContent.WorstSaller     = totalBySaller.Where(o => o.SalesTotalValue == worstSale).Select(o => o.SalesmanName).ToArray();

            return(outputFileContent);
        }
        /// <summary>
        /// Analyze file content
        /// </summary>
        /// <param name="file"></param>
        private static OutputFileContent AnalyzeFile(FileInfo file)
        {
            FileContent content = ParseToFileContent(file);

            OutputFileContent outputFileContent = new OutputFileContent(content);

            return(outputFileContent);
        }
Пример #4
0
        private string AssertDuplicates(List <FileInfo> filesInfolder, OutputFileContent file)
        {
            var fullPath = $"{_configuration["OutputPath"]}{file.FileName}";

            return(filesInfolder.Any(f => f.Name == file.FileName)
                ? fullPath.Replace(file.FileExtension
                                   , $" - {filesInfolder.Count(f => f.Name == file.FileName) + 1}{file.FileExtension}")
                : fullPath);
        }
Пример #5
0
 private string ReplaceAllPlaceHolders(string template, OutputFileContent file)
 {
     return(template
            .Replace(_configuration["FileNamePlaceHolder"], file.FileName)
            .Replace(_configuration["SalesmenQuantityPlaceHolder"], file.SalesmenQuantity.ToString())
            .Replace(_configuration["CustomersQuantityPlaceHolder"], file.CustomersQuantity.ToString())
            .Replace(_configuration["MostExpensiveSalePlaceHolder"], file.MostExpensiveSale.ToString())
            .Replace(_configuration["WorstSalesmanPlaceHolder"], file.WorstSalesman)
            .Replace(_configuration["GeneratedAtPlaceHolder"], file.GenerationDate.ToString("yyyy-MM-dd HH:mm:ss")));
 }
        public void Execute()
        {
            try
            {
                //init object
                IRepository _InputRepository = new InputRepository();

                if (_InputRepository.HasFiles())
                {
                    OutputRepository _outputRepository = new OutputRepository();

                    //Get files from path
                    FileInfo[] files = _InputRepository.GetAll();

                    //Extract information by each one
                    Parallel.ForEach(files, item =>
                    {
                        OutputFileContent outputFileContent = null;

                        try
                        {
                            //try parse files
                            outputFileContent = AnalyzeFile(item);
                        }
                        catch (Exception ex)
                        {
                            //Move to rejected folder if has error to parse
                            _InputRepository.RejectFile(item);
                            _logger.Error(ex, $"The file {item.Name} cannot be converted and has been moved to the rejected folder.");

                            //move to next interaction
                            return;
                        }

                        //log the processed information
                        _logger.Information($"Processed file {item.FullName} output: {Serializer.Serialize(outputFileContent)}");

                        //Save file in output diretory
                        _outputRepository.AddFile(outputFileContent);
                        //create backup
                        _InputRepository.BackupFile(item.FullName);
                        //delete from input folder
                        _InputRepository.DeleteFile(item.FullName);
                    });
                }
            }
            catch (IOException ex)
            {
                _logger.Error(ex, "An I/O error is ocurred");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "An error is ocurred");
            }
        }
Пример #7
0
        public void AddFile(OutputFileContent content)
        {
            string FileName = content.Identifier.ToString() + ".txt";

            // Create a new file
            using (StreamWriter sw = File.CreateText(Path.Combine(PathUtil.GetOutputPathMonitor(), FileName)))
            {
                sw.WriteLine("Sales report.");
                sw.WriteLine("Customer quantity: {0}", content.CustomerQuantity);
                sw.WriteLine("Sellers quantity: {0}", content.SellerQuantity);
                sw.WriteLine("Most expensive sale Id: {0}", content.IdMostExpansiveSale);
                sw.WriteLine("Worst seller: {0}", content.WorstSeller);
            }
        }
Пример #8
0
        private void saveReport(OutputFileContent outputFileContent, string fileName)
        {
            try
            {
                string outputFileName = fileName.ToLower().Replace(_fileImporterConfiguration.extentionFile.ToLower(), _fileImporterConfiguration.processedExtentionFile.ToLower());
                string outputString   = Newtonsoft.Json.JsonConvert.SerializeObject(outputFileContent);

                LoggerService.WriteLog(string.Format("Criando relatório {0}", outputFileName), LoggerService.LogType.info);
                using (StreamWriter sw = new StreamWriter(Path.Combine(_fileImporterConfiguration.outputDir, outputFileName)))
                {
                    sw.WriteLine(outputString);
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                LoggerService.WriteLog("Não foi possível mover arquivo", LoggerService.LogType.error, ex);
            }
        }
Пример #9
0
        public void TestSumarizeReport()
        {
            LoggerService.disableLogger = true;
            FileContent fileContent = new FileContent();

            fileContent.Sales.Add(new Sales {
                SaleId = 1, SalesmanName = "Pedro", SalesTotalValue = 100
            });
            fileContent.Sales.Add(new Sales {
                SaleId = 2, SalesmanName = "Carlos", SalesTotalValue = 200
            });
            fileContent.Sales.Add(new Sales {
                SaleId = 3, SalesmanName = "Pedro", SalesTotalValue = 200
            });
            fileContent.Sellers.Add(new Seller {
                CPF = "111111111", Name = "Pedro", Salary = 2500.55m
            });
            fileContent.Sellers.Add(new Seller {
                CPF = "222222222", Name = "Carlos", Salary = 2800.55m
            });
            fileContent.Customers.Add(new Customer {
                CNPJ = "99999999999999", BusinessArea = "TI", Name = "XXX LTDA"
            });
            fileContent.Customers.Add(new Customer {
                CNPJ = "88888888888888", BusinessArea = "Agro", Name = "YYY LTDA"
            });

            FileImporterService fileImporterService = new FileImporterService(configureFileImporterParameters());
            PrivateObject       obj = new PrivateObject(fileImporterService);

            OutputFileContent summarizeFile = (OutputFileContent)obj.Invoke("summarizeFile", fileContent);

            Assert.IsTrue(
                summarizeFile.CustomerCount == 2 &&
                summarizeFile.SellerCount == 2 &&
                Enumerable.SequenceEqual(summarizeFile.ExpensiveSaleId, new int[] { 2, 3 }) &&
                Enumerable.SequenceEqual(summarizeFile.WorstSaller, new string[] { "Carlos" })
                );
        }
Пример #10
0
        public void GenerateFIle(OutputFileContentDto outputDto)
        {
            _logger.LogInformation($"{outputDto.FileName} output is been generated.");

            var outputContent = new OutputFileContent
            {
                FileName          = outputDto.FileName,
                FileExtension     = outputDto.FileExtension,
                SalesmenQuantity  = outputDto.SalesmenQuantity,
                CustomersQuantity = outputDto.CustomersQuantity,
                MostExpensiveSale = outputDto.MostExpensiveSale,
                WorstSalesman     = outputDto.WorstSalesman,
                GenerationDate    = outputDto.GenerationDate
            };

            var folderFiles = GetFilesInfolder();

            var fileFullName = AssertDuplicates(folderFiles, outputContent);

            var template = File.ReadAllText(_configuration["TemplateFullPath"]);

            if (string.IsNullOrEmpty(template))
            {
                _logger.LogCritical("Template file cannot be found");
                return;
            }

            var replacedTemplate = ReplaceAllPlaceHolders(template, outputContent);

            _logger.LogInformation("Template replaced, writing output file");

            File.WriteAllText(fileFullName, replacedTemplate);

            _logger.LogInformation("Saving processed file into the database for service trace history");

            _context.OutputFilesContent.Add(outputContent);

            _context.SaveChanges();
        }