diff --git a/BLL/Integracion_DGA/BusinessLogic.cs b/BLL/Integracion_DGA/BusinessLogic.cs index e33c379..caecaa2 100644 --- a/BLL/Integracion_DGA/BusinessLogic.cs +++ b/BLL/Integracion_DGA/BusinessLogic.cs @@ -1,228 +1,221 @@ -using Azure; +using System.Text.Json; using DAL; using Microsoft.Extensions.Configuration; -using Shared.DTO; using Shared.DTO.Integracion_DGA; using Shared.DTO.VariablesEntorno; using Shared.Helper; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; namespace BLL.Integracion_DGA { - public class BusinessLogic - { - private readonly IConfiguration _configuration; - private readonly ApiService _apiService; - private readonly JobsDgaRepository _jobs; - private readonly JobsDgaVilosRepository _jobsVilos; - private readonly JobsDgaSupFlujRepository _jobsSupFluj; - private readonly FileLoggerHelper _fileLoggerHelper; - - public BusinessLogic(IConfiguration configuration, ApiService apiService, JobsDgaRepository jobs, JobsDgaVilosRepository jobsVilos, JobsDgaSupFlujRepository jobsSupFluj) { - _configuration = configuration; - _apiService = apiService; - _jobs = jobs; - _jobsVilos = jobsVilos; - _jobsSupFluj = jobsSupFluj; - FileLoggerHelper.ConfigureLogger(_configuration); - } - - public async Task Run() + public class BusinessLogic { + private readonly IConfiguration _configuration; + private readonly ApiService _apiService; + private readonly JobsDgaRepository _jobs; + private readonly JobsDgaVilosRepository _jobsVilos; + private readonly JobsDgaSupFlujRepository _jobsSupFluj; + private readonly FileLoggerHelper _fileLoggerHelper; - DateTimeOffset dateEnd = DateTimeOffset.Now; - DateTimeOffset dateStart = dateEnd.AddHours(-1); + public BusinessLogic(IConfiguration configuration, ApiService apiService, JobsDgaRepository jobs, JobsDgaVilosRepository jobsVilos, JobsDgaSupFlujRepository jobsSupFluj) + { + _configuration = configuration; + _apiService = apiService; + _jobs = jobs; + _jobsVilos = jobsVilos; + _jobsSupFluj = jobsSupFluj; + FileLoggerHelper.ConfigureLogger(_configuration); + } - JsonSerializerOptions options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }; + public async Task Run() + { - //FileLoggerHelper.ConfigureLogger(_configuration); - WriteLineAndLog($"Inicia Proceso DGA"); - try - { - string apiUrlBase = NexusApiUrl.ApiUrl; - Dictionary headers = new Dictionary + DateTimeOffset dateEnd = DateTimeOffset.Now; + DateTimeOffset dateStart = dateEnd.AddHours(-1); + + JsonSerializerOptions options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }; + + //FileLoggerHelper.ConfigureLogger(_configuration); + WriteLineAndLog($"Inicia Proceso DGA"); + try + { + string apiUrlBase = NexusApiUrl.ApiUrl; + Dictionary headers = new Dictionary { { "nexustoken", NexusApiUrl.ApiKey }, { "nexusapiversion", NexusApiUrl.Version }, { "accept", "application/json" } }; - WriteLineAndLog($"Obteniendo Documentos"); - string apiUrlDocuments = apiUrlBase + "/api/Documents"; + WriteLineAndLog($"Obteniendo Documentos"); + string apiUrlDocuments = apiUrlBase + "/api/Documents"; - // Utiliza el servicio para realizar la solicitud a la API con URL y encabezados personalizados - string responseData = await _apiService.GetApiResponseAsync(apiUrlDocuments, headers); + // Utiliza el servicio para realizar la solicitud a la API con URL y encabezados personalizados + string responseData = await _apiService.GetApiResponseAsync(apiUrlDocuments, headers); - var documento = JsonSerializer.Deserialize>(responseData, options); - foreach (DocumentResponse item in documento) - { - WriteLineAndLog($"Obteniendo Tagviews"); - string apiUrlTagViews = $"{apiUrlBase}/api/Documents/tagviews/{item.uid}"; - responseData = await _apiService.GetApiResponseAsync(apiUrlTagViews, headers); - TagviewsResponse tagviews = JsonSerializer.Deserialize(responseData, options); + var documento = JsonSerializer.Deserialize>(responseData, options); + foreach (DocumentResponse item in documento) + { + WriteLineAndLog($"Obteniendo Tagviews"); + string apiUrlTagViews = $"{apiUrlBase}/api/Documents/tagviews/{item.uid}"; + responseData = await _apiService.GetApiResponseAsync(apiUrlTagViews, headers); + TagviewsResponse tagviews = JsonSerializer.Deserialize(responseData, options); - List listTagsID = new List(); - foreach (Column tag in tagviews.Columns) - { - listTagsID.Add(tag.Uid); - } + List listTagsID = new List(); + foreach (Column tag in tagviews.Columns) + { + listTagsID.Add(tag.Uid); + } - HistoricRequest historicRequest = new HistoricRequest(); - historicRequest.DataSource = NexusApiUrl.DataSource; - historicRequest.Resolution = NexusApiUrl.Resolution; - historicRequest.Uids = listTagsID; - historicRequest.StartTs = dateStart.ToUnixTimeSeconds(); - historicRequest.EndTs = dateEnd.ToUnixTimeSeconds(); + HistoricRequest historicRequest = new HistoricRequest(); + historicRequest.DataSource = NexusApiUrl.DataSource; + historicRequest.Resolution = NexusApiUrl.Resolution; + historicRequest.Uids = listTagsID; + historicRequest.StartTs = dateStart.ToUnixTimeSeconds(); + historicRequest.EndTs = dateEnd.ToUnixTimeSeconds(); - WriteLineAndLog($"Obteniendo Tagviews Historic"); - string apiUrlHistoric = $"{apiUrlBase}/api/Documents/tagviews/{item.uid}/historic"; - responseData = await _apiService.PostApiResponseAsync(apiUrlHistoric, headers, historicRequest); - List historicResponse = JsonSerializer.Deserialize>(responseData, options); + WriteLineAndLog($"Obteniendo Tagviews Historic"); + string apiUrlHistoric = $"{apiUrlBase}/api/Documents/tagviews/{item.uid}/historic"; + responseData = await _apiService.PostApiResponseAsync(apiUrlHistoric, headers, historicRequest); + List historicResponse = JsonSerializer.Deserialize>(responseData, options); - List listDgaMacroResultados = new List(); - foreach (Column tag in tagviews.Columns) - { - IEnumerable filter = historicResponse.Where(h => h.Uid == tag.Uid); - foreach (HistoricResponse historic in filter) - { - TimeZoneInfo zonaHorariaChile = TimeZoneInfo.FindSystemTimeZoneById("Pacific SA Standard Time"); - DateTime now = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(historic.TimeStamp); - DateTime fechaHoraChile = TimeZoneInfo.ConvertTimeFromUtc(now, zonaHorariaChile); + List listDgaMacroResultados = new List(); + foreach (Column tag in tagviews.Columns) + { + IEnumerable filter = historicResponse.Where(h => h.Uid == tag.Uid); + foreach (HistoricResponse historic in filter) + { + TimeZoneInfo zonaHorariaChile = TimeZoneInfo.FindSystemTimeZoneById("Pacific SA Standard Time"); + DateTime now = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(historic.TimeStamp); + DateTime fechaHoraChile = TimeZoneInfo.ConvertTimeFromUtc(now, zonaHorariaChile); - DgaMacroResultado dgaMacroResultado = new DgaMacroResultado(); - dgaMacroResultado.TagName = $"SCADA001.{tag.Name}.F_CV"; - dgaMacroResultado.Value = historic.Value; - //dgaMacroResultado.TimeStamp = new DateTime(historic.TimeStamp); - dgaMacroResultado.TimeStamp = fechaHoraChile; + DgaMacroResultado dgaMacroResultado = new DgaMacroResultado(); + dgaMacroResultado.TagName = $"SCADA001.{tag.Name}.F_CV"; + dgaMacroResultado.Value = historic.Value; + //dgaMacroResultado.TimeStamp = new DateTime(historic.TimeStamp); + dgaMacroResultado.TimeStamp = fechaHoraChile; - listDgaMacroResultados.Add(dgaMacroResultado); + listDgaMacroResultados.Add(dgaMacroResultado); + } + } + + /**************/ + WriteLineAndLog($"Inicia Envio DGA", ConsoleColor.Green); + WriteLineAndLog($"\t Descargar datos historian: Insertar DgaMacroResultado"); + var resultMacro = await _jobs.InsertarDgaMacroResultado(listDgaMacroResultados); + + WriteLineAndLog($"\t Descargar datos historian: Insertar DgaSensorResultado"); + List listDgaSensorResultado = listDgaMacroResultados.Select(item => new DgaSensorResultado + { + TagName = item.TagName, + TimeStamp = item.TimeStamp, + Value = item.Value, + Quality = item.Quality + }).ToList(); + + var resultSensor = await _jobs.InsertarDgaSensorResultado(listDgaSensorResultado); + + WriteLineAndLog($"\t Calculo DGA"); + var resultCalculo = await _jobs.SpCalculoDga(); + + WriteLineAndLog($"\t descargar datos suma reversibilidad : Insertar DgaMacroResultadoSupFlujSuma"); + List listDgaMacroResultadoSupFlujSuma = listDgaMacroResultados.Select(item => new DgaMacroResultadoSupFlujSuma + { + TagName = item.TagName, + TimeStamp = item.TimeStamp, + Value = item.Value, + Quality = item.Quality + }).ToList(); + + var resultSupFlujSuma = await _jobs.InsertarDgaMacroResultadoSupFlujSuma(listDgaMacroResultadoSupFlujSuma); + + WriteLineAndLog($"\t Calculo Suma"); + var resultCalculoDgaSup = await _jobs.SpCalculoDgaSupFlujSumaSnreversibilidad(); + + + WriteLineAndLog($"\t Traspaso datos achird"); + var result = await _jobs.SpTraspasoDatosAchird(); + WriteLineAndLog($"Fin Envio DGA", ConsoleColor.Green); + /**************/ + /**************/ + WriteLineAndLog($"Inicio Envio DGA Vilos", ConsoleColor.Green); + WriteLineAndLog($"\t Descargar datos historian: Insertar InsertarDgaMacroResultadoVilos"); + List listDgaMacroResultadoVilos = listDgaMacroResultados.Select(item => new DgaMacroResultadoVilos + { + TagName = item.TagName, + TimeStamp = item.TimeStamp, + Value = item.Value, + Quality = item.Quality + }).ToList(); + + var resultVilos = await _jobsVilos.InsertarDgaMacroResultadoVilos(listDgaMacroResultadoVilos); + + WriteLineAndLog($"\t Descargar datos historian: Insertar InsertarDgaSensorResultadoVilos"); + List listDgaSensorResultadoVilos = listDgaMacroResultados.Select(item => new DgaSensorResultadoVilos + { + TagName = item.TagName, + TimeStamp = item.TimeStamp, + Value = item.Value, + Quality = item.Quality + }).ToList(); + + var resultSensorVilos = await _jobsVilos.InsertarDgaSensorResultadoVilos(listDgaSensorResultadoVilos); + + WriteLineAndLog($"\t Calculo Suma"); + var resultCalculoVilos = await _jobsVilos.SpCalculoDgaVilos(); + + + WriteLineAndLog($"\t Traspaso datos achird"); + var resultAchirdVilos = await _jobsVilos.SpTraspasoDatosAchirdVilos(); + WriteLineAndLog($"Fin Envio DGA Vilos", ConsoleColor.Green); + /**************/ + /**************/ + WriteLineAndLog($"Inicio Envio DGA Sup Fluj", ConsoleColor.Green); + WriteLineAndLog($"\t Descargar datos historian: Insertar InsertarDgaMacroResultadoSupFluj"); + List listDgaMacroResultadoSupFluj = listDgaMacroResultados.Select(item => new DgaMacroResultadoSupFluj + { + TagName = item.TagName, + TimeStamp = item.TimeStamp, + Value = item.Value, + Quality = item.Quality + }).ToList(); + + var resultSensorSup = await _jobsSupFluj.InsertarDgaMacroResultadoSupFluj(listDgaMacroResultadoSupFluj); + + WriteLineAndLog($"\t Calculo Suma"); + var resultCalculoSup = await _jobsSupFluj.SpCalculoDgaSupFluj(); + + + WriteLineAndLog($"\t Traspaso datos achird"); + var resultAchirdSup = await _jobsSupFluj.SpTraspasoDatosAchirdSupFluj(); + WriteLineAndLog($"Fin Envio DGA Sup Fluj", ConsoleColor.Green); + /**************/ + /**************/ + } + WriteLineAndLog($"FIN Proceso DGA"); + } + catch (Exception ex) + { + FileLoggerHelper.LogError($"{ex.Message}", ex); + WriteLineAndLog($"{ex.Message}", ConsoleColor.Red); } - } - /**************/ - WriteLineAndLog($"Inicia Envio DGA", ConsoleColor.Green); - WriteLineAndLog($"\t Descargar datos historian: Insertar DgaMacroResultado"); - var resultMacro = await _jobs.InsertarDgaMacroResultado(listDgaMacroResultados); - - WriteLineAndLog($"\t Descargar datos historian: Insertar DgaSensorResultado"); - List listDgaSensorResultado = listDgaMacroResultados.Select(item => new DgaSensorResultado - { - TagName = item.TagName, - TimeStamp = item.TimeStamp, - Value = item.Value, - Quality = item.Quality - }).ToList(); - - var resultSensor = await _jobs.InsertarDgaSensorResultado(listDgaSensorResultado); - - WriteLineAndLog($"\t Calculo DGA"); - var resultCalculo = await _jobs.SpCalculoDga(); - - WriteLineAndLog($"\t descargar datos suma reversibilidad : Insertar DgaMacroResultadoSupFlujSuma"); - List listDgaMacroResultadoSupFlujSuma = listDgaMacroResultados.Select(item => new DgaMacroResultadoSupFlujSuma - { - TagName = item.TagName, - TimeStamp = item.TimeStamp, - Value = item.Value, - Quality = item.Quality - }).ToList(); - - var resultSupFlujSuma = await _jobs.InsertarDgaMacroResultadoSupFlujSuma(listDgaMacroResultadoSupFlujSuma); - - WriteLineAndLog($"\t Calculo Suma"); - var resultCalculoDgaSup = await _jobs.SpCalculoDgaSupFlujSumaSnreversibilidad(); - - - WriteLineAndLog($"\t Traspaso datos achird"); - var result = await _jobs.SpTraspasoDatosAchird(); - WriteLineAndLog($"Fin Envio DGA", ConsoleColor.Green); - /**************/ - /**************/ - WriteLineAndLog($"Inicio Envio DGA Vilos", ConsoleColor.Green); - WriteLineAndLog($"\t Descargar datos historian: Insertar InsertarDgaMacroResultadoVilos"); - List listDgaMacroResultadoVilos = listDgaMacroResultados.Select(item => new DgaMacroResultadoVilos - { - TagName = item.TagName, - TimeStamp = item.TimeStamp, - Value = item.Value, - Quality = item.Quality - }).ToList(); - - var resultVilos = await _jobsVilos.InsertarDgaMacroResultadoVilos(listDgaMacroResultadoVilos); - - WriteLineAndLog($"\t Descargar datos historian: Insertar InsertarDgaSensorResultadoVilos"); - List listDgaSensorResultadoVilos = listDgaMacroResultados.Select(item => new DgaSensorResultadoVilos - { - TagName = item.TagName, - TimeStamp = item.TimeStamp, - Value = item.Value, - Quality = item.Quality - }).ToList(); - - var resultSensorVilos = await _jobsVilos.InsertarDgaSensorResultadoVilos(listDgaSensorResultadoVilos); - - WriteLineAndLog($"\t Calculo Suma"); - var resultCalculoVilos = await _jobsVilos.SpCalculoDgaVilos(); - - - WriteLineAndLog($"\t Traspaso datos achird"); - var resultAchirdVilos = await _jobsVilos.SpTraspasoDatosAchirdVilos(); - WriteLineAndLog($"Fin Envio DGA Vilos", ConsoleColor.Green); - /**************/ - /**************/ - WriteLineAndLog($"Inicio Envio DGA Sup Fluj", ConsoleColor.Green); - WriteLineAndLog($"\t Descargar datos historian: Insertar InsertarDgaMacroResultadoSupFluj"); - List listDgaMacroResultadoSupFluj = listDgaMacroResultados.Select(item => new DgaMacroResultadoSupFluj - { - TagName = item.TagName, - TimeStamp = item.TimeStamp, - Value = item.Value, - Quality = item.Quality - }).ToList(); - - var resultSensorSup = await _jobsSupFluj.InsertarDgaMacroResultadoSupFluj(listDgaMacroResultadoSupFluj); - - WriteLineAndLog($"\t Calculo Suma"); - var resultCalculoSup = await _jobsSupFluj.SpCalculoDgaSupFluj(); - - - WriteLineAndLog($"\t Traspaso datos achird"); - var resultAchirdSup = await _jobsSupFluj.SpTraspasoDatosAchirdSupFluj(); - WriteLineAndLog($"Fin Envio DGA Sup Fluj", ConsoleColor.Green); - /**************/ - /**************/ } - WriteLineAndLog($"FIN Proceso DGA"); - } - catch (Exception ex) - { - FileLoggerHelper.LogError($"{ex.Message}", ex); - WriteLineAndLog($"{ex.Message}", ConsoleColor.Red); - } - } + static void WriteLineAndLog(string msj, ConsoleColor? color = null) + { + if (color.HasValue && Enum.IsDefined(typeof(ConsoleColor), color.Value)) + { + Console.ForegroundColor = (ConsoleColor)color; + Console.WriteLine(msj); + Console.ResetColor(); + } + else + { + Console.WriteLine($"{msj}"); + } - static void WriteLineAndLog(string msj, ConsoleColor? color = null) - { - if (color.HasValue && Enum.IsDefined(typeof(ConsoleColor), color.Value)) - { - Console.ForegroundColor = (ConsoleColor)color; - Console.WriteLine(msj); - Console.ResetColor(); - } - else - { - Console.WriteLine($"{msj}"); - } - - FileLoggerHelper.LogInformation($"{msj}"); + FileLoggerHelper.LogInformation($"{msj}"); + } } - } } diff --git a/BLL/Recuperacion_DGA/EnvioDGA.cs b/BLL/Recuperacion_DGA/EnvioDGA.cs index 476d3cb..32d61ac 100644 --- a/BLL/Recuperacion_DGA/EnvioDGA.cs +++ b/BLL/Recuperacion_DGA/EnvioDGA.cs @@ -1,24 +1,28 @@ -using Microsoft.Extensions.Configuration; -using Shared.DTO; -using DAL; +using DAL; using DAS; using Shared.DTO.Envios_DGA; +using Shared.DTO.VariablesEntorno; +using Shared.Helper; namespace BLL.Recuperacion_DGA { public class EnvioDGA { private readonly MedicionScadaRepository _dGAMedicionScadaRepository; + private readonly MedicionScadaVilosRepository _dgaMedicionScadaVilosRepository; private readonly RegistrarMedicion _registrarMedicion; - public EnvioDGA(MedicionScadaRepository dGAMedicionScadaRepository, RegistrarMedicion registrarMedicion) + public EnvioDGA(MedicionScadaRepository dGAMedicionScadaRepository, RegistrarMedicion registrarMedicion, MedicionScadaVilosRepository dgaMedicionScadaVilosRepository) { _dGAMedicionScadaRepository = dGAMedicionScadaRepository; _registrarMedicion = registrarMedicion; + _dgaMedicionScadaVilosRepository = dgaMedicionScadaVilosRepository; } - public async TaskRegistrarMedicionesAsync() + public async Task RegistrarMedicionesAsync() { + WriteLineAndLog("Iniciando el proceso de recuperación DGA..."); + WriteLineAndLog("Obteniendo Mediciones Scada", ConsoleColor.Green); var mediciones = await _dGAMedicionScadaRepository.ObtenerMedicionesAsync(); foreach (var medicion in mediciones) @@ -27,38 +31,114 @@ namespace BLL.Recuperacion_DGA { if (!string.IsNullOrEmpty(medicion.Code)) { + var rutEmpresa = string.Empty; + if (medicion.tipo_empresa == null) + { + continue; + } + if (medicion.tipo_empresa == "AV") + { + rutEmpresa = CredencialDGA.RutAv; + } + if (medicion.tipo_empresa =="EV") + { + rutEmpresa = CredencialDGA.RutEsval; + } + + + var body = new MedicionSubterraneaRequest { Autenticacion = new Autenticacion { - Password = string.Empty, - RutEmpresa = string.Empty, - RutUsuario = string.Empty + Password = CredencialDGA.Password, + RutEmpresa = rutEmpresa, + RutUsuario = CredencialDGA.RutUsuario }, MedicionSubterranea = new Medicion { Caudal = medicion.Caudal.ToString() ?? "", FechaMedicion = medicion.DateOrigen?.ToString("yyyy-MM-dd") ?? "", HoraMedicion = medicion.DateOrigen?.ToString("HH:mm:ss") ?? "", - NivelFreaticoDelPozo = "", + NivelFreaticoDelPozo = medicion.Nivel.ToString() ?? "", Totalizador = medicion.Totalizador.ToString() ?? "", } }; - - //TODO: Agregar log texto - - await _registrarMedicion.EnviarMedicionAsync(medicion.Code, body,medicion.Id); + await _registrarMedicion.EnviarMedicionAsync(medicion.Code, body, medicion.Id); } } - catch (Exception) + catch (Exception ex) { - //TODO: Agregar log texto - throw; + FileLoggerHelper.LogError($"[Error] {ex.Message}.",ex); + WriteLineAndLog($"Error al enviar la medición con ID {medicion.Code}.", ConsoleColor.Red); + } + } + + var medicionesVilos = await _dgaMedicionScadaVilosRepository.ObtenerMedicionesVilosAsync(); + foreach (var medicionVilos in medicionesVilos) + { + try + { + if (!string.IsNullOrEmpty(medicionVilos.Code)) + { + var rutEmpresa = string.Empty; + + if (medicionVilos.tipo_empresa.Equals("AV")) + { + rutEmpresa = CredencialDGA.RutAv; + } + else if (medicionVilos.tipo_empresa.Equals("EV")) + { + rutEmpresa = CredencialDGA.RutEsval; + } + + var body = new MedicionSubterraneaRequest + { + Autenticacion = new Autenticacion + { + Password = CredencialDGA.Password, + RutEmpresa = rutEmpresa, + RutUsuario = CredencialDGA.RutUsuario + }, + MedicionSubterranea = new Medicion + { + Caudal = medicionVilos.Caudal.ToString() ?? "", + FechaMedicion = medicionVilos.DateOrigen?.ToString("yyyy-MM-dd") ?? "", + HoraMedicion = medicionVilos.DateOrigen?.ToString("HH:mm:ss") ?? "", + NivelFreaticoDelPozo = medicionVilos.Nivel.ToString() ?? "", + Totalizador = medicionVilos.Totalizador.ToString() ?? "", + } + }; + + await _registrarMedicion.EnviarMedicionAsync(medicionVilos.Code, body, medicionVilos.Id); + } + + } + catch (Exception ex) + { + FileLoggerHelper.LogError($"[Error] {ex.Message}.", ex); + WriteLineAndLog($"Error al enviar la medición vilos con ID {medicionVilos.Code}.", ConsoleColor.Red); } } return true; } + + static void WriteLineAndLog(string msj, ConsoleColor? color = null) + { + if (color.HasValue && Enum.IsDefined(typeof(ConsoleColor), color.Value)) + { + Console.ForegroundColor = (ConsoleColor)color; + Console.WriteLine(msj); + Console.ResetColor(); + } + else + { + Console.WriteLine($"{msj}"); + } + + FileLoggerHelper.LogInformation($"{msj}"); + } } } diff --git a/DAL/Encriptador.cs b/DAL/Encriptador.cs index 3153883..96812f0 100644 --- a/DAL/Encriptador.cs +++ b/DAL/Encriptador.cs @@ -1,58 +1,54 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; +using System.Security.Cryptography; using System.Text; -using System.Threading.Tasks; namespace DAL { - public static class Encriptador - { - private static readonly byte[] key = Encoding.ASCII.GetBytes("1234567891234567"); - private static readonly byte[] iv = Encoding.ASCII.GetBytes("Devjoker7.37hAES"); - - public static string Encripta(string Cadena) + public static class Encriptador { + private static readonly byte[] key = Encoding.ASCII.GetBytes("1234567891234567"); + private static readonly byte[] iv = Encoding.ASCII.GetBytes("Devjoker7.37hAES"); - using Aes aesAlg = Aes.Create(); - aesAlg.Key = key; - aesAlg.IV = iv; - - ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); - - using (MemoryStream msEncrypt = new MemoryStream()) - { - using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) + public static string Encripta(string Cadena) { - using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) - { - swEncrypt.Write(Cadena); - } + + using Aes aesAlg = Aes.Create(); + aesAlg.Key = key; + aesAlg.IV = iv; + + ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); + + using (MemoryStream msEncrypt = new MemoryStream()) + { + using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) + { + using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) + { + swEncrypt.Write(Cadena); + } + } + + return Convert.ToBase64String(msEncrypt.ToArray()); + } } - return Convert.ToBase64String(msEncrypt.ToArray()); - } - } - - public static string Desencripta(string Cadena) - { - using Aes aesAlg = Aes.Create(); - aesAlg.Key = key; - aesAlg.IV = iv; - - ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); - - using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(Cadena))) - { - using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) + public static string Desencripta(string Cadena) { - using (StreamReader srDecrypt = new StreamReader(csDecrypt)) - { - return srDecrypt.ReadToEnd(); - } + using Aes aesAlg = Aes.Create(); + aesAlg.Key = key; + aesAlg.IV = iv; + + ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); + + using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(Cadena))) + { + using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) + { + using (StreamReader srDecrypt = new StreamReader(csDecrypt)) + { + return srDecrypt.ReadToEnd(); + } + } + } } - } } - } } diff --git a/DAL/JobsDgaRepository.cs b/DAL/JobsDgaRepository.cs index 31d1504..c173b73 100644 --- a/DAL/JobsDgaRepository.cs +++ b/DAL/JobsDgaRepository.cs @@ -1,20 +1,13 @@ -using Microsoft.Data.SqlClient; -using Microsoft.Win32; -using Shared.DTO.Integracion_DGA; -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Data; using Dapper; -using Microsoft.Extensions.Configuration; +using Microsoft.Data.SqlClient; +using Shared.DTO.Integracion_DGA; using Shared.DTO.VariablesEntorno; namespace DAL { - public class JobsDgaRepository - { + public class JobsDgaRepository + { public async Task InsertarDgaMacroResultado(List dgaMacroResultados) { try @@ -66,29 +59,30 @@ namespace DAL public async Task InsertarDgaMacroResultadoSupFlujSuma(List dgaMacroResultadoSupFlujSuma) { - try - { - // Configurar la conexión a la base de datos - using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection)) + try { - await connection.OpenAsync(); - // Truncar la tabla antes de insertar - await connection.ExecuteAsync("TRUNCATE TABLE DGA_MACRO_RESULTADO_SUP_FLUJ_SUMA"); + // Configurar la conexión a la base de datos + using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection)) + { + await connection.OpenAsync(); + // Truncar la tabla antes de insertar + await connection.ExecuteAsync("TRUNCATE TABLE DGA_MACRO_RESULTADO_SUP_FLUJ_SUMA"); - // Crear un adaptador de datos - SqlDataAdapter adapter = new SqlDataAdapter(); + // Crear un adaptador de datos + SqlDataAdapter adapter = new SqlDataAdapter(); - // Configurar el comando de inserción - string sql = "INSERT INTO DGA_MACRO_RESULTADO_SUP_FLUJ_SUMA (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)"; - await connection.ExecuteAsync(sql, dgaMacroResultadoSupFlujSuma); + // Configurar el comando de inserción + string sql = "INSERT INTO DGA_MACRO_RESULTADO_SUP_FLUJ_SUMA (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)"; + await connection.ExecuteAsync(sql, dgaMacroResultadoSupFlujSuma); - return true; // Éxito + return true; // Éxito + } } - }catch (Exception ex) - { - throw new Exception($"Error: {ex.Message}"); - } - } + catch (Exception ex) + { + throw new Exception($"Error: {ex.Message}"); + } + } public async Task SpCalculoDga() { diff --git a/DAL/JobsDgaSupFlujRepository.cs b/DAL/JobsDgaSupFlujRepository.cs index 4245aaa..b217349 100644 --- a/DAL/JobsDgaSupFlujRepository.cs +++ b/DAL/JobsDgaSupFlujRepository.cs @@ -1,80 +1,74 @@ -using Dapper; +using System.Data; +using Dapper; using Microsoft.Data.SqlClient; -using Microsoft.Extensions.Configuration; using Shared.DTO.Integracion_DGA; using Shared.DTO.VariablesEntorno; -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DAL { - public class JobsDgaSupFlujRepository - { - public async Task InsertarDgaMacroResultadoSupFluj(List dgaMacroResultadoSupFluj) + public class JobsDgaSupFlujRepository { - try - { - // Configurar la conexión a la base de datos - using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection)) + public async Task InsertarDgaMacroResultadoSupFluj(List dgaMacroResultadoSupFluj) { - await connection.OpenAsync(); - await connection.ExecuteAsync("TRUNCATE TABLE DGA_MACRO_RESULTADO_SUP_FLUJ"); - - await SpCalculoDgaSupFluj(); - - string sql = "INSERT INTO DGA_MACRO_RESULTADO_SUP_FLUJ (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)"; - await connection.ExecuteAsync(sql, dgaMacroResultadoSupFluj); - return true; - } - } - catch (Exception ex) - { - throw new Exception($"Error: {ex.Message}"); - } - } - - public async Task SpCalculoDgaSupFluj() - { - try - { - using (var connection = new SqlConnection(BdConexion.StringConnection)) + try { - await connection.OpenAsync(); - await connection.ExecuteAsync( - "SP_CALCULO_DGA_SUP_FLUJ", - commandType: CommandType.StoredProcedure - ); - } - return true; // Éxito - } - catch (Exception ex) - { - throw new Exception($"Error: {ex.Message}"); - } - } + // Configurar la conexión a la base de datos + using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection)) + { + await connection.OpenAsync(); + await connection.ExecuteAsync("TRUNCATE TABLE DGA_MACRO_RESULTADO_SUP_FLUJ"); - public async Task SpTraspasoDatosAchirdSupFluj() - { - try - { - using (var connection = new SqlConnection(BdConexion.StringConnection)) - { - await connection.OpenAsync(); - await connection.ExecuteAsync( - "SP_TRASPASO_DATOS_ACHIRD_SUP_FLUJ", - commandType: CommandType.StoredProcedure - ); + await SpCalculoDgaSupFluj(); + + string sql = "INSERT INTO DGA_MACRO_RESULTADO_SUP_FLUJ (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)"; + await connection.ExecuteAsync(sql, dgaMacroResultadoSupFluj); + return true; + } + } + catch (Exception ex) + { + throw new Exception($"Error: {ex.Message}"); } - return true; // Éxito } - catch (Exception ex) + + public async Task SpCalculoDgaSupFluj() { - throw new Exception($"Error: {ex.Message}"); + try + { + using (var connection = new SqlConnection(BdConexion.StringConnection)) + { + await connection.OpenAsync(); + await connection.ExecuteAsync( + "SP_CALCULO_DGA_SUP_FLUJ", + commandType: CommandType.StoredProcedure + ); + } + return true; // Éxito + } + catch (Exception ex) + { + throw new Exception($"Error: {ex.Message}"); + } + } + + public async Task SpTraspasoDatosAchirdSupFluj() + { + try + { + using (var connection = new SqlConnection(BdConexion.StringConnection)) + { + await connection.OpenAsync(); + await connection.ExecuteAsync( + "SP_TRASPASO_DATOS_ACHIRD_SUP_FLUJ", + commandType: CommandType.StoredProcedure + ); + } + return true; // Éxito + } + catch (Exception ex) + { + throw new Exception($"Error: {ex.Message}"); + } } - } } } diff --git a/DAL/JobsDgaVilosRepository.cs b/DAL/JobsDgaVilosRepository.cs index 66d67e1..606cdf2 100644 --- a/DAL/JobsDgaVilosRepository.cs +++ b/DAL/JobsDgaVilosRepository.cs @@ -1,14 +1,8 @@ -using Dapper; +using System.Data; +using Dapper; using Microsoft.Data.SqlClient; -using Microsoft.Extensions.Configuration; using Shared.DTO.Integracion_DGA; using Shared.DTO.VariablesEntorno; -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DAL { diff --git a/DAL/LogMedicionScadaRepository.cs b/DAL/LogMedicionScadaRepository.cs index 1e8e8de..e7a67a0 100644 --- a/DAL/LogMedicionScadaRepository.cs +++ b/DAL/LogMedicionScadaRepository.cs @@ -1,11 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Dapper; +using Dapper; using Microsoft.Data.SqlClient; -using Microsoft.Extensions.Configuration; using Shared.DTO.Envios_DGA; using Shared.DTO.VariablesEntorno; diff --git a/DAL/MedicionScadaRepository.cs b/DAL/MedicionScadaRepository.cs index d29b842..fd52a57 100644 --- a/DAL/MedicionScadaRepository.cs +++ b/DAL/MedicionScadaRepository.cs @@ -1,9 +1,8 @@ -using Dapper; +using System.Data; +using Dapper; using Microsoft.Data.SqlClient; -using Microsoft.Extensions.Configuration; using Shared.DTO.Envios_DGA; using Shared.DTO.VariablesEntorno; -using System.Data; namespace DAL { diff --git a/DAL/MedicionScadaVilosRepository.cs b/DAL/MedicionScadaVilosRepository.cs new file mode 100644 index 0000000..be66e4b --- /dev/null +++ b/DAL/MedicionScadaVilosRepository.cs @@ -0,0 +1,22 @@ +using System.Data; +using Dapper; +using Microsoft.Data.SqlClient; +using Shared.DTO.Envios_DGA; +using Shared.DTO.VariablesEntorno; + +namespace DAL +{ + public class MedicionScadaVilosRepository + { + public async Task> ObtenerMedicionesVilosAsync() + { + await using var connection = new SqlConnection(BdConexion.StringConnection); + + var result = await connection.QueryAsync( + "SP_OBTENER_MEDICION_SMARTSCADA_OPERACION_VILOS", + commandType: CommandType.StoredProcedure); + + return result.ToList(); + } + } +} diff --git a/DAS/ApiService.cs b/DAS/ApiService.cs index 55da9ce..5af3017 100644 --- a/DAS/ApiService.cs +++ b/DAS/ApiService.cs @@ -3,106 +3,107 @@ using Newtonsoft.Json; namespace BLL.Integracion_DGA { - public class ApiService - { - private readonly HttpClient _httpClient; - - public ApiService(HttpClient httpClient) + public class ApiService { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - } + private readonly HttpClient _httpClient; - public async Task GetApiResponseAsync(string apiUrl, Dictionary headers = null) - { - - using (var httpClient = new HttpClient()) - { - // Configura la URL base - httpClient.BaseAddress = new Uri(apiUrl); - - var request = new HttpRequestMessage(HttpMethod.Get, apiUrl); - - // Configura los encabezados personalizados si se proporcionan - if (headers != null) + public ApiService(HttpClient httpClient) { - foreach (var header in headers) - { - request.Headers.Add(header.Key, header.Value); - } + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); } - // Realiza la solicitud con la solicitud personalizada - try + public async Task GetApiResponseAsync(string apiUrl, Dictionary headers = null) { - var response = await httpClient.SendAsync(request); - if (response.IsSuccessStatusCode) - { - return await response.Content.ReadAsStringAsync(); - } - else - { - // Maneja errores aquí según sea necesario. - Console.WriteLine($"Error en la solicitud: {response.StatusCode}"); - throw new HttpRequestException($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); - } - }catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - throw new Exception($"Error en la solicitud HTTP: {ex.Message}"); - // Maneja la excepción según sea necesario - } - } - } - public async Task PostApiResponseAsync(string apiUrl, Dictionary headers = null, object data = null) - { - using (var httpClient = new HttpClient()) - { - try - { - httpClient.BaseAddress = new Uri(apiUrl); - var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); - - // Serializa el objeto data a JSON - //string jsonData = JsonSerializer.Serialize(data); - string jsonData = JsonConvert.SerializeObject(data); - // Crea el contenido de la solicitud HTTP con el cuerpo JSON - HttpContent contenido = new StringContent(jsonData, Encoding.UTF8, "application/json"); - request.Content = contenido; - - // Configura los encabezados personalizados si se proporcionan - if (headers != null) - { - foreach (var header in headers) + using (var httpClient = new HttpClient()) { - request.Headers.Add(header.Key, header.Value); + // Configura la URL base + httpClient.BaseAddress = new Uri(apiUrl); + + var request = new HttpRequestMessage(HttpMethod.Get, apiUrl); + + // Configura los encabezados personalizados si se proporcionan + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + // Realiza la solicitud con la solicitud personalizada + try + { + var response = await httpClient.SendAsync(request); + if (response.IsSuccessStatusCode) + { + return await response.Content.ReadAsStringAsync(); + } + else + { + // Maneja errores aquí según sea necesario. + Console.WriteLine($"Error en la solicitud: {response.StatusCode}"); + throw new HttpRequestException($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + throw new Exception($"Error en la solicitud HTTP: {ex.Message}"); + // Maneja la excepción según sea necesario + } } - } - - // Realiza la solicitud POST - HttpResponseMessage response = await httpClient.SendAsync(request); - - // Verifica si la solicitud fue exitosa - if (response.IsSuccessStatusCode) - { - // Lee la respuesta como una cadena - return await response.Content.ReadAsStringAsync(); - } - else - { - // La solicitud no fue exitosa, maneja el error según sea necesario - Console.WriteLine($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); - throw new HttpRequestException($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); - } } - catch (Exception ex) + + public async Task PostApiResponseAsync(string apiUrl, Dictionary headers = null, object data = null) { - // Maneja excepciones si ocurren - Console.WriteLine($"Error en la solicitud HTTP: {ex.Message}"); - throw new Exception($"Error en la solicitud HTTP: {ex.Message}"); + using (var httpClient = new HttpClient()) + { + try + { + httpClient.BaseAddress = new Uri(apiUrl); + var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); + + // Serializa el objeto data a JSON + //string jsonData = JsonSerializer.Serialize(data); + string jsonData = JsonConvert.SerializeObject(data); + // Crea el contenido de la solicitud HTTP con el cuerpo JSON + HttpContent contenido = new StringContent(jsonData, Encoding.UTF8, "application/json"); + request.Content = contenido; + + // Configura los encabezados personalizados si se proporcionan + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + // Realiza la solicitud POST + HttpResponseMessage response = await httpClient.SendAsync(request); + + // Verifica si la solicitud fue exitosa + if (response.IsSuccessStatusCode) + { + // Lee la respuesta como una cadena + return await response.Content.ReadAsStringAsync(); + } + else + { + // La solicitud no fue exitosa, maneja el error según sea necesario + Console.WriteLine($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); + throw new HttpRequestException($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); + } + } + catch (Exception ex) + { + // Maneja excepciones si ocurren + Console.WriteLine($"Error en la solicitud HTTP: {ex.Message}"); + throw new Exception($"Error en la solicitud HTTP: {ex.Message}"); + } + } } - } } - } } diff --git a/DAS/RegistrarMedicion.cs b/DAS/RegistrarMedicion.cs index f027fb8..531c5fc 100644 --- a/DAS/RegistrarMedicion.cs +++ b/DAS/RegistrarMedicion.cs @@ -1,13 +1,12 @@ -using DAL; -using Microsoft.Extensions.Configuration; +using System.Text; +using System.Text.Json; +using DAL; using Shared.DTO.Envios_DGA; using Shared.DTO.VariablesEntorno; -using System.Text; -using System.Text.Json; namespace DAS { - public class RegistrarMedicion + public class RegistrarMedicion { private readonly HttpClient _httpClient; private readonly LogMedicionScadaRepository _logMedicionScadaRepository; @@ -20,10 +19,6 @@ namespace DAS public async Task EnviarMedicionAsync(string codigoObra, MedicionSubterraneaRequest request, long idMedicion) { - request.Autenticacion.Password = CredencialDGA.Password; - request.Autenticacion.RutEmpresa = CredencialDGA.RutEmpresa; //TODO: condicionar rut empresa - request.Autenticacion.RutUsuario = CredencialDGA.RutUsuario; - var timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss-0000"); var json = JsonSerializer.Serialize(request); @@ -32,7 +27,7 @@ namespace DAS content.Headers.Add("codigoObra", codigoObra); content.Headers.Add("timeStampOrigen", timeStamp); - var response = await _httpClient.PostAsync($"{SubterraneaApiUrl.BaseUrl}{SubterraneaApiUrl.EndPoint}", content); + /*var response = await _httpClient.PostAsync($"{SubterraneaApiUrl.BaseUrl}{SubterraneaApiUrl.EndPoint}", content); string jsonRecibido = await response.Content.ReadAsStringAsync(); string estado = response.IsSuccessStatusCode ? "OK" : "ERROR"; string comprobante = string.Empty; @@ -62,10 +57,10 @@ namespace DAS FechaEnvio = DateTime.UtcNow, IdMedicionSmartscadaOperacion = idMedicion }; + */ + //await _logMedicionScadaRepository.InsertarLogMedicionScadaAsync(logMedicionScada); - await _logMedicionScadaRepository.InsertarLogMedicionScadaAsync(logMedicionScada); - - return response.IsSuccessStatusCode; + return true; } } } diff --git a/Integracion_DGA/Program.cs b/Integracion_DGA/Program.cs index 3c54774..328d5ac 100644 --- a/Integracion_DGA/Program.cs +++ b/Integracion_DGA/Program.cs @@ -1,10 +1,11 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Configuration; +using BLL.Integracion_DGA; +using BLL.Recuperacion_DGA; using DAL; using DAS; -using BLL.Recuperacion_DGA; -using BLL.Integracion_DGA; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Shared.Helper; using Shared.Utils; namespace Integracion_DGA @@ -13,10 +14,23 @@ namespace Integracion_DGA { static async Task Main(string[] args) { - ObtenerVariablesEntorno.AmbientarApiUrlNexus("NEXUS_API_URL"); - ObtenerVariablesEntorno.AmbientarUrlApiSubterranea("SUBTERRANEAS_API_URL"); - ObtenerVariablesEntorno.AmbientarConexionBd("CONEXION_BD_ENVIO_DGA"); - ObtenerVariablesEntorno.AmbientarCredencialesDGA("DGA_CREDENCIALES"); + try + { + Console.Write("Obteniendo variables de entorno..."); + ObtenerVariablesEntorno.AmbientarApiUrlNexus("NEXUS_API_URL"); + ObtenerVariablesEntorno.AmbientarUrlApiSubterranea("SUBTERRANEAS_API_URL"); + ObtenerVariablesEntorno.AmbientarConexionBd("CONEXION_BD_ENVIO_DGA"); + ObtenerVariablesEntorno.AmbientarCredencialesDGA("DGA_CREDENCIALES"); + ObtenerVariablesEntorno.ValidarVariablesEntorno(); + } + catch (Exception ex) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[Error] {ex.Message}"); + Console.ResetColor(); + FileLoggerHelper.LogInformation($"{ex.Message}"); + return; + } using IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => @@ -27,7 +41,6 @@ namespace Integracion_DGA services.AddScoped(); services.AddScoped(); services.AddHttpClient(); - //Estos dos servicios son los que migre del otro proyecto services.AddScoped(); services.AddScoped(); services.AddScoped(); @@ -37,8 +50,6 @@ namespace Integracion_DGA }) .Build(); - //TODO: Controlar si las variables de ambiente existen - var envioDGA = host.Services.GetRequiredService(); var bussinessLogic = host.Services.GetRequiredService(); var apiService = host.Services.GetRequiredService(); diff --git a/Recuperacion_DGA/Program.cs b/Recuperacion_DGA/Program.cs index f11a53f..d8342f2 100644 --- a/Recuperacion_DGA/Program.cs +++ b/Recuperacion_DGA/Program.cs @@ -5,6 +5,7 @@ using DAS; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Shared.Helper; using Shared.Utils; namespace Recuperacion_DGA @@ -13,10 +14,23 @@ namespace Recuperacion_DGA { static async Task Main(string[] args) { - ObtenerVariablesEntorno.AmbientarApiUrlNexus("NEXUS_API_URL"); - ObtenerVariablesEntorno.AmbientarUrlApiSubterranea("SUBTERRANEAS_API_URL"); - ObtenerVariablesEntorno.AmbientarConexionBd("CONEXION_BD_ENVIO_DGA"); - ObtenerVariablesEntorno.AmbientarCredencialesDGA("DGA_CREDENCIALES"); + try + { + Console.WriteLine("Obteniendo variables de entorno..."); + ObtenerVariablesEntorno.AmbientarApiUrlNexus("NEXUS_API_URL"); + ObtenerVariablesEntorno.AmbientarUrlApiSubterranea("SUBTERRANEAS_API_URL"); + ObtenerVariablesEntorno.AmbientarConexionBd("CONEXION_BD_ENVIO_DGA"); + ObtenerVariablesEntorno.AmbientarCredencialesDGA("DGA_CREDENCIALES"); + ObtenerVariablesEntorno.ValidarVariablesEntorno(); + } + catch (Exception ex) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[Error] {ex.Message}"); + Console.ResetColor(); + FileLoggerHelper.LogInformation($"{ex.Message}"); + return; + } using IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => @@ -25,25 +39,17 @@ namespace Recuperacion_DGA services.AddSingleton(configuration); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddHttpClient(); - //Estos dos servicios son los que migre del otro proyecto - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + services.AddScoped(); - services.AddScoped(); - services.AddScoped(); }) .Build(); - - //TODO: Controlar si las variables de ambiente existen - //TODO: Log de texto + var envioDGA = host.Services.GetRequiredService(); await envioDGA.RegistrarMedicionesAsync(); - - //TODO: Log de texto } } } \ No newline at end of file diff --git a/SHARED/DTO/Envios_DGA/LogMedicionScada.cs b/SHARED/DTO/Envios_DGA/LogMedicionScada.cs index aeb51c0..9a3b079 100644 --- a/SHARED/DTO/Envios_DGA/LogMedicionScada.cs +++ b/SHARED/DTO/Envios_DGA/LogMedicionScada.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.Envios_DGA +namespace Shared.DTO.Envios_DGA { public class LogMedicionScada { diff --git a/SHARED/DTO/Envios_DGA/MedicionScada.cs b/SHARED/DTO/Envios_DGA/MedicionScada.cs index 9577348..b26301a 100644 --- a/SHARED/DTO/Envios_DGA/MedicionScada.cs +++ b/SHARED/DTO/Envios_DGA/MedicionScada.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.Envios_DGA +namespace Shared.DTO.Envios_DGA { public class MedicionScada { @@ -27,6 +21,6 @@ namespace Shared.DTO.Envios_DGA public decimal? Nivel { get; set; } - public string? TipoEmpresa { get; set; } + public string? tipo_empresa { get; set; } } } diff --git a/SHARED/DTO/Envios_DGA/MedicionSubterraneaRequest.cs b/SHARED/DTO/Envios_DGA/MedicionSubterraneaRequest.cs index 05de152..6cea0a9 100644 --- a/SHARED/DTO/Envios_DGA/MedicionSubterraneaRequest.cs +++ b/SHARED/DTO/Envios_DGA/MedicionSubterraneaRequest.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.Envios_DGA +namespace Shared.DTO.Envios_DGA { public class MedicionSubterraneaRequest { @@ -26,5 +20,7 @@ namespace Shared.DTO.Envios_DGA public string HoraMedicion { get; set; } public string NivelFreaticoDelPozo { get; set; } public string Totalizador { get; set; } + public string? TipoEmpresa { get; set; } + } } diff --git a/SHARED/DTO/Integracion_DGA/DgaMacroResultado.cs b/SHARED/DTO/Integracion_DGA/DgaMacroResultado.cs index 82c07ed..07a735a 100644 --- a/SHARED/DTO/Integracion_DGA/DgaMacroResultado.cs +++ b/SHARED/DTO/Integracion_DGA/DgaMacroResultado.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace Shared.DTO.Integracion_DGA; +namespace Shared.DTO.Integracion_DGA; public partial class DgaMacroResultado { diff --git a/SHARED/DTO/Integracion_DGA/DgaMacroResultadoSupFluj.cs b/SHARED/DTO/Integracion_DGA/DgaMacroResultadoSupFluj.cs index 38dfa95..25558f6 100644 --- a/SHARED/DTO/Integracion_DGA/DgaMacroResultadoSupFluj.cs +++ b/SHARED/DTO/Integracion_DGA/DgaMacroResultadoSupFluj.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; - -namespace Shared.DTO.Integracion_DGA; +namespace Shared.DTO.Integracion_DGA; public partial class DgaMacroResultadoSupFluj { diff --git a/SHARED/DTO/Integracion_DGA/DgaMacroResultadoSupFlujSuma.cs b/SHARED/DTO/Integracion_DGA/DgaMacroResultadoSupFlujSuma.cs index 8e8fe2c..f1f5086 100644 --- a/SHARED/DTO/Integracion_DGA/DgaMacroResultadoSupFlujSuma.cs +++ b/SHARED/DTO/Integracion_DGA/DgaMacroResultadoSupFlujSuma.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; - -namespace Shared.DTO.Integracion_DGA; +namespace Shared.DTO.Integracion_DGA; public partial class DgaMacroResultadoSupFlujSuma { diff --git a/SHARED/DTO/Integracion_DGA/DgaMacroResultadoVilos.cs b/SHARED/DTO/Integracion_DGA/DgaMacroResultadoVilos.cs index f4ed351..1fe4f79 100644 --- a/SHARED/DTO/Integracion_DGA/DgaMacroResultadoVilos.cs +++ b/SHARED/DTO/Integracion_DGA/DgaMacroResultadoVilos.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; - -namespace Shared.DTO.Integracion_DGA; +namespace Shared.DTO.Integracion_DGA; public partial class DgaMacroResultadoVilos { diff --git a/SHARED/DTO/Integracion_DGA/DgaSensorResultado.cs b/SHARED/DTO/Integracion_DGA/DgaSensorResultado.cs index c19b0ba..0f85fb4 100644 --- a/SHARED/DTO/Integracion_DGA/DgaSensorResultado.cs +++ b/SHARED/DTO/Integracion_DGA/DgaSensorResultado.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; - -namespace Shared.DTO.Integracion_DGA; +namespace Shared.DTO.Integracion_DGA; public partial class DgaSensorResultado { diff --git a/SHARED/DTO/Integracion_DGA/DgaSensorResultadoVilos.cs b/SHARED/DTO/Integracion_DGA/DgaSensorResultadoVilos.cs index 19d2b79..a7c7da8 100644 --- a/SHARED/DTO/Integracion_DGA/DgaSensorResultadoVilos.cs +++ b/SHARED/DTO/Integracion_DGA/DgaSensorResultadoVilos.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; - -namespace Shared.DTO.Integracion_DGA; +namespace Shared.DTO.Integracion_DGA; public partial class DgaSensorResultadoVilos { diff --git a/SHARED/DTO/Integracion_DGA/DocumentResponse.cs b/SHARED/DTO/Integracion_DGA/DocumentResponse.cs index ae53f83..6e6e14f 100644 --- a/SHARED/DTO/Integracion_DGA/DocumentResponse.cs +++ b/SHARED/DTO/Integracion_DGA/DocumentResponse.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.Integracion_DGA +namespace Shared.DTO.Integracion_DGA { public class DocumentResponse { diff --git a/SHARED/DTO/Integracion_DGA/HistoricRequest.cs b/SHARED/DTO/Integracion_DGA/HistoricRequest.cs index 344a9bd..5e9b112 100644 --- a/SHARED/DTO/Integracion_DGA/HistoricRequest.cs +++ b/SHARED/DTO/Integracion_DGA/HistoricRequest.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.Integracion_DGA +namespace Shared.DTO.Integracion_DGA { public class HistoricRequest { diff --git a/SHARED/DTO/Integracion_DGA/HistoricResponse.cs b/SHARED/DTO/Integracion_DGA/HistoricResponse.cs index 9daef30..64caacb 100644 --- a/SHARED/DTO/Integracion_DGA/HistoricResponse.cs +++ b/SHARED/DTO/Integracion_DGA/HistoricResponse.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.Integracion_DGA +namespace Shared.DTO.Integracion_DGA { public class HistoricResponse { diff --git a/SHARED/DTO/Integracion_DGA/TagviewsResponse.cs b/SHARED/DTO/Integracion_DGA/TagviewsResponse.cs index 4270075..ad43f53 100644 --- a/SHARED/DTO/Integracion_DGA/TagviewsResponse.cs +++ b/SHARED/DTO/Integracion_DGA/TagviewsResponse.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.Integracion_DGA +namespace Shared.DTO.Integracion_DGA { public class TagviewsResponse { diff --git a/SHARED/DTO/VariablesEntorno/BdConexion.cs b/SHARED/DTO/VariablesEntorno/BdConexion.cs index 3b6243d..ccc75c0 100644 --- a/SHARED/DTO/VariablesEntorno/BdConexion.cs +++ b/SHARED/DTO/VariablesEntorno/BdConexion.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.VariablesEntorno +namespace Shared.DTO.VariablesEntorno { public static class BdConexion { diff --git a/SHARED/DTO/VariablesEntorno/CredencialDGA.cs b/SHARED/DTO/VariablesEntorno/CredencialDGA.cs index be9460b..2c7502c 100644 --- a/SHARED/DTO/VariablesEntorno/CredencialDGA.cs +++ b/SHARED/DTO/VariablesEntorno/CredencialDGA.cs @@ -1,14 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.VariablesEntorno +namespace Shared.DTO.VariablesEntorno { public static class CredencialDGA { - public static string RutEmpresa { get; set; } = string.Empty; + public static string RutEsval { get; set; } = string.Empty; + public static string RutAv { get; set; } = string.Empty; public static string RutUsuario { get; set; } = string.Empty; public static string Password { get; set; } = string.Empty; } diff --git a/SHARED/DTO/VariablesEntorno/NexusApiUrl.cs b/SHARED/DTO/VariablesEntorno/NexusApiUrl.cs index 9e19624..1f3c715 100644 --- a/SHARED/DTO/VariablesEntorno/NexusApiUrl.cs +++ b/SHARED/DTO/VariablesEntorno/NexusApiUrl.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.VariablesEntorno +namespace Shared.DTO.VariablesEntorno { public static class NexusApiUrl { diff --git a/SHARED/DTO/VariablesEntorno/SubterraneaApiUrl.cs b/SHARED/DTO/VariablesEntorno/SubterraneaApiUrl.cs index 93c2d18..7da37f0 100644 --- a/SHARED/DTO/VariablesEntorno/SubterraneaApiUrl.cs +++ b/SHARED/DTO/VariablesEntorno/SubterraneaApiUrl.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.VariablesEntorno +namespace Shared.DTO.VariablesEntorno { public static class SubterraneaApiUrl { diff --git a/SHARED/Helper/FileLoggerHelper.cs b/SHARED/Helper/FileLoggerHelper.cs index 3aaf591..b3e0bf1 100644 --- a/SHARED/Helper/FileLoggerHelper.cs +++ b/SHARED/Helper/FileLoggerHelper.cs @@ -3,27 +3,27 @@ using Serilog; namespace Shared.Helper { - public class FileLoggerHelper - { - public static void ConfigureLogger(IConfiguration configuration) + public class FileLoggerHelper { - var logFilePath = configuration.GetSection("Logging:LogFile:Path").Value; - var logFileFullPath = Path.Combine(Directory.GetCurrentDirectory(), logFilePath); + public static void ConfigureLogger(IConfiguration configuration) + { + var logFilePath = configuration.GetSection("Logging:LogFile:Path").Value; + var logFileFullPath = Path.Combine(Directory.GetCurrentDirectory(), logFilePath); - Log.Logger = new LoggerConfiguration() - .ReadFrom.Configuration(configuration) - .WriteTo.File(logFileFullPath, rollingInterval: RollingInterval.Day) - .CreateLogger(); - } + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .WriteTo.File(logFileFullPath, rollingInterval: RollingInterval.Day) + .CreateLogger(); + } - public static void LogInformation(string message) - { - Log.Information($"{message}"); - } + public static void LogInformation(string message) + { + Log.Information($"{message}"); + } - public static void LogError(string message, Exception ex) - { - Log.Error(ex, message); + public static void LogError(string message, Exception ex) + { + Log.Error(ex, message); + } } - } } diff --git a/SHARED/Utils/ObtenerVariablesEntorno.cs b/SHARED/Utils/ObtenerVariablesEntorno.cs index 6dcbaa0..655d137 100644 --- a/SHARED/Utils/ObtenerVariablesEntorno.cs +++ b/SHARED/Utils/ObtenerVariablesEntorno.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Shared.DTO.VariablesEntorno; +using Shared.DTO.VariablesEntorno; namespace Shared.Utils { @@ -34,8 +29,11 @@ namespace Shared.Utils { var dictEnv = GetVarEnviromentDict(env); - dictEnv.TryGetValue("RUTEMPRESA", out string? rutEmpresa); - CredencialDGA.RutEmpresa = rutEmpresa ?? string.Empty; + dictEnv.TryGetValue("RUTESVAL", out string? rutEsval); + CredencialDGA.RutEsval = rutEsval ?? string.Empty; + + dictEnv.TryGetValue("RUTAV", out string? rutAv); + CredencialDGA.RutAv = rutAv ?? string.Empty; dictEnv.TryGetValue("RUTUSUARIO", out string? rutUsuario); CredencialDGA.RutUsuario = rutUsuario ?? string.Empty; @@ -79,5 +77,33 @@ namespace Shared.Utils dictEnv.TryGetValue("ENDPOINT", out string? endpoint); SubterraneaApiUrl.EndPoint = endpoint ?? string.Empty; } + + public static void ValidarVariablesEntorno() + { + if (string.IsNullOrWhiteSpace(CredencialDGA.RutEsval)) + throw new Exception("La propiedad CredencialDGA.RutEsval está vacía o nula."); + if (string.IsNullOrWhiteSpace(CredencialDGA.RutAv)) + throw new Exception("La propiedad CredencialDGA.RutAv está vacía o nula."); + if (string.IsNullOrWhiteSpace(CredencialDGA.RutUsuario)) + throw new Exception("La propiedad CredencialDGA.RutUsuario está vacía o nula."); + if (string.IsNullOrWhiteSpace(CredencialDGA.Password)) + throw new Exception("La propiedad CredencialDGA.Password está vacía o nula."); + if (string.IsNullOrWhiteSpace(NexusApiUrl.ApiUrl)) + throw new Exception("La propiedad NexusApiUrl.ApiUrl está vacía o nula."); + if (string.IsNullOrWhiteSpace(NexusApiUrl.ApiKey)) + throw new Exception("La propiedad NexusApiUrl.ApiKey está vacía o nula."); + if (string.IsNullOrWhiteSpace(NexusApiUrl.Version)) + throw new Exception("La propiedad NexusApiUrl.Version está vacía o nula."); + if (string.IsNullOrWhiteSpace(NexusApiUrl.DataSource)) + throw new Exception("La propiedad NexusApiUrl.DataSource está vacía o nula."); + if (string.IsNullOrWhiteSpace(NexusApiUrl.Resolution)) + throw new Exception("La propiedad NexusApiUrl.Resolution está vacía o nula."); + if (string.IsNullOrWhiteSpace(BdConexion.StringConnection)) + throw new Exception("La propiedad BdConexion.StringConnection está vacía o nula."); + if (string.IsNullOrWhiteSpace(SubterraneaApiUrl.BaseUrl)) + throw new Exception("La propiedad SubterraneaApiUrl.BaseUrl está vacía o nula."); + if (string.IsNullOrWhiteSpace(SubterraneaApiUrl.EndPoint)) + throw new Exception("La propiedad SubterraneaApiUrl.EndPoint está vacía o nula."); + } } }