<%@ WebHandler Language="C#" Class="TareasJam" %> using System; using System.Web; using Extensiones; using System.Net; using System.IO; using System.Web.Services; using System.Web.Services.Protocols; using GemBox.Spreadsheet; using System.Data; using System.Text; using System.Collections.Generic; public class TareasJam : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); bool retorno = false; string Metodo = context.Request["Metodo"] ==null?"": context.Request["Metodo"]; int CveEmpresa =context.Request["CveEmpresa"] ==null?0: context.Request["CveEmpresa"].ToEntero(); switch (Metodo) { case "TestConexion": retorno = PruebaConexionFTP("ftp://us2.hostedftp.com/", "agrojam", "A12345678"); break; case "EjecutaThalamus": retorno =EjecutaThalamus(CveEmpresa); break; default: break; } if (retorno) { context.Response.Write("True"); }else { context.Response.Write("False"); } context.Response.End(); } private bool EjecutaThalamus(int CveEmpresa) { bool Respuesta = false; StringBuilder SBLog = new StringBuilder(); ClsGenerales ObjGenerales = new ClsGenerales(); DataTable DTProductos = new DataTable(); DataTable DTVentas = new DataTable(); DataTable DTClientes = new DataTable(); DataTable DTAlmacenes = new DataTable(); string RutaProductos = $@"{ HttpContext.Current.Server.MapPath("~") }Temp\Productos{DateTime.Now.ToString("yyyyMMdd")}.xlsx"; string RutaVentas = $@"{ HttpContext.Current.Server.MapPath("~") }Temp\Ventas{DateTime.Now.ToString("yyyyMMdd")}.xlsx"; string RutaClientes = $@"{ HttpContext.Current.Server.MapPath("~") }Temp\Clientes{DateTime.Now.ToString("yyyyMMdd")}.xlsx"; string RutaAlmacenes = $@"{ HttpContext.Current.Server.MapPath("~") }Temp\Almacenes{DateTime.Now.ToString("yyyyMMdd")}.xlsx"; try { if (File.Exists(RutaProductos)) { File.Delete(RutaProductos); } if (File.Exists(RutaVentas)) { File.Delete(RutaVentas); } if (File.Exists(RutaClientes)) { File.Delete(RutaClientes); } if (File.Exists(RutaAlmacenes)) { File.Delete(RutaAlmacenes); } } catch (Exception ex) { SBLog.AppendLine("Error al eliminar archivos"); } ////"ftp://us2.hostedftp.com/", "agrojam", "A12345678"; //string FTPServer = "ftp://127.0.0.1/"; //string TFPUsr = "Toor"; //string FTPPass = "agj-3500"; string FTPServer = "ftp://us2.hostedftp.com"; string TFPUsr = "agrojam"; string FTPPass = "A12345678"; bool ErrorProceso = false; SBLog.AppendLine("Consultas
"); SBLog.AppendLine(""); if (ObjGenerales.GetJAMCorveta(1)) { DTProductos = ObjGenerales.DtResultados.Copy(); SBLog.AppendLine($""); } else { ErrorProceso = true; SBLog.AppendLine($""); } if (ObjGenerales.GetJAMCorveta(2) & ErrorProceso == false) { DTVentas = ObjGenerales.DtResultados.Copy(); SBLog.AppendLine($"Ventas"); } else { ErrorProceso = true; SBLog.AppendLine($""); } if (ObjGenerales.GetJAMCorveta(3) & ErrorProceso == false) { DTClientes = ObjGenerales.DtResultados.Copy(); SBLog.AppendLine($""); } else { ErrorProceso = true; SBLog.AppendLine($""); } if (ObjGenerales.GetJAMCorveta(4) & ErrorProceso == false) { DTAlmacenes = ObjGenerales.DtResultados.Copy(); SBLog.AppendLine($""); } else { ErrorProceso = true; SBLog.AppendLine($""); } SBLog.AppendLine("
ConsultaRegistros
Productos{DTProductos.Rows.Count}
ProductosError al consultar
{DTVentas.Rows.Count}
VentasError al consultar
Clientes{DTClientes.Rows.Count}
ClientesError al consultar
Almacenes{DTAlmacenes.Rows.Count}
AlmacenesError al consultar
"); SBLog.AppendLine("
"); ObjGenerales.Dispose(); if (!ErrorProceso) { try { DTProductos.Columns[0].ColumnName = "Código Producto Interno "; DTProductos.Columns[1].ColumnName = "Nombre del Producto"; DTProductos.Columns[2].ColumnName = "Presentación"; DTProductos.AcceptChanges(); DTClientes.Columns[4].ColumnName = "address.countryId"; DTClientes.Columns[5].ColumnName = "address.stateId"; DTClientes.Columns[6].ColumnName = "address.city"; DTClientes.Columns[7].ColumnName = "address.street1"; DTClientes.Columns[8].ColumnName = "address.street2"; DTClientes.Columns[9].ColumnName = "address.postalCode"; DTClientes.Columns[10].ColumnName = "phone.intCode"; DTClientes.Columns[11].ColumnName = "phone.areaCode"; DTClientes.Columns[12].ColumnName = "phone.number"; //DTClientes.Columns.RemoveAt(12); //DTClientes.Columns.RemoveAt(11); //DTClientes.Columns.RemoveAt(10); //DTClientes.Columns.RemoveAt(8); //DTClientes.Columns.RemoveAt(7); DTClientes.AcceptChanges(); DTVentas.Columns.RemoveAt(7); //DTVentas.Columns.RemoveAt(6); DTVentas.Columns[3].ColumnName = "Sale Date"; DTVentas.Columns[6].ColumnName = "Transaction ID"; DTVentas.AcceptChanges(); DTAlmacenes.Columns[2].ColumnName = "Description"; DTAlmacenes.Columns[3].ColumnName = "Stock Date"; DTAlmacenes.AcceptChanges(); DataTable dtCloned = DTVentas.Clone(); dtCloned.Columns[3].DataType = typeof(string); foreach (DataRow row in DTVentas.Rows) { dtCloned.ImportRow(row); } DTVentas = dtCloned; foreach(DataRow dRow in DTVentas.Rows) { string tmpString = dRow[3].ToString().ToDate().ToString("yyyy/MM/dd"); dRow[3] = tmpString; } DTVentas.AcceptChanges(); dtCloned = DTAlmacenes.Clone(); dtCloned.Columns[3].DataType = typeof(string); foreach (DataRow row in DTAlmacenes.Rows) { dtCloned.ImportRow(row); } DTAlmacenes = dtCloned; foreach(DataRow dRow in DTAlmacenes.Rows) { string tmpString = dRow[3].ToString().ToDate().ToString("yyyy/MM/dd"); dRow[3] = tmpString; } DTAlmacenes.AcceptChanges(); } catch (Exception e) { SBLog.AppendLine("Error al renombrar columnas"); } } if (!ErrorProceso) { SpreadsheetInfo.SetLicense(Extensiones.ModExtensiones.SerialGemBoxSpreadsheet()); var workbookProductos = new ExcelFile(); var worksheetProductos = workbookProductos.Worksheets.Add("Productos"); worksheetProductos.InsertDataTable(DTProductos, new InsertDataTableOptions() { ColumnHeaders = true, StartRow = 0 }); workbookProductos.Save(RutaProductos); var workbookVentas = new ExcelFile(); var worksheetVentas = workbookVentas.Worksheets.Add("Ventas"); worksheetVentas.InsertDataTable(DTVentas, new InsertDataTableOptions() { ColumnHeaders = true, StartRow = 0 }); workbookVentas.Save(RutaVentas); var workbookClientes = new ExcelFile(); var worksheetClientes = workbookClientes.Worksheets.Add("Clientes"); worksheetClientes.InsertDataTable(DTClientes, new InsertDataTableOptions() { ColumnHeaders = true, StartRow = 0 }); workbookClientes.Save(RutaClientes); var workbookAlmacenes = new ExcelFile(); var worksheetAlmacenes = workbookAlmacenes.Worksheets.Add("Almacenes"); worksheetAlmacenes.InsertDataTable(DTAlmacenes, new InsertDataTableOptions() { ColumnHeaders = true, StartRow = 0 }); workbookAlmacenes.Save(RutaAlmacenes); var FInfoProductos = new FileInfo(RutaProductos); var FInfoVentas = new FileInfo(RutaVentas); var FInfoClientes = new FileInfo(RutaClientes); var FInfoAlmacenes = new FileInfo(RutaAlmacenes); bool CargaProductos = false; bool CargaVentas = false; bool CargaClientes = false; bool CargaAlmacenes = false; SBLog.AppendLine("Cargas
"); SBLog.AppendLine(""); CargaProductos = CargarArchivos(FInfoProductos, FTPServer, TFPUsr, FTPPass); if (CargaProductos) { CargaProductos = VerificarArchivo(FInfoProductos, FInfoProductos.Length, FTPServer, TFPUsr, FTPPass); } if (CargaProductos) { SBLog.AppendLine($""); } else { SBLog.AppendLine($""); } if (CargaProductos) { CargaVentas = CargarArchivos(FInfoVentas, FTPServer, TFPUsr, FTPPass); if (CargaVentas) { CargaVentas = VerificarArchivo(FInfoVentas, FInfoVentas.Length, FTPServer, TFPUsr, FTPPass); } } if (CargaVentas) { SBLog.AppendLine($""); }else { SBLog.AppendLine($""); } if (CargaProductos & CargaVentas) { CargaClientes = CargarArchivos(FInfoClientes, FTPServer, TFPUsr, FTPPass); if (CargaClientes) { CargaClientes = VerificarArchivo(FInfoClientes, FInfoClientes.Length, FTPServer, TFPUsr, FTPPass); } } if (CargaClientes) { SBLog.AppendLine($""); }else { SBLog.AppendLine($""); } if (CargaProductos & CargaVentas& CargaClientes ) { CargaAlmacenes = CargarArchivos(FInfoAlmacenes, FTPServer, TFPUsr, FTPPass); if (CargaClientes) { CargaAlmacenes = VerificarArchivo(FInfoAlmacenes, FInfoAlmacenes.Length, FTPServer, TFPUsr, FTPPass); } } if (CargaAlmacenes) { SBLog.AppendLine($""); }else { SBLog.AppendLine($""); } if (CargaProductos & CargaVentas & CargaClientes & CargaAlmacenes) { Respuesta = true; } else { Respuesta = false; } SBLog.AppendLine("
ArchivoEstado
Productosok
ProductosError carga
Ventasok
VentasError carga
Clientesok
ClientesError carga
Almacenesok
AlmacenesError carga
"); } else { Respuesta = false; } string Cuerpo = Respuesta ? $"Correcto
Tarea de carga de archios Corteva realizada correctamente
{SBLog.ToString()}" : $"Error
Error tarea de carga de archios Corteva
{SBLog.ToString()}" ; MandaCorreo(Cuerpo, Respuesta, RutaProductos, RutaVentas, RutaClientes, RutaAlmacenes); return Respuesta; } private void MandaCorreo(string Cuerpo, bool ErrorProceso, string RutaProductos, string RutaVentas, string RutaClientes, string RutaAlmacenes) { try { List ListaArchivos = new List(); ClsSisMail.ArchivoMail Productos = new ClsSisMail.ArchivoMail(); ClsSisMail.ArchivoMail Ventas = new ClsSisMail.ArchivoMail(); ClsSisMail.ArchivoMail Clientes = new ClsSisMail.ArchivoMail(); ClsSisMail.ArchivoMail Almacenes = new ClsSisMail.ArchivoMail(); Productos.Ruta = RutaProductos; Ventas.Ruta = RutaVentas; Clientes.Ruta = RutaClientes; Almacenes.Ruta = RutaAlmacenes; //FileInfo FIp = new FileInfo(RutaProductos); //FileInfo FIv = new FileInfo(RutaVentas); //FileInfo FIc = new FileInfo(RutaClientes); //FileInfo FIa = new FileInfo(RutaAlmacenes); ListaArchivos.Add(Productos); ListaArchivos.Add(Ventas); ListaArchivos.Add(Clientes); ListaArchivos.Add(Almacenes); ClsSisMail Correo = new ClsSisMail(); string Para = "julian@adssistemas.mx;rene.molina@adssistemas.mx;oscar.irigoyen@adssistemas.mx"; // string Para = "oscar.irigoyen@adssistemas.mx"; string Asunto = ErrorProceso ? $"Carga Layout Corteva {DateTime.Now.ToString("yyyy-MM-dd")}" : $"Carga Layout Corteva Error {DateTime.Now.ToString("yyyy-MM-dd")}"; Correo.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Cuerpo, Archivos:ListaArchivos); }catch(Exception ex) { Extensiones.ModExtensiones.GuardaLog(null,$"Error Tareas Programadas 119 error enviar mail --> {ex.Message} "); } } private bool CargarArchivos(FileInfo FInfo, string FTPServer, string FTPUsr, string FTPPass) { bool Respuesta; //var FInfo = new FileInfo(RutaArchivo); if (FInfo.Exists) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"{FTPServer}/{FInfo.Name}"); request.Method = WebRequestMethods.Ftp.UploadFile; int tamanio = 1024; var buffer = new byte[tamanio + 1]; int byteRead = 0; bool Conected = false; request.Credentials = new NetworkCredential(FTPUsr, FTPPass); try { request.GetResponse(); Conected = true; } catch (Exception ex) { Extensiones.ModExtensiones.GuardaLog(null,$"Error Tareas Programadas 119 Conexión a servidor FTP archivo { FInfo.Name } {ex.Message} "); } if (Conected) { Stream ftpStream; FileStream f; ftpStream = request.GetRequestStream(); f = File.OpenRead(FInfo.FullName); try { do { byteRead = f.Read(buffer, 0, tamanio); ftpStream.Write(buffer, 0, byteRead); } while (byteRead != 0); Respuesta = true; } catch (Exception ex) { Respuesta = false; Extensiones.ModExtensiones.GuardaLog(null,$"Error Tareas Programadas 119 cargando archivo { FInfo.Name } {ex.Message} "); } if (f is object) { f.Close(); } if (ftpStream is object) { ftpStream.Close(); } } else { Respuesta = false; // no se conecto al ftp probablemente credenciales erroneas } } else { Respuesta = false; // El archivo no existe en el disco local } return Respuesta; } private bool VerificarArchivo(FileInfo FInfo, long Tamanio, string FTPServer, string FTPUsr, string FTPPass) { bool Respuesta = false; try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"{FTPServer}/{FInfo.Name}"); request.Credentials = new NetworkCredential(FTPUsr, FTPPass); request.Method = WebRequestMethods.Ftp.GetFileSize; request.UseBinary = true; FtpWebResponse loginresponse = (FtpWebResponse)request.GetResponse(); FtpWebResponse respSize = (FtpWebResponse)request.GetResponse(); respSize = (FtpWebResponse)request.GetResponse(); long size = respSize.ContentLength; respSize.Close(); if (Tamanio == size) { Respuesta = true; } }catch(Exception ex) { Extensiones.ModExtensiones.GuardaLog(null,$"Error Tareas Programadas 119 verificando archivo { FInfo.Name } {ex.Message} "); Respuesta = false; } return Respuesta; } private bool PruebaConexionFTP( string FTPServer, string FTPUsr, string FTPPass) { bool Respuesta = false; FtpWebRequest request =(FtpWebRequest)WebRequest.Create($"{FTPServer}/Test.log"); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential(FTPUsr, FTPPass); try { request.GetResponse(); Respuesta = true; } catch (Exception ex) { Extensiones.ModExtensiones.GuardaLog(null, $"Error Tareas Programadas 119 error Prueba de Conexión a servidor FTP archivo {ex.Message} "); } return Respuesta; } public bool IsReusable { get { return false; } } }