Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using StructureMap;
- using Uon.Log.Interfaces;
- using System.IO;
- using LusoRouxTI.IO;
- using LusoRouxTI.Xml.Serialization;
- using LusoRouxTI.Extensions;
- using LusoRouxTI.IO.Compression;
- using System.Xml.Serialization;
- using Uon.UonDateTime;
- using Uon.Portal.UnitOfWork;
- using Uon.Portal.Business.BPM;
- using Uon.Data.UnitOfWork.Interfaces;
- using Uon.Portal.Entities;
- using LusoRouxTI.Doc.Excel.AsposeExcel;
- using System.Globalization;
- using Uon.Portal.Business.Core;
- using LusoRouxTI.Sms;
- using LuxoRouxTI.Sms.Factory;
- using SMS.UnitOfWork;
- using Uon.Portal.Business.Comm;
- namespace Uon.Portal.Integration.Generali.Cobranca
- {
- class Program
- {
- private enum FileExtensions
- {
- [XmlEnum(".rar")]
- Rar,
- [XmlEnum(".zip")]
- Zip
- }
- private enum LembreteAtraso
- {
- Lembrete,
- Atraso
- }
- private enum IntegracaoLogMessage
- {
- [XmlEnum("GeneraliCobrança - File Downloaded")]
- DownloadFile,
- [XmlEnum("GeneraliCobrança - Start processing the file")]
- StartProcessingFile,
- [XmlEnum("GeneraliCobrança - File Processed with Success")]
- ProcessedFile,
- [XmlEnum("GeneraliCobrança - Error after try processing the file")]
- ErrorFile
- }
- private enum UonState
- {
- Processado = 1,
- Ignorar = 0,
- Erro = -1,
- ErroSms = -2,
- ErroEmail = -3
- }
- //Log variable
- private static ILog log;
- //Paths
- private static IEnumerable<string> storageWritePaths;
- private static string originalLocationOfFiles;
- private static string locationDownloadedFiles;
- private static string locationProcessedFiles;
- private static string locationErrorFiles;
- private static List<string> listOfCodeProducts;
- private static int daysBefore, daysAfter;
- private static int? columnCodigoProdutoIndex, columnDataVencimentoIndex, columnEmailIndex;
- private static Dictionary<int, Tuple<int, int>> dictionaryTel; //contem os indices das colunas
- private static int processId;
- private static int errorCounter;
- static void Main(string[] args)
- {
- // Initialize the Log 4 Net
- ObjectFactory.Initialize(x => x.PullConfigurationFromAppConfig = true);
- log = ObjectFactory.GetInstance<ILog>();
- try
- {
- processId = GetProcessId();
- // Get the value of paths or return exception
- GetPaths(out storageWritePaths, out originalLocationOfFiles, out locationDownloadedFiles, out locationProcessedFiles, out locationErrorFiles);
- // create directories for download, processed and error files.
- CreateFoldersDownloadAndProcessedAndError(storageWritePaths, locationDownloadedFiles, locationProcessedFiles, locationErrorFiles);
- // The path correspond a file path
- if (File.Exists(originalLocationOfFiles))
- {
- ProcessFile(originalLocationOfFiles);
- }
- // The path is from a directory
- else if (Directory.Exists(originalLocationOfFiles))
- {
- // get file paths in folder
- var filePaths = GetFilesPathFromDirectory(originalLocationOfFiles);
- foreach (string file in filePaths)
- {
- try
- {
- ProcessFile(originalLocationOfFiles);
- }
- catch (Exception ex)
- {
- try { log.Error(new LogEntry { Exception = ex, Tag = "GeneraliCobrança" }); }
- catch { }
- }
- }
- }
- else
- {
- try
- {
- log.Error(new LogEntry { Message = "O caminho do ficheiro ou do diretório a processar não é válido.", Tag = "GeneraliCobrança" });
- }
- catch { }
- }
- }
- catch (Exception ex)
- {
- try { log.Error(new LogEntry { Exception = ex, Tag = "GeneraliCobrança" }); }
- catch { }
- }
- }
- private static int GetProcessId()
- {
- using (var uow = new UnitOfWorkPortal())
- {
- int objSubCategoriaIdOfProcess = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ObjSubCategoriaIdOfProcess"]);
- string refExternaOfProcess = System.Configuration.ConfigurationManager.AppSettings["RefExternaOfProcess"];
- int processoId = new ObjProcessoService(uow).Get().Where(x => x.ObjSubCategoriaId == objSubCategoriaIdOfProcess && x.ObjRefExterna == refExternaOfProcess).Select(x => x.Id).FirstOrDefault();
- if (processoId == 0)
- {
- throw new ArgumentException("Não foi encontrado um processoId referente ao obj que contem a subCategoriaId: " + System.Configuration.ConfigurationManager.AppSettings["ObjSubCategoriaIdOfProcess"] + ", e, com a refExterna: " + System.Configuration.ConfigurationManager.AppSettings["RefExternaOfProcess"]);
- }
- return processoId;
- }
- }
- private static void GetPaths(out IEnumerable<string> storageWritePaths, out string originalLocationOfFiles, out string locationDownloadedFiles, out string locationProcessedFiles, out string locationErrorFiles)
- {
- storageWritePaths = (System.Configuration.ConfigurationManager.AppSettings["StorageWritePaths"] ?? string.Empty).Split(',', ';');
- if (string.IsNullOrWhiteSpace(storageWritePaths.FirstOrDefault()))
- {
- storageWritePaths = null;
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["FolderLocationToGetFiles"]))
- {
- throw new ArgumentException("FolderLocationToGetFiles in app.config is null or empty");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["FolderLocatioOfDownloadedFiles"]))
- {
- throw new ArgumentException("FolderLocationOfDownloadedFiles in app.config is null or empty");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["FolderLocationOfProcessedFiles"]))
- {
- throw new ArgumentException("FolderLocationOfProcessedFiles in app.config is null or empty");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["FolderLocationOfErrorFile"]))
- {
- throw new ArgumentException("FolderLocationOfErrorFile in app.config is null or empty");
- }
- originalLocationOfFiles = System.Configuration.ConfigurationManager.AppSettings["FolderLocationToGetFiles"];
- locationDownloadedFiles = System.Configuration.ConfigurationManager.AppSettings["FolderLocatioOfDownloadedFiles"];
- locationProcessedFiles = System.Configuration.ConfigurationManager.AppSettings["FolderLocationOfProcessedFiles"];
- locationErrorFiles = System.Configuration.ConfigurationManager.AppSettings["FolderLocationOfErrorFiles"];
- }
- private static void CreateFoldersDownloadAndProcessedAndError(IEnumerable<string> storageWritePaths, string locationDownloadedFiles, string locationProcessedFiles, string locationErrorFiles)
- {
- string downloadedFolder = new StorageManager().GetAvailableWritePath(locationDownloadedFiles, storageWritePaths);
- Directory.CreateDirectory(downloadedFolder);
- string processedFolder = new StorageManager().GetAvailableWritePath(locationProcessedFiles, storageWritePaths);
- Directory.CreateDirectory(processedFolder);
- string errorFolder = new StorageManager().GetAvailableWritePath(locationErrorFiles, storageWritePaths);
- Directory.CreateDirectory(errorFolder);
- }
- private static IntegracaoLog GetIntegracaoLog( IntegracaoLogService integracaoLogService, string filename)
- {
- var integracaoLog = integracaoLogService.GetByCliExternalId(Path.GetFileName(filename)).OrderByDescending(x => x.Id).FirstOrDefault();
- if (integracaoLog == null)
- {
- integracaoLog = GetNewIntegracaoLog(2, filename, processId, IntegracaoLogMessage.DownloadFile.ReadXmlEnumAttribute(), null, null, null, null, null);
- integracaoLogService.Add(integracaoLog);
- }
- return integracaoLog;
- }
- private static void ProcessFile(string pathFile)
- {
- string fileExtension = Path.GetExtension(pathFile);
- string filenameWithoutExtension = Path.GetFileNameWithoutExtension(pathFile);
- string datetimeNow = UONDateTime.Now.Ticks.ToString();
- //Rename current file
- string newNameWithCurrentTicks = Path.ChangeExtension(Path.Combine(filenameWithoutExtension, "_" + datetimeNow), fileExtension);
- System.IO.File.Move(pathFile, newNameWithCurrentTicks);
- //Copy file to folder of dowload
- string newPathDowloadedFile = Path.Combine(locationDownloadedFiles, Path.GetFileName(newNameWithCurrentTicks));
- System.IO.File.Copy(newNameWithCurrentTicks, newPathDowloadedFile);
- //Protect and verify value of objSubCategoriaId and refExterna in app.config. Its necessary your values, to get the processId.
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ObjSubCategoriaIdOfProcess"]))
- {
- throw new ArgumentException("ObjSubCategoriaIdOfProcess in app.config is null or empty");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["RefExternaOfProcess"]))
- {
- throw new ArgumentException("RefExternaOfProcess in app.config is null or empty");
- }
- using (var uow = new UnitOfWorkPortal())
- {
- var integracaoLogService = new IntegracaoLogService(uow);
- GetIntegracaoLog(integracaoLogService, newNameWithCurrentTicks);
- uow.Commit();
- //Delete original file
- System.IO.File.Delete(newNameWithCurrentTicks);
- // Verify if extension is zip or rar. If true, is necessary unzip and get the file.
- // in this case, each zip is a single file compressed.
- if (fileExtension.Equals(FileExtensions.Rar.ReadXmlEnumAttribute()) || fileExtension.Equals(FileExtensions.Zip.ReadXmlEnumAttribute()))
- {
- //unizp the file
- LusoRouxTI.IO.Compression.Compressor.UnzipFile(newPathDowloadedFile, locationDownloadedFiles);
- //delete zip file
- System.IO.File.Delete(newPathDowloadedFile);
- }
- // only get files that finish with .csv
- string[] csvFiles = Directory.GetFiles(locationDownloadedFiles, "*.csv");
- //Process/read csv files in location
- foreach (string csvFilePath in csvFiles)
- {
- ReadAndProcessCSVFile(csvFilePath);
- }
- // Obtenho o numero de erros para este ficheiro, de acordo com o id maior, ou seja o ultimo a ser adicionado (mais recente).
- var numberOfErrors = integracaoLogService.GetByCliExternalId(Path.GetFileName(newNameWithCurrentTicks)).OrderByDescending(x => x.Id).Select(x => x.ErrorCounter).FirstOrDefault();
- // Verificar se error counter deste ficheiro existe e é menor que o numero de erros permitido na app.config.
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ErrorCounter"]))
- {
- throw new ArgumentException("ErrorCounter in app.config is null or empty");
- }
- if (numberOfErrors < int.Parse(System.Configuration.ConfigurationManager.AppSettings["ErrorCounter"]))
- {
- //Mover para pasta de erro
- //string newNameWithCurrentTicks = Path.Combine(filenameWithoutExtension, "_" + datetimeNow + fileExtension);
- //System.IO.File.Move(pathFile, newNameWithCurrentTicks);
- }
- }
- }
- /// <summary>
- /// Devolve um objeto IntegracaoLog.
- /// </summary>
- /// <param name="integracaoLogEstadoId">Correpsonde ao estado do ficheiro, possuindo um dos valores da tabela integracaoLogEstadoId</param>
- /// <param name="fullPath">Corresponde ao caminho completo do ficheiro.</param>
- /// <param name="processoId">Corresponde ao processoId a que este ficheiro pertence</param>
- /// <param name="obs">Contem uma mensagem do Enum IntegracaoLogMessage para compreender o estado do ficheiro.</param>
- /// <param name="errorCounter">Contador de erros, podendo ir no maximo ate 5.</param>
- /// <param name="errorDate">Corresponde à data do fim de qualquer processamento e possuir um erro.</param>
- /// <param name="errorMessage">Corresponde à mensagem de erro.</param>
- /// <param name="dataConfirmacao">Corresponde à data de processamento com sucesso.</param>
- /// <param name="finalPath"> Contém o valor que será guardado em XML Response, que corresponde ao caminho final do ficheiro. Seja ao fim de 5 tentativas e dando erro, ou no caso de sucesso.</param>
- /// <returns></returns>
- private static IntegracaoLog GetNewIntegracaoLog(int integracaoLogEstadoId, string fullPath, int processoId, string obs, int? errorCounter, DateTime? errorDate, string errorMessage, DateTime? dataConfirmacao, string finalPath)
- {
- var integracaoLog = new IntegracaoLog();
- integracaoLog.UtilizadorId = 1;
- integracaoLog.Data = UONDateTime.Now;
- integracaoLog.IntegracaoLogEstadoId = integracaoLogEstadoId;
- integracaoLog.ObjProcessoObjId = processoId;
- integracaoLog.XmlFicheiro = fullPath;
- integracaoLog.CliExternalID = Path.GetFileName(fullPath);
- integracaoLog.Obs = obs;
- integracaoLog.ErrorCounter = errorCounter;
- integracaoLog.ErrorDate = errorDate;
- integracaoLog.ErrorMessage = errorMessage;
- integracaoLog.DataConfirmacao = dataConfirmacao;
- integracaoLog.XMLResponse = finalPath;
- return integracaoLog;
- }
- // TODO -> INCREMETNAR error COUNTER DO INTEGRACAO LOG-> usar getvalueordefault +1
- // TODO -> GETBYNOME DO FICHEIRO (cleExternalid (ex: test.txt)) -> path.getfilename()
- // TODO -> adicionar o path total no xmlFicheiro (do file)
- // TODO -> data confirmacao -> datas de sucesso
- // TODO -> data erro -> data quanto acabar o processamento e tiver algum erro
- // TODO -> xml response -> vai ter o caminho quando atingir as 5 tentativas de erro, ou sucesso
- private static void ReadAndProcessCSVFile(string csvFilePath)
- {
- try
- {
- // Verify if name of columns to be considered is defined
- VerifyColumnsForConsideration();
- // Add information in integrationLog about start processing the file
- using (IUnitOfWork uow = new UnitOfWorkPortal())
- {
- IntegracaoLogService currentIntegracaoLogService = new IntegracaoLogService(uow);
- var integracaoLog = GetIntegracaoLog(currentIntegracaoLogService, csvFilePath);
- integracaoLog.IntegracaoLogEstadoId = 4;
- integracaoLog.Obs = IntegracaoLogMessage.StartProcessingFile.ReadXmlEnumAttribute();
- uow.Commit();
- }
- var fileAspose = new AsposeExcel(csvFilePath);
- // Get column index where is null ,and get the index of necessary columns.
- int columnIndex = 0;
- int columnStateCode1, columnStateCode2, columnStateCode3, columnStateCode4, columnNumeroTel1, columnNumeroTel2, columnNumeroTel3, columnNumeroTel4 = null;
- while (true)
- {
- string columnName = (fileAspose.ReadCell(0, 0, columnIndex) ?? string.Empty).ToString();
- if (string.IsNullOrWhiteSpace(columnName))
- {
- break;
- }
- if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnCodigoProduto"]))
- {
- columnCodigoProdutoIndex = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnDataVencimento"]))
- {
- columnDataVencimentoIndex = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnEmail"]))
- {
- columnEmailIndex = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel1"]))
- {
- columnNumeroTel1 = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel2"]))
- {
- columnNumeroTel2 = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel3"]))
- {
- columnNumeroTel3 = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel4"]))
- {
- columnNumeroTel4 = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode1"]))
- {
- columnStateCode1 = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode2"]))
- {
- columnStateCode2 = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode3"]))
- {
- columnStateCode3 = columnIndex;
- }
- else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode4"]))
- {
- columnStateCode4 = columnIndex;
- }
- columnIndex++;
- }
- // TODO protection of columnStateCode and columnNumeroTel -> try catch
- dictionaryTel.Add(1, new Tuple<int,int>(columnStateCode1, columnNumeroTel1));
- dictionaryTel.Add(2, new Tuple<int, int>(columnStateCode2, columnNumeroTel2));
- dictionaryTel.Add(3, new Tuple<int, int>(columnStateCode3, columnNumeroTel3));
- dictionaryTel.Add(4, new Tuple<int, int>(columnStateCode4, columnNumeroTel4));
- if (columnCodigoProdutoIndex == null)
- {
- throw new Exception("O indice da coluna com o Codigo do Produto não foi identificado. Nome da coluna: ColumnCodigoProduto");
- }
- if (columnDataVencimentoIndex == null)
- {
- throw new Exception("O indice da coluna com a Data de Vencimento não foi identificado. Nome da coluna: ColumnDataVencimento");
- }
- if (columnEmailIndex == null)
- {
- throw new Exception("O indice da coluna com a Email não foi identificado. Nome da coluna: ColumnEmail");
- }
- //TODO codigo produto para lista
- listOfCodeProducts = System.Configuration.ConfigurationManager.AppSettings["ColumnCodigoProduto"].Split(',').ToList();
- //TODO lembrete days before e lembrete days after
- daysBefore = int.Parse(System.Configuration.ConfigurationManager.AppSettings["LembreteDaysBefore"]);
- daysAfter = int.Parse(System.Configuration.ConfigurationManager.AppSettings["LembreteDaysAfter"]);
- //Verificar se existem as configuracoes necessárias no app.config para a coluna de estado.
- //Verificar se existe a coluna de estado criada no ficheiro csv e, se existir, está definido como sendo a ultima coluna.
- int columnStateIndex = columnIndex - 1;
- string columnNameLastColumnWithValue = (fileAspose.ReadCell(0, 0, columnIndex - 1) ?? string.Empty).ToString();
- VerifyColumnUonStateSettings();
- if (!columnNameLastColumnWithValue.Equals(System.Configuration.ConfigurationManager.AppSettings["UonStateColumnName"]))
- {
- // Set column name (in first row)
- fileAspose.WriteCell(0, 0, columnIndex, System.Configuration.ConfigurationManager.AppSettings["UonStateColumnName"]);
- columnStateIndex = columnIndex;
- }
- //Process each row
- for (int rowIndex = 1; rowIndex < fileAspose.TotalRows(0); rowIndex++)
- {
- ProcessRow(fileAspose, rowIndex, columnStateIndex);
- }
- // Verificar se coluna _UON_STATE_ existe
- // Se nao existir, criar/adicionar na posicao 0
- //
- // --> Processa uma linha:
- // -> usar metodo ReadCell
- // ver se coluna CD_PRODUTO com 31501 e 31522
- // e coluna DT_VENCIMENTO compreendido entre UONDateTime.Now - 10 dias e UONDateTime.Now +5 dias -> Tempos são configurados no appconfig
- // Enviar email ou sms
- // Inserir ERRO na coluna se houver algum erro.
- // Ou Inserir IGNORAR se nao se verificar condicao cd_produto e dt_vencimento.
- // Ou Inserir PROCESSADO na coluna se tudo correr bem.
- //
- // Se existir
- // ver se celula da coluna 0 é vazia ou com erro
- // se sim, processar linha
- //No fim ver se ha alguma coluna com ERRO, ou ter um contador que contabiliza o numero de erros.
- // Caso tenha erros incrementa error counter e regista na integracaolog. Se counter ficar a 5, mover para erro.
- // 2 -> receçao documentos
- //integracaologestadoid = 4 -> atualizacao de estado
- //integracaologestadoid = 9 -> envio mensagens
- // integracaologestadoid = 99 ->erro
- // Read each line of csv
- }catch(Exception ex){
- ProcessErrorOfFile(ex, csvFilePath);
- }
- }
- private static void ProcessErrorOfFile(Exception ex, string csvFilePath)
- {
- try
- {
- using (IUnitOfWork uow = new UnitOfWorkPortal())
- {
- IntegracaoLogService currentIntegracaoLogService = new IntegracaoLogService(uow);
- var newIntegracaoLog = GetNewIntegracaoLog(4, csvFilePath, processId, IntegracaoLogMessage.ErrorFile.ReadXmlEnumAttribute(), null, null, null, null, null);
- var currentIntegracaoLog = GetIntegracaoLog(currentIntegracaoLogService, csvFilePath);
- currentIntegracaoLog.IntegracaoLogEstadoId = 99;
- currentIntegracaoLog.ErrorCounter = currentIntegracaoLog.ErrorCounter.GetValueOrDefault() + 1;
- if(currentIntegracaoLog.ErrorCounter >= 5){
- string newFileName = Path.Combine(locationErrorFiles, Path.GetFileName(csvFilePath));
- System.IO.File.Move(csvFilePath, newFileName);
- }
- currentIntegracaoLog.ErrorDate = UONDateTime.Now;
- currentIntegracaoLog.ErrorMessage = ex.GetInnerException().Message;
- uow.Commit();
- }
- }
- catch (Exception newEx){
- try
- {
- log.Error(new LogEntry { Exception = newEx, Tag = "GeneraliCobrança" });
- }
- catch { }
- }
- }
- // if estado 4, estado 99, move para location error.
- private static bool ProcessRow(AsposeExcel fileAspose, int rowIndex, int columnStateIndex)
- {
- try
- {
- if ((fileAspose.ReadCell(0, rowIndex, columnStateIndex) ?? string.Empty).ToString().Equals(UonState.Ignorar.ToString()))
- {
- return true;
- }
- if (listOfCodeProducts.Contains((fileAspose.ReadCell(0, rowIndex, columnCodigoProdutoIndex.Value) ?? string.Empty).ToString()))
- {
- var dataVencimento = GetDateTimeFromObject(fileAspose.ReadCell(0, rowIndex, columnDataVencimentoIndex.Value));
- if (dataVencimento.HasValue)
- {
- var now = UONDateTime.Now;
- // Lembrete
- if ((dataVencimento.Value - now).Days <= daysBefore)
- {
- return SendEmailAndOrSMS(fileAspose, rowIndex, columnStateIndex, LembreteAtraso.Lembrete);
- }
- // Atraso
- else if ((now - dataVencimento.Value).Days <= daysAfter)
- {
- return SendEmailAndOrSMS(fileAspose, rowIndex, columnStateIndex, LembreteAtraso.Atraso);
- }
- // Não interessa
- else
- {
- fileAspose.WriteCell(0, rowIndex, columnStateIndex, UonState.Ignorar.ToString());
- return true;
- }
- }
- else
- {
- fileAspose.WriteCell(0, rowIndex, columnStateIndex, UonState.Ignorar.ToString());
- return true;
- }
- }
- else
- {
- fileAspose.WriteCell(0, rowIndex, columnStateIndex, UonState.Ignorar.ToString());
- return true;
- }
- }
- catch (Exception ex)
- {
- fileAspose.WriteCell(0, rowIndex, columnStateIndex, UonState.Erro.ToString());
- return false;
- }
- }
- private static bool SendEmailAndOrSMS(AsposeExcel fileAspose, int rowIndex, int columnStateIndex, LembreteAtraso lembreteOuAtraso)
- {
- //columnCodigoProdutoIndex, columnDataVencimentoIndex, columnEmailIndex
- // se coluna de email diferent null
- // ir buscar formulario e substituir os valores
- // envia email
- var emailProcessed = SendEmail();
- // metodo que devolve um numero
- // get valid number
- // se numero diferente de null, envio
- // ir buscar a formulario e fazer replace
- // envia sms
- var smsProcessed = SendSMS(processId, message, number);
- UonState state = UonState.Erro;
- if (emailProcessed && smsProcessed)
- {
- state = UonState.Processado;
- }
- else if (emailProcessed)
- {
- state = UonState.ErroSms;
- }
- else if (smsProcessed)
- {
- state = UonState.ErroEmail;
- }
- fileAspose.WriteCell(0, rowIndex, columnStateIndex, state);
- return state == UonState.Processado;
- }
- private static string GetValidPhoneNumber(Dictionary<int, int> dictionaryTel)
- {
- if (dictionaryTel != null)
- {
- foreach (var item in dictionaryTel)
- {
- item.Value
- }
- }
- }
- private static void SendSMS(int processId, string message, string number)
- {
- using (var uow = new UnitOfWorkPortal())
- {
- SettingService currentSettingService = new SettingService(uow);
- using (ISmsProvider smsProvider = Provider.OpenComm(currentSettingService.SmsProviderName, currentSettingService.GetPropValues(currentSettingService.SmsProviderName)))
- {
- using (var uowSms = new UnitOfWorkSMS())
- {
- int serie = new SMS.Business.ServiceProviderService(uowSms).GetSeriesById(smsProvider.Id);
- SmsSendResponse response = smsProvider.Send("Provider Number", number, message, serie);
- new SMS.Business.SmsService(uowSms).Add(response.SmsMessage, processId, null, 1, smsProvider.Id);
- uowSms.Commit();
- }
- }
- }
- }
- private static bool SendEmail()
- {
- return true;
- }
- private static DateTime? GetDateTimeFromObject(object value)
- {
- DateTime result;
- return DateTime.TryParse((value ?? string.Empty).ToString(), CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out result) ? result : (DateTime?)null;
- }
- private static string[] GetFilesPathFromDirectory(string targetDirectory)
- {
- string[] fileEntries = Directory.GetFiles(targetDirectory);
- return fileEntries;
- }
- private static void VerifyColumnUonStateSettings()
- {
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["UonStateColumnName"]))
- {
- throw new ArgumentException("A configuracao UonStateColumnName do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["UonStateErro"]))
- {
- throw new ArgumentException("A configuracao UonStateErro do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["UonStateProcessado"]))
- {
- throw new ArgumentException("A configuracao UonStateProcessado do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["UonStateIgnorar"]))
- {
- throw new ArgumentException("A configuracao UonStateIgnorar do ficheiro App.config é vazio ou nulo.");
- }
- }
- private static void VerifyColumnsForConsideration()
- {
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnCodigoProduto"]))
- {
- throw new Exception("A configuracao ColumnCodigoProduto do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnDataVencimento"]))
- {
- throw new Exception("A configuracao ColumnDataVencimento do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["LembreteDaysBefore"]))
- {
- throw new Exception("A configuracao LembreteDaysBefore do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["LembreteDaysAfter"]))
- {
- throw new Exception("A configuracao LembreteDaysAfter do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["CodigosProduto"]))
- {
- throw new Exception("A configuracao CodigosProduto do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnEmail"]))
- {
- throw new Exception("A configuracao ColumnEmail do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel1"]))
- {
- throw new Exception("A configuracao UColumnNumeroTel1 do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel2"]))
- {
- throw new Exception("A configuracao ColumnNumeroTel2 do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel3"]))
- {
- throw new Exception("A configuracao ColumnNumeroTel3 do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel4"]))
- {
- throw new Exception("A configuracao ColumnNumeroTel4 do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode1"]))
- {
- throw new Exception("A configuracao ColumnStateCode1 do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode2"]))
- {
- throw new Exception("A configuracao ColumnStateCode2 do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode3"]))
- {
- throw new Exception("A configuracao ColumnStateCode3 do ficheiro App.config é vazio ou nulo.");
- }
- if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode4"]))
- {
- throw new Exception("A configuracao ColumnStateCode4 do ficheiro App.config é vazio ou nulo.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement