/// <summary> /// Constructor que carga el reporte donde se guardaran los datos y el archivo PDF del cual se obtendran. /// </summary> /// <param name="reporteNovedades">Archivo Excel donde se guardaran los datos.</param> /// <param name="datosInventarioPlanchon">Archivo PDF del cual se obtendran los datos.</param> public InventarioPlanchon(ArchivoExcel reporteNovedades, ArchivoPdf datosInventarioPlanchon, double tiraProg, DatosSalida salida) { this.reporteNovedades = reporteNovedades; this.datosInventarioPlanchon = datosInventarioPlanchon; this.tiraProg = tiraProg; this.salida = salida; }
private void tsbCargarConfiguracion_Click(object sender, EventArgs e) { try { if (cargarConfDlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { StreamReader archivo = new StreamReader(cargarConfDlg.OpenFile()); txtArchivo.Text = archivo.ReadToEnd(); archivo.Close(); archivo.Dispose(); _excel = JsonConvert.DeserializeObject <ArchivoExcel>(txtArchivo.Text); } } catch (Exception ex) { log.Error("Error al cargar archivo de configuración desde el GUI", ex); } }
private void button4_Click(object sender, EventArgs e) { DialogResult resultado = openFileDialog2.ShowDialog(); if (resultado == DialogResult.OK) { string ruta = System.IO.Path.GetFullPath(openFileDialog2.FileName); label6.Text = ruta; label6.Font = new Font(label6.Font, FontStyle.Regular); ArchivoExcel reporteCoordinacion; reporteCoordinacion = new ArchivoExcel(ruta, true); inventarioCoordinacion = new InventarioCoordinacion(reporteNovedades, reporteCoordinacion); } }
static void Main(string[] args) { Stopwatch timeMeasure = new Stopwatch(); timeMeasure.Start(); DataTable dt = Datos.CrearTabla(); _excel = new ArchivoExcel("Ejemplo.xlsx"); try { _excel.Inicializar(); _excel.FuenteDeDatos = dt; // _excel.EncabezadosHandler = ConstruirEncabezados; _excel.SubtitulosHandler = AgregarSubtitulos; _excel.ExcluirColumnas = new string[] { "Columna 3", "Columna 4" }; _excel.EstilosColumnas = new EstiloColumnas[] { new EstiloColumnas { Estilo = _excel.HojaDeEstilos.DATO_NUMERICO, Columnas = new int[] { 0 } }, new EstiloColumnas { Estilo = _excel.HojaDeEstilos.DATO_MONEDA, Columnas = new int[] { 8, 10 } }, new EstiloColumnas { Estilo = _excel.HojaDeEstilos.DATO_FECHA, Columnas = new int[] { 9, 11 } } }; _excel.FilaNivelAgregado += OnFilaNivelAgregado; // _excel.NombreColumnaNivel = "id"; _excel.Construir(); _excel.Guardar(); } finally { _excel.CerrarLibro(); // excel.EliminarDocumento(); } timeMeasure.Stop(); TimeSpan ts = timeMeasure.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine($"Tiempo de ejecución: {elapsedTime}"); }
private void button1_Click(object sender, EventArgs e) { DialogResult resultado = openFileDialog1.ShowDialog(); if (resultado == DialogResult.OK) { string ruta = System.IO.Path.GetFullPath(openFileDialog1.FileName); label1.Text = ruta; label1.Font = new Font(label1.Font, FontStyle.Regular); reporteNovedades = new ArchivoExcel(ruta, false); salida = new DatosSalida(); txtTiraProg.Enabled = true; button2.Enabled = true; button3.Enabled = true; button4.Enabled = true; } }
public async Task <IActionResult> ExtraerVariables(int id) { var rutaArchivo = ""; try { Stopwatch time = new Stopwatch(); time.Start(); this._log.WriteInfo($"Inicia el servicio para extraer las variables"); List <TipoProductoFamilia> tipoProductoFamilias = null; int cantidadArchivos = Request.Form.Files.Count; if (cantidadArchivos > 0 && cantidadArchivos == 1) { var archivoExcelPeticion = Request.Form.Files.Select(e => e).ToList()[0]; string extensionArchivo = Path.GetExtension(archivoExcelPeticion.FileName) .ToUpperInvariant(); if (string.IsNullOrEmpty(extensionArchivo) || this.extensionesPermitidas.Contains(extensionArchivo)) { ArchivoExcel archivoExcel = null; rutaArchivo = $"{Path.GetTempPath()}variables{DateTime.Now.Ticks}.xlsx"; using (var stream = new FileStream(rutaArchivo, FileMode.Create)) { await archivoExcelPeticion.CopyToAsync(stream); stream.Close(); archivoExcel = new ArchivoExcel(rutaArchivo); } archivoExcel.RutaTemportal = rutaArchivo; tipoProductoFamilias = archivoExcel.ExcelUsingEPPlus().ToList(); time.Stop(); this._log.WriteAndCountService($"Método:{nameof(ExtraerVariables)}-> Se ejecuto correctamente", new Dictionary <string, int> { { nameof(WsAdministracionVariables), Convert.ToInt32(time.ElapsedMilliseconds) } }); return(Ok( new RespuestaOK { respuesta = new { productosFamilias = tipoProductoFamilias, esValido = !(tipoProductoFamilias.Any(e => e.fiFamiliaId == 0)) } })); } else { time.Stop(); this._log.WriteAndCountService($"Método:{nameof(ExtraerVariables)}-> No es un archivo el archivo que se cargo", new Dictionary <string, int> { { nameof(WsAdministracionVariables), Convert.ToInt32(time.ElapsedMilliseconds) } }); return(BadRequest( new RespuestaError400 { errorInfo = string.Empty, errorMessage = $"No es un archivo de Excel" })); } } else { time.Stop(); this._log.WriteAndCountService($"Método:{nameof(ExtraerVariables)}-> Se cargo más de un archivo o no se cargo ningún archivo", new Dictionary <string, int> { { nameof(WsAdministracionVariables), Convert.ToInt32(time.ElapsedMilliseconds) } }); return(BadRequest( new RespuestaError400 { errorInfo = string.Empty, errorMessage = cantidadArchivos > 0 ? "Solo se puede subir un archivo" : "No subiste ningún archivo" })); } } catch (Exception ex) { if (ex is UnauthorizedAccessException) { if (_log is null) { //_log = new BibliotecaSimulador.Logs.Logg(this.Nombrelog); this._log.WriteErrorService(ex, nameof(WsAdministracionVariables)); return(StatusCode(StatusCodes.Status500InternalServerError, new RespuestaError { errorMessage = this._configuration.GetValue <string>("Mensajes:Errores:CrearArchivoExcel") })); } _log.WriteErrorService(ex, nameof(WsAdministracionVariables)); return(StatusCode(StatusCodes.Status500InternalServerError, new RespuestaError { errorMessage = this._configuration.GetValue <string>($"Mensajes:Errores:Generico") })); } else if (ex is ArgumentNullException) { if (this._log is null) { this._log.WriteErrorService(ex, nameof(WsAdministracionVariables)); return(StatusCode(StatusCodes.Status500InternalServerError, new RespuestaError { errorMessage = this._configuration.GetValue <string>("Mensajes:Errores:Argumento") })); } this._log.WriteErrorService(ex, nameof(WsAdministracionVariables)); return(StatusCode(StatusCodes.Status500InternalServerError, new RespuestaError { errorMessage = this._configuration.GetValue <string>("Mensajes:Errores:Generico") })); } else { this._log.WriteErrorService(ex, nameof(WsAdministracionVariables)); return(StatusCode(StatusCodes.Status500InternalServerError, new RespuestaError { errorMessage = this._configuration.GetValue <string>("Mensajes:Errores:Generico") })); } } finally { if (System.IO.File.Exists(rutaArchivo)) { System.IO.File.Delete(rutaArchivo); } } }
public IActionResult GuardarValoresTodos(int id, IEnumerable <TipoProductoFamilia> tipoProductosFamilias) { try { Stopwatch time = new Stopwatch(); time.Start(); this._log.WriteInfo($"Inicia el servicio para el guardado de variables"); bool sonValidasVariables = false; if (!(tipoProductosFamilias is null)) { ValidacionVariables validacionVariables = new ValidacionVariables(this._configuration); validacionVariables.construccionObjetoPeticion(tipoProductosFamilias.ToList()); ObjetoRespuestaVariables objetoRespuesta = validacionVariables.RealizarPeticionValidacion(); if (!(objetoRespuesta is null)) { if (!(objetoRespuesta.Valores is null)) { sonValidasVariables = validacionVariables.ValidacionValoresVariables(objetoRespuesta); if (sonValidasVariables) { bool validarValores = false; bool validarVariables = false; foreach (TipoProductoFamilia tipoProductoFamilia in tipoProductosFamilias) { TccrConfiguracionCalculosDao tCCRConfiguracionCalculosDAO = new TccrConfiguracionCalculosDao(); tCCRConfiguracionCalculosDAO.nombreSPAEjecutar = this._configuration.GetSection("spConfiguracion").Value; TccrConfiguracionCalculos tCCRConfiguracionCalculos = tCCRConfiguracionCalculosDAO.obtenerTCCRConfiguracionCalculos(1, null, tipoProductoFamilia.fiTipoProductoId , null, null, null); if (!(tCCRConfiguracionCalculos is null)) { if (tCCRConfiguracionCalculos.fiConfiguracionId > 0) { TccrFactoresDao tccrFactoresActualizar = new TccrFactoresDao(); tccrFactoresActualizar.nombreSPAEjecutar = this._configuration.GetSection("spFactores").Value; int actualizado = tccrFactoresActualizar.establecerFactoresEnCeroPorFamilia(0, tCCRConfiguracionCalculos.fiConfiguracionId , tipoProductoFamilia.fiFamiliaId); if (actualizado >= 0) { foreach (var variables in tipoProductoFamilia.variablesCabeceras) { if (variables.fiVariableId <= 0) { int fiVariableIdABuscar = 0; TccrVariablesDao tCCRVariablesDAOBuscar = new TccrVariablesDao(); tCCRVariablesDAOBuscar.nombreSPAEjecutar = this._configuration.GetSection("spVariables").Value; fiVariableIdABuscar = tCCRVariablesDAOBuscar.insertarTCCRVariablesPersonalizado(1, null, variables.fcDescripcion, null, null); if (fiVariableIdABuscar > 0) { variables.fiVariableId = fiVariableIdABuscar; } else { int fiVariableId = 0; TccrVariablesDao tCCRVariablesDAO = new TccrVariablesDao(); tCCRVariablesDAO.nombreSPAEjecutar = this._configuration.GetSection("spVariables").Value; fiVariableId = tCCRVariablesDAO.insertarTCCRVariablesPersonalizado(2, null, variables.fcDescripcion, 1, id); if (fiVariableId > 0) { variables.fiVariableId = fiVariableId; } else { validarVariables = true; } } } if (variables.fiVariableId > 0) { foreach (var variablesValores in variables.variables) { var valorValidadoActual = false; TccrFactoresDao tCCRFactoresDAO = new TccrFactoresDao(); tCCRFactoresDAO.nombreSPAEjecutar = this._configuration.GetSection("spFactores").Value; if (variablesValores.esPorcentaje) { variablesValores.valor = ArchivoExcel.PorcentajeDecimal(variablesValores.valor); } TccrFactores tCCRFactores = new TccrFactores { fiConfiguracionId = tCCRConfiguracionCalculos.fiConfiguracionId, fiVariableId = variables.fiVariableId, fiFamiliaId = tipoProductoFamilia.fiFamiliaId, fiPlazo = variablesValores.plazo, fnValor = variablesValores.valor, fdIniVigencia = null, fiStatus = 1, fiUsuario = id, }; valorValidadoActual = tCCRFactoresDAO.insertarTCCRFactoresPersonalizado(2, tCCRFactores); if (!valorValidadoActual) { if (!validarValores) { validarValores = true; } } } } else { validarVariables = true; } } } else { time.Stop(); string mensaje = $"Se tuvo un error al actulizar los factores en cero de la familia ${tipoProductoFamilia.fcDescripcionFamilia}"; this._log.WriteAndCountService($"Método:{nameof(GuardarValoresTodos)}-> {mensaje}", new Dictionary <string, int> { { nameof(WsAdministracionVariables), Convert.ToInt32(time.ElapsedMilliseconds) } }); return(StatusCode(StatusCodes.Status500InternalServerError, new RespuestaError { errorMessage = mensaje })); } } else { time.Stop(); string mensaje = $"No existe una configuración para el tipo producto: " + $"{ tipoProductoFamilia.fiTipoProductoId } para la familia:{ tipoProductoFamilia.fcDescripcionFamilia } , favor de validar"; this._log.WriteAndCountService($"Método:{nameof(GuardarValoresTodos)}-> {mensaje}", new Dictionary <string, int> { { nameof(WsAdministracionVariables), Convert.ToInt32(time.ElapsedMilliseconds) } }); return(NotFound( new RespuestaError404 { errorMessage = mensaje })); } } else { time.Stop(); string mensaje = $"No existe una configuración para el tipo producto: " + $"{ tipoProductoFamilia.fiTipoProductoId } para la familia:{ tipoProductoFamilia.fcDescripcionFamilia } , favor de validar"; this._log.WriteAndCountService($"Método:{nameof(GuardarValoresTodos)}-> {mensaje}", new Dictionary <string, int> { { nameof(WsAdministracionVariables), Convert.ToInt32(time.ElapsedMilliseconds) } }); return(NotFound( new RespuestaError404 { errorMessage = mensaje })); } } time.Stop(); this._log.WriteAndCountService($"Método:{nameof(GuardarValoresTodos)}-> Se guardo correctamento los valores", new Dictionary <string, int> { { nameof(WsAdministracionVariables), Convert.ToInt32(time.ElapsedMilliseconds) } }); return(Ok( new RespuestaOK { respuesta = new { userId = id, validacion = sonValidasVariables, valoresOK = validarValores, variablesOK = validarVariables } })); } else { time.Stop(); this._log.WriteAndCountService($"Método:{nameof(GuardarValoresTodos)}-> Los valores no validaron correctamente", new Dictionary <string, int> { { nameof(WsAdministracionVariables), Convert.ToInt32(time.ElapsedMilliseconds) } }); return(Ok( new RespuestaOK { respuesta = new { userId = id, validacion = sonValidasVariables, objeto = validacionVariables.tipoProductoFamilia } })); } }
/// <summary> /// Constructor que carga el reporte donde se guardaran los datos y el archivo PDF del cual se obtendran. /// </summary> /// <param name="reporteNovedades">Archivo Excel donde se guardaran los datos.</param> /// <param name="datosInventarioSteckel">Archivo PDF del cual se obtendran los datos.</param> public InventarioSteckel(ArchivoExcel reporteNovedades, ArchivoPdf datosInventarioSteckel) { this.reporteNovedades = reporteNovedades; this.datosInventarioSteckel = datosInventarioSteckel; }
static int Main(string[] args) { // Carga la configuración de log4net desde App.congif log4net.Config.XmlConfigurator.Configure(); if (log.IsDebugEnabled) { log.Debug("Configurado log4net."); } Console.WriteLine(); bool showHelp = false; bool showGui = false; int errorLevel = 0; string server = String.Empty; string db = String.Empty; string fileConf = String.Empty; var p = new OptionSet() { { "g|gui", "En lugar de lanzar el proceso, muestra la interfaz gráfica para un uso manual.", v => showGui = (v != null) }, { "v|verbose=", "Especifica el nivel de detalle del archivo LOG ignorando la " + "configuración definida en el archivo .CONGIF.\n" + "\t5 - Todos los niveles: DEBUG, INFO, WARN, ERROR, FATAL\n" + "\t4 - INFO, WARN, ERROR, FATAL\n" + "\t3 - WARN, ERROR, FATAL\n" + "\t2 - ERROR, FATAL\n" + "\t1 - FATAL\n", v => errorLevel = Int32.Parse(v) }, { "s|server=", "Servidor SQL Server para la conexión", v => server = v }, { "d|database=", "Nombre de la base de datos de inicio en el servidor SQL Server para la conexión", v => db = v }, { "c|config=", "Ruta completa del archivo JSON de configuración de las actualizaciones", v => fileConf = v }, { "h|help", "Muestra las opciones de la línea de comandos", v => showHelp = (v != null) } }; List <string> extra; try { log.Debug("Parseando los argumentos"); extra = p.Parse(args); } catch (Exception ex) { log.Fatal("Argumentos de la línea de comandos no válidos", ex); ShowHelp(p); } switch (errorLevel) { case 0: // se utiliza el nivel establecido en la configuración de la app. break; case 1: log.Logger.Repository.Threshold = Level.Fatal; break; case 2: log.Logger.Repository.Threshold = Level.Error; break; case 3: log.Logger.Repository.Threshold = Level.Warn; break; case 4: log.Logger.Repository.Threshold = Level.Info; break; case 5: log.Logger.Repository.Threshold = Level.Debug; break; default: Console.WriteLine(); Console.WriteLine("El parámetro -verbose solamente puede tener los valores [0-5]"); Console.WriteLine("Utiliza sql2excel -h para obtener más detalles"); Console.WriteLine(); break; } if (log.IsDebugEnabled) { log.DebugFormat("Nivel de mensajes establecido a {0}", log.Logger.Repository.Threshold.DisplayName); } if (showHelp) { log.Debug("Mostrando ayuda"); ShowHelp(p); return(0); } else if (showGui) { if (log.IsDebugEnabled) { log.Debug("Iniciando entorno gráfico según el parámetro de la línea de comandos -g"); } System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); System.Windows.Forms.Application.Run(new MainForm()); return(0); } else { if (log.IsDebugEnabled) { log.Debug("Iniciando en modo comandos sin entorno gráfico"); } Console.WriteLine(); // 1. Cargar el archivo de configuración if (String.IsNullOrWhiteSpace(fileConf)) { log.Fatal("No se ha especificado archivo de configuración"); return(1); } String conf = String.Empty; try { log.Info("Cargando archivo de actualizaciones"); using (StreamReader reader = new StreamReader(fileConf)) { conf = reader.ReadToEnd(); } } catch (Exception ex) { log.Fatal("No se ha podido leer el archivo de configuración", ex); } ArchivoExcel excel = JsonConvert.DeserializeObject <ArchivoExcel>(conf); // 2. Cargar configuración de conexión y realizar prueba if (String.IsNullOrWhiteSpace(server)) { log.Fatal("No se ha especificado un servidor SQL Server"); return(2); } if (String.IsNullOrWhiteSpace(db)) { log.Fatal("No se ha especificado una base de datos"); return(3); } Conexion conexion = new Conexion { Servidor = server, BaseDatos = db }; log.InfoFormat("Probando la conexión a {0}/{1}", server, db); if (conexion.Probar() == false) { log.Fatal("Ha fallado la prueba de conexión a la base de datos"); return(4); } // 3. Aplicamos las actualizaciones try { log.Info("Aplicando actualizaciones"); excel.ActualizarDatos(conexion); } catch (Exception ex) { log.Fatal("Error al actualizar los datos", ex); return(5); } // 4. Salimos sin errores log.Info("Proceso terminado"); return(0); } }
/// <summary> /// Constructor que carga el reporte donde se guardaran los datos y el archivo excel del cual se obtendran. /// </summary> /// <param name="reporteNovedades">Archivo Excel donde se guardaran los datos.</param> /// <param name="datosInventarioPlanchon">Archivo PDF del cual se obtendran los datos.</param> public InventarioCoordinacion(ArchivoExcel reporteNovedades, ArchivoExcel datosInventarioCoordinación) { this.reporteNovedades = reporteNovedades; this.datosInventarioCoordinación = datosInventarioCoordinación; }