I have a windows service engine that process some input files that users upload from a web application, the application reads them and send to another engine where some calculations are generated over the data that was inputed and send the result to yet another engine where the reports are finally concluded and sent to the user as an downloadable excel. The data has to be very consistent, so it means that a single error can lead to thousands of money lost.
Given the importance of the data, the users want to be able to know all errors that occurred during the process of the files, so my main question is:
Does there are any way to achieve this without polluting my code with a bunch of try..catch ?
I mean a elegant solution that has already been used and proved... a pattern to generate reports from errors and take me away from thousands of try..catch spreaded in a bunch of files that are already implemented.
Just a note: If you guys find any weird grammatical mistake i really sorry as english is not my main language.
public List<ProcessamentoBeneficiarioBll> ProcessFile(int idOfProcess, Hashtable configs)
{
if (UibAppConfig.Settings["Debugging"].Equals("false"))
{
EventLog.WriteEntry(configs["Nm_Servico"].ToString(), "Inciando processamento de carga de persones", EventLogEntryType.Information);
}
var timeOfStart = DateTime.Now.TimeOfDay;
var processFile = _processService.FindprocessFileByType(12, idOfProcess).FirstOrDefault();
StringBuilder resultToShowOnUi = new StringBuilder();
if (processFile != null)
{
string filenameTobeSaved = String.Format("{0}\\{1}\\{2}{3}", configs["DirprocessFilesCarga"],
processFile.id_estipulante, "conf_" + processFile.id_processFile,
Path.GetExtension(processFile.ds_filename));
var excel = new ExcelFile();
try
{
excel.LoadXlsx(filenameTobeSaved, XlsxOptions.None);
}
catch (Exception ex)
{
throw new ApplicationException(String.Format("arquivo {0} não encontrado.", filenameTobeSaved), ex);
}
if (excel.Worksheets.Count == 0)
{
throw new ApplicationException("O arquivo de colaboradores deve conter pelo menos uma planilha.");
}
var listOfPeopleInFile = new List<ProcessamentoBeneficiarioBll>();
List<Tuple<Exception, int>> listofThrownExceptions = new List<Tuple<Exception, int>>();
var worksheet = excel.Worksheets.ActiveWorksheet;
for (var row = 3; row < worksheet.Rows.Count; ++row)
{
var person = new ProcessamentoBeneficiarioBll();
person.CD_MATRICULA = (worksheet.Cells[row, 0].Value != null)
? worksheet.Cells[row, 0].Value.ToString()
: "Desligado";
if (worksheet.Cells[row, 8].Value != null)
{
try
{
person.DT_ADMISSAO =
Convert.ToDateTime(worksheet.Cells[row, 8].Value);
}
catch (Exception)
{
listofThrownExceptions.Add(
new Tuple<Exception, int>(
new ApplicationException("Data de admissão deve ter o formato DD/MM/AAAA"), row + 1));
}
}
if (worksheet.Cells[row, 14].Value != null)
{
try
{
person.DT_DEMISSAO =
Convert.ToDateTime(worksheet.Cells[row, 14].Value);
}
catch (Exception ex)
{
listofThrownExceptions.Add(
new Tuple<Exception, int>(
new ApplicationException("Data de demissão deve ter o formato DD/MM/AAAA", ex),
row + 1));
}
}
person.CD_CPF = (worksheet.Cells[row, 6].Value != null)
? Uib.Core.Util.Utils.RemoveChars(
worksheet.Cells[row, 6].Value.ToString(),
new char[] {'.', '-'})
: null;
if (worksheet.Cells[row, 7].Value != null)
{
try
{
person.DT_NASCIMENTO =
Convert.ToDateTime(worksheet.Cells[row, 7].Value);
}
catch (Exception ex)
{
listofThrownExceptions.Add(
new Tuple<Exception, int>(
new ApplicationException("Data de nascimento deve ter o formato DD/MM/AAAA", ex),
row + 1));
}
}
person.CD_SEXO = (worksheet.Cells[row, 11].Value != null)
? worksheet.Cells[row, 11].Value.ToString()
: null;
person.DS_NOME_BENEFICIARIO_TITULAR =
(worksheet.Cells[row, 5].Value != null)
? worksheet.Cells[row, 5].Value.ToString()
: "Nome não informado";
person.CD_ESTADOCIVIL = (worksheet.Cells[row, 12].Value != null)
? worksheet.Cells[row, 12].Value.ToString()
: null;
if (worksheet.Cells[row, 10].Value != null)
{
try
{
person.VL_SALARIO =
Convert.ToDecimal(worksheet.Cells[row, 10].Value);
}
catch (Exception ex)
{
listofThrownExceptions.Add(
new Tuple<Exception, int>(
new ApplicationException("Valor salario está em um formato inválido.", ex), row + 1));
}
}
else
{
person.VL_SALARIO = 0.0M;
}
person.DS_CARGO = (worksheet.Cells[row, 15].Value != null)
? worksheet.Cells[row, 15].Value.ToString()
: null;
listOfPeopleInFile.Add(person);
}
resultToShowOnUi.AppendFormat("persones: Foram selecionados {0} persones.\r\n",
listOfPeopleInFile.Count);
Console.WriteLine(resultToShowOnUi);
excel.ClosePreservedXlsx();
if (!listofThrownExceptions.Any())
{
try
{
TimeSpan timeOfEnd = DateTime.Now.TimeOfDay - timeOfStart;
resultToShowOnUi.AppendFormat(
"processFile de utilização importado com sucesso, tempo decorrido: {0:g}\r\n",
timeOfEnd);
_processService.EndProcess(processFile.id_processFile, 0, 1, false, resultToShowOnUi.ToString(),
null);
return listOfPeopleInFile;
}
catch (Exception ex)
{
throw new ApplicationException(
String.Format(
"Falha na importação do processFile de persones."), ex);
}
}
else
{
configs["DisplayLineNumber"] = true;
var urlReport = new ProcessErrorsReportGenerator(processFile, listofThrownExceptions).Run(0, configs);
var url = "/processFiles/Reports/" + processFile.id_estipulante + "/Erros/" + urlReport;
resultToShowOnUi.AppendFormat(
String.Format(
"A importação do processFile falhou por uma ou mais exceções. Cheque o log de consistência para uma lista detalhada sobre os erros: Número de erros: {0}. {1}",
listofThrownExceptions.Count, "<a href='" + url + "'>Relatório de Consistência</a>"));
_processService.EndProcess(processFile.id_processFile, 0, 1, true, resultToShowOnUi.ToString(), null);
return null;
}
}
else
{
throw new ApplicationException("É necessário informar um arquivo segvida para buscar as matrículas da Unimed.");
}
}
Aucun commentaire:
Enregistrer un commentaire