diff --git a/App_Code/CalendarEvent.vb b/App_Code/CalendarEvent.vb index 6bd2224a0..316fdb6be 100644 --- a/App_Code/CalendarEvent.vb +++ b/App_Code/CalendarEvent.vb @@ -4,6 +4,8 @@ Public Class CalendarEvent Public Property id As Integer Public Property title As String + Public Property colorfont As String + Public Property description As String Public Property start As String Public Property [end] As String diff --git a/App_Code/modExtensiones.vb b/App_Code/modExtensiones.vb index 2dc7bddd6..4599ce6a7 100644 --- a/App_Code/modExtensiones.vb +++ b/App_Code/modExtensiones.vb @@ -1,23 +1,23 @@ -Option Explicit On -Option Strict On - -Imports System.Data -Imports System.IO -Imports System.Net -Imports System.Net.Http -Imports System.Reflection -Imports System.Security.Cryptography -Imports System.Web.Configuration -Imports System.Web.Http.Controllers -Imports System.Web.Http.Filters -Imports ADServerControl -Imports AjaxControlToolkit -'Imports Microsoft.VisualBasic -'Imports msExcel = Microsoft.Office.Interop.Excel -'Imports VBIDE - -Imports ClosedXML.Excel -Imports GemBox.Spreadsheet +Option Explicit On +Option Strict On + +Imports System.Data +Imports System.IO +Imports System.Net +Imports System.Net.Http +Imports System.Reflection +Imports System.Security.Cryptography +Imports System.Web.Configuration +Imports System.Web.Http.Controllers +Imports System.Web.Http.Filters +Imports ADServerControl +Imports AjaxControlToolkit +'Imports Microsoft.VisualBasic +'Imports msExcel = Microsoft.Office.Interop.Excel +'Imports VBIDE + +Imports ClosedXML.Excel +Imports GemBox.Spreadsheet Imports iText.Kernel.Pdf Imports iText.Kernel.Geom Imports iText.Layout @@ -27,7 +27,7 @@ Imports iText.Layout.Properties Imports Newtonsoft.Json Namespace Extensiones -#Region "E X T E N S I O N E S" +#Region "E X T E N S I O N E S" Public Module ModExtensiones @@ -136,7 +136,7 @@ Namespace Extensiones Return System.Configuration.ConfigurationManager.AppSettings("DirectorioBaseEmpresas").ToString() End If End Get - End Property + End Property Public ReadOnly DirectorioEmpresas As String = String.Format("{0}Empresas\", DirectorioBaseEmpresas) Public ReadOnly Property GOOGLE_MAPS_API_KEY As String @@ -147,20 +147,20 @@ Namespace Extensiones Return System.Configuration.ConfigurationManager.AppSettings("GOOGLE_MAPS_API_KEY").ToString() End If End Get - End Property - - Public Const IMEI As String = "IMEISISTEMAGERENCIAL" - Public Const MinFecha As Date = #1/1/1900# - Public Const MaxFecha As Date = #1/1/9999# + End Property + + Public Const IMEI As String = "IMEISISTEMAGERENCIAL" + Public Const MinFecha As Date = #1/1/1900# + Public Const MaxFecha As Date = #1/1/9999# Public Const GlobalRowVersion As Integer = 555555 -#Region "PropiedadesEncriptación" - Private _Key() As Byte = {} - Private ReadOnly _IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} - Private ReadOnly _IVAES() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF, &H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} - Private Const SEncryptionKey As String = "$Ap7+5&z" +#Region "PropiedadesEncriptación" + Private _Key() As Byte = {} + Private ReadOnly _IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} + Private ReadOnly _IVAES() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF, &H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} + Private Const SEncryptionKey As String = "$Ap7+5&z" Private Const SEncryptionKeyAES As String = "$Ap7+5&z$Ap7+5&z$Ap7+5&z$Ap7+5&z" -#End Region +#End Region Public Function ReadExcelFile(ByVal flatFilePath As String, ByVal firstRowHasHeaders As Boolean, Optional curRow As Integer = 0) As DataTable GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet) @@ -222,23 +222,23 @@ Namespace Extensiones End Function - Public Function IfNull(Valor As Object, Predeterminado As Object, Optional IfNotNull As Object = Nothing) As Object - - If Valor Is Nothing OrElse IsDBNull(Valor) Then ' si es nulo, manda el valor predeterminado - Return Predeterminado - ElseIf IfNotNull Is Nothing Then - Return Valor - Else ' si se envió un valor en el ifnotnull, tiene prioridad con valor - Return IfNotNull - End If - End Function - - Public Function StringNull(Valor As String, Tipo As Integer) As String - If String.IsNullOrEmpty(Valor) Then - Return If(Tipo = 1, "", "0") - Else - Return Valor - End If + Public Function IfNull(Valor As Object, Predeterminado As Object, Optional IfNotNull As Object = Nothing) As Object + + If Valor Is Nothing OrElse IsDBNull(Valor) Then ' si es nulo, manda el valor predeterminado + Return Predeterminado + ElseIf IfNotNull Is Nothing Then + Return Valor + Else ' si se envió un valor en el ifnotnull, tiene prioridad con valor + Return IfNotNull + End If + End Function + + Public Function StringNull(Valor As String, Tipo As Integer) As String + If String.IsNullOrEmpty(Valor) Then + Return If(Tipo = 1, "", "0") + Else + Return Valor + End If End Function Public Function Truncate(value As String, length As Integer) As String @@ -272,8 +272,8 @@ Namespace Extensiones End Class -#Region "Log" - +#Region "Log" + Public Function GetTagValue(Obj As String, tag As String) As String Try Dim Regex As New Regex($"<{tag}>(.*)") @@ -281,351 +281,351 @@ Namespace Extensiones Return match.Groups(1).ToString() Catch ex As Exception Return "" - End Try + End Try End Function - - Public Sub GuardaLog(Str As String, Optional TipoMensaje As TipoMensaje = TipoMensaje.MsgError) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - Dim Urlstring As String = "" - Try - If Not IsNothing(System.Web.HttpContext.Current) Then - If Not IsNothing(System.Web.HttpContext.Current.Request) Then - - Urlstring = $"{HttpContext.Current.Request.Url.LocalPath.ToString()}{HttpContext.Current.Request.Url.Query}{Environment.NewLine}" - End If - End If - Catch - End Try - ' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) - strLineaTMP = String.Format("{0}{1}Log: {5}{2}{3}:{4}", Chr(13), Chr(10), Str, ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, Urlstring) - Try + + Public Sub GuardaLog(Str As String, Optional TipoMensaje As TipoMensaje = TipoMensaje.MsgError) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + Dim Urlstring As String = "" + Try + If Not IsNothing(System.Web.HttpContext.Current) Then + If Not IsNothing(System.Web.HttpContext.Current.Request) Then + + Urlstring = $"{HttpContext.Current.Request.Url.LocalPath.ToString()}{HttpContext.Current.Request.Url.Query}{Environment.NewLine}" + End If + End If + Catch + End Try + ' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) + strLineaTMP = String.Format("{0}{1}Log: {5}{2}{3}:{4}", Chr(13), Chr(10), Str, ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, Urlstring) + Try If TipoMensaje = TipoMensaje.MsgError Then ArchivoW = New StreamWriter(String.Format("{0}\Log\Log.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) Else ArchivoW = New StreamWriter(String.Format("{0}\Log\LognoError.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - End If - Catch ex As UnauthorizedAccessException - 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) - Exit Sub - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.WriteLine(strLineaTMP) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - ''' - ''' Guarda {Mensaje} en LOG en la ruta: /Log/{Archivo}.txt - ''' - ''' Mensaje a guardar - ''' Nombre del archivo donde se guardara el LOG [/Log/{Archivo}.txt] - - Public Sub GuardaLogAD(Mensaje As String, Optional Archivo As String = "Log") - Dim ArchivoW As StreamWriter - - Dim MensajeFormato As String = String.Format("{0}{1}Log: {2} | Fecha:{3}", Chr(13), Chr(10), Mensaje, ClsPaginas.NowADS().ToString("dd/MM/yyyy HH:mm")) - - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\{1}.txt", AppDomain.CurrentDomain.BaseDirectory, Archivo), True, System.Text.Encoding.UTF8) - Catch ex As UnauthorizedAccessException - 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) - Exit Sub - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.WriteLine(MensajeFormato) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - - Public Sub GuardaLog(Obj As Object, pTexto As String) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - - - strLineaTMP = String.Format("{0} {0}{3}{2}:{1}{0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\Log.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.Write(strLineaTMP) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - - Public Sub GuardaLogMail(pTexto As String) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - strLineaTMP = String.Format("{0} {1}:{2} {3} {0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\LogMail.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.Write(strLineaTMP) - Catch - End Try - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - Public Sub GuardaLogTimbrado(Str As String, CvePAC As Integer, Optional Modulo As String = "") - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - - ' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) - strLineaTMP = String.Format("{0}{1} .. PAC: {2} - Modulo: {3} ..{4}:{5}", Chr(13), Chr(10), CvePAC, Modulo, Str, ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString) - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\LogTimbrado.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As UnauthorizedAccessException - 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) - Exit Sub - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.WriteLine(strLineaTMP) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - Public Sub GuardaLogCancelacionSAT(pTexto As String) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - strLineaTMP = String.Format("{0} {1}:{2} {3} {0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) - - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\LogCancelacionSAT.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.Write(strLineaTMP) - Catch - End Try - ArchivoW.Close() - ArchivoW.Dispose() + End If + Catch ex As UnauthorizedAccessException + 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) + Exit Sub + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.WriteLine(strLineaTMP) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() End Sub -#End Region + + ''' + ''' Guarda {Mensaje} en LOG en la ruta: /Log/{Archivo}.txt + ''' + ''' Mensaje a guardar + ''' Nombre del archivo donde se guardara el LOG [/Log/{Archivo}.txt] + + Public Sub GuardaLogAD(Mensaje As String, Optional Archivo As String = "Log") + Dim ArchivoW As StreamWriter + + Dim MensajeFormato As String = String.Format("{0}{1}Log: {2} | Fecha:{3}", Chr(13), Chr(10), Mensaje, ClsPaginas.NowADS().ToString("dd/MM/yyyy HH:mm")) + + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\{1}.txt", AppDomain.CurrentDomain.BaseDirectory, Archivo), True, System.Text.Encoding.UTF8) + Catch ex As UnauthorizedAccessException + 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) + Exit Sub + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.WriteLine(MensajeFormato) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + + + Public Sub GuardaLog(Obj As Object, pTexto As String) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + + + strLineaTMP = String.Format("{0} {0}{3}{2}:{1}{0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\Log.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.Write(strLineaTMP) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + + + Public Sub GuardaLogMail(pTexto As String) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + strLineaTMP = String.Format("{0} {1}:{2} {3} {0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\LogMail.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.Write(strLineaTMP) + Catch + End Try + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + + Public Sub GuardaLogTimbrado(Str As String, CvePAC As Integer, Optional Modulo As String = "") + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + + ' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) + strLineaTMP = String.Format("{0}{1} .. PAC: {2} - Modulo: {3} ..{4}:{5}", Chr(13), Chr(10), CvePAC, Modulo, Str, ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString) + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\LogTimbrado.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As UnauthorizedAccessException + 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) + Exit Sub + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.WriteLine(strLineaTMP) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + + Public Sub GuardaLogCancelacionSAT(pTexto As String) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + strLineaTMP = String.Format("{0} {1}:{2} {3} {0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) + + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\LogCancelacionSAT.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.Write(strLineaTMP) + Catch + End Try + ArchivoW.Close() + ArchivoW.Dispose() + End Sub +#End Region #Region "Alertas y notificaciones" Public Enum TipoUpdate As Integer - NoGuardar = 0 - Guardar = 1 - CalcularYGuardar = 2 - + NoGuardar = 0 + Guardar = 1 + CalcularYGuardar = 2 + End Enum Public Enum TipoMensaje As Integer - MsgError = 1 - MsgInformacion = 2 - MsgConfirmacion = 3 - MsgAdvertencia = 4 - MsgDosBotones = 9 - - ToastInformacion = 5 'succes - ToastInformacionB = 6 'info - ToastError = 7 'error + MsgError = 1 + MsgInformacion = 2 + MsgConfirmacion = 3 + MsgAdvertencia = 4 + MsgDosBotones = 9 + + ToastInformacion = 5 'succes + ToastInformacionB = 6 'info + ToastError = 7 'error ToastAdventencia = 8 'Warning - End Enum - - Public Sub Alert(Obj As Object, Mensaje As String, pOpcion As TipoMensaje, Optional JSBtnAceptar As String = "", Optional TextoConfirmacion As String = "Aceptar", Optional TextoCancelacion As String = "Cancelar", Optional TimeoutToast As Integer = 5, Optional ShowCloseButton As Boolean = True, Optional TextoSegundoBoton As String = "", Optional JSBtn2 As String = "") - If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler.GetType().IsSubclassOf(GetType(Page)) Then - - Dim Titulo As String = "" - Dim Plus As String = ClsPaginas.NowADS().Ticks.ToString - - Dim headerclas As String = "" - Dim showalert As Boolean = True - Mensaje = Mensaje.Replace("'"c, "\'").Replace(vbCrLf, "").Replace("""", "\'").Replace(vbLf, " ") - JSBtnAceptar = JSBtnAceptar.Replace("'"c, "\'") - Dim onEscape As String = "" - Dim b1title As String = "" - Dim b1clas As String = "" - Dim b1js As String = "" - Dim b2title As String = "" - Dim b2clas As String = "hide" - Dim b2js As String = "" - Dim b3title As String = "" - Dim b3clas As String = "hide" - Dim b3js As String = "" - Dim closeButtonOption As String = "" - Select Case pOpcion - Case TipoMensaje.MsgInformacion - Titulo = " Información" - b1title = "Aceptar" - b1clas = "green" - b1js = JSBtnAceptar - onEscape = JSBtnAceptar - headerclas = " header-green " - Case TipoMensaje.MsgConfirmacion - Titulo = " Confirmación" - b1title = TextoConfirmacion - b1clas = "blue" - b1js = JSBtnAceptar - onEscape = "" - b2title = TextoCancelacion - b2clas = "red" - b2js = "" - onEscape = "" + End Enum + + Public Sub Alert(Obj As Object, Mensaje As String, pOpcion As TipoMensaje, Optional JSBtnAceptar As String = "", Optional TextoConfirmacion As String = "Aceptar", Optional TextoCancelacion As String = "Cancelar", Optional TimeoutToast As Integer = 5, Optional ShowCloseButton As Boolean = True, Optional TextoSegundoBoton As String = "", Optional JSBtn2 As String = "") + If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler.GetType().IsSubclassOf(GetType(Page)) Then + + Dim Titulo As String = "" + Dim Plus As String = ClsPaginas.NowADS().Ticks.ToString + + Dim headerclas As String = "" + Dim showalert As Boolean = True + Mensaje = Mensaje.Replace("'"c, "\'").Replace(vbCrLf, "").Replace("""", "\'").Replace(vbLf, " ") + JSBtnAceptar = JSBtnAceptar.Replace("'"c, "\'") + Dim onEscape As String = "" + Dim b1title As String = "" + Dim b1clas As String = "" + Dim b1js As String = "" + Dim b2title As String = "" + Dim b2clas As String = "hide" + Dim b2js As String = "" + Dim b3title As String = "" + Dim b3clas As String = "hide" + Dim b3js As String = "" + Dim closeButtonOption As String = "" + Select Case pOpcion + Case TipoMensaje.MsgInformacion + Titulo = " Información" + b1title = "Aceptar" + b1clas = "green" + b1js = JSBtnAceptar + onEscape = JSBtnAceptar + headerclas = " header-green " + Case TipoMensaje.MsgConfirmacion + Titulo = " Confirmación" + b1title = TextoConfirmacion + b1clas = "blue" + b1js = JSBtnAceptar + onEscape = "" + b2title = TextoCancelacion + b2clas = "red" + b2js = "" + onEscape = "" headerclas = " header-blue " - Case TipoMensaje.MsgDosBotones - Titulo = " Información" - b1title = TextoConfirmacion - b1clas = "green" - b1js = JSBtnAceptar + Case TipoMensaje.MsgDosBotones + Titulo = " Información" + b1title = TextoConfirmacion + b1clas = "green" + b1js = JSBtnAceptar onEscape = "" - b2title = TextoSegundoBoton - b2clas = "blue" - b2js = JSBtn2 - onEscape = "" - headerclas = " header-green " - - Case TipoMensaje.MsgAdvertencia - Titulo = " Advertencia" - b1title = "Aceptar" - b1clas = "yellow" - b1js = JSBtnAceptar - onEscape = JSBtnAceptar - headerclas = " header-yellow " - - Case TipoMensaje.MsgError - Titulo = " Error" - b1title = "Aceptar" - b1clas = "red" - b1js = JSBtnAceptar - onEscape = JSBtnAceptar - headerclas = " header-red " - - Case Else - showalert = False - End Select - - Try - 'No cerrar el alert obliga a hacer click en los botones de opcion + b2title = TextoSegundoBoton + b2clas = "blue" + b2js = JSBtn2 + onEscape = "" + headerclas = " header-green " + + Case TipoMensaje.MsgAdvertencia + Titulo = " Advertencia" + b1title = "Aceptar" + b1clas = "yellow" + b1js = JSBtnAceptar + onEscape = JSBtnAceptar + headerclas = " header-yellow " + + Case TipoMensaje.MsgError + Titulo = " Error" + b1title = "Aceptar" + b1clas = "red" + b1js = JSBtnAceptar + onEscape = JSBtnAceptar + headerclas = " header-red " + + Case Else + showalert = False + End Select + + Try + 'No cerrar el alert obliga a hacer click en los botones de opcion If Not ShowCloseButton Then closeButtonOption = "backdrop : ""static"", keyboard : false, closeButton: false," - End If - - Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.CurrentHandler, Page) - Dim script As String = "" - If showalert Then - script = String.Format("bootbox.dialog({{message: ""{0} "", className: ""{11}"", {13} onEscape: function() {{ {12} }},title: ""{1}"",buttons: {{ success: {{ label: ""{2}"", className: "" {3}""," & - "callback: function() {{ {4} }} }}, danger: {{ label: ""{5}"", className: "" {6}"",callback: function() {{ {7} }} }}," & - "main: {{ label: ""{8}"", className: "" {9}"", callback: function() {{ {10} }} }} }} }});", - Mensaje, Titulo, b3title, b3clas, b3js, b2title, b2clas, b2js, b1title, b1clas, b1js, headerclas, onEscape, closeButtonOption) - Else - - script = String.Format("alertatoast({3},'{0}',function(){{{1}}},{2});", Mensaje, JSBtnAceptar, TimeoutToast, DirectCast(pOpcion, Integer)) - End If - ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), String.Format("Alert{0}", (ClsPaginas.NowADS().Ticks + 1).ToString()), script, True) - Pag = Nothing - Catch ex As Exception - Mensaje.GuardaLog(String.Format("Error Alert : {0}", Mensaje)) - End Try - 'Alerta = Nothing - End If - - End Sub - - - Public Sub Alert2(Obj As Object, Mensaje As String, pOpcion As TipoMensaje, Optional JSBtnAceptar As String = "") - - If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler IsNot Nothing Then - Dim Img, Botones As String - Dim Titulo As String - Dim Plus As String = ClsPaginas.NowADS().Ticks.ToString - - Mensaje = Mensaje.Replace("'"c, "\'").Replace(vbCrLf, "") - JSBtnAceptar = JSBtnAceptar.Replace("'"c, "\'") - - Select Case pOpcion - Case TipoMensaje.MsgInformacion - Titulo = "Información" - Img = "I" - Botones = "1" - Case TipoMensaje.MsgConfirmacion - Titulo = "Confirmación" - Img = "C" - Botones = "2" - Case TipoMensaje.MsgAdvertencia - Titulo = "Advertencia" - Img = "A" - Botones = "1" - Case Else - Titulo = "Error" - Img = "E" - Botones = "1" - End Select - - Try - Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.CurrentHandler, Page) - 'ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), (NowADS().Ticks + 1).ToString(), "MuestraAlert('" & Alerta.ToString() & "', '" & Plus & "');", True) - ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), (ClsPaginas.NowADS().Ticks + 1).ToString(), String.Format("MuestraAlerta('{0}','{1}','{2}','{3}','{4}');", Titulo, Mensaje, Img, Botones, JSBtnAceptar), True) - Pag = Nothing - Catch ex As Exception - + End If + + Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.CurrentHandler, Page) + Dim script As String = "" + If showalert Then + script = String.Format("bootbox.dialog({{message: ""{0} "", className: ""{11}"", {13} onEscape: function() {{ {12} }},title: ""{1}"",buttons: {{ success: {{ label: ""{2}"", className: "" {3}""," & + "callback: function() {{ {4} }} }}, danger: {{ label: ""{5}"", className: "" {6}"",callback: function() {{ {7} }} }}," & + "main: {{ label: ""{8}"", className: "" {9}"", callback: function() {{ {10} }} }} }} }});", + Mensaje, Titulo, b3title, b3clas, b3js, b2title, b2clas, b2js, b1title, b1clas, b1js, headerclas, onEscape, closeButtonOption) + Else + + script = String.Format("alertatoast({3},'{0}',function(){{{1}}},{2});", Mensaje, JSBtnAceptar, TimeoutToast, DirectCast(pOpcion, Integer)) + End If + ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), String.Format("Alert{0}", (ClsPaginas.NowADS().Ticks + 1).ToString()), script, True) + Pag = Nothing + Catch ex As Exception + Mensaje.GuardaLog(String.Format("Error Alert : {0}", Mensaje)) End Try - End If - - End Sub - - + 'Alerta = Nothing + End If + + End Sub + + + Public Sub Alert2(Obj As Object, Mensaje As String, pOpcion As TipoMensaje, Optional JSBtnAceptar As String = "") + + If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler IsNot Nothing Then + Dim Img, Botones As String + Dim Titulo As String + Dim Plus As String = ClsPaginas.NowADS().Ticks.ToString + + Mensaje = Mensaje.Replace("'"c, "\'").Replace(vbCrLf, "") + JSBtnAceptar = JSBtnAceptar.Replace("'"c, "\'") + + Select Case pOpcion + Case TipoMensaje.MsgInformacion + Titulo = "Información" + Img = "I" + Botones = "1" + Case TipoMensaje.MsgConfirmacion + Titulo = "Confirmación" + Img = "C" + Botones = "2" + Case TipoMensaje.MsgAdvertencia + Titulo = "Advertencia" + Img = "A" + Botones = "1" + Case Else + Titulo = "Error" + Img = "E" + Botones = "1" + End Select + + Try + Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.CurrentHandler, Page) + 'ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), (NowADS().Ticks + 1).ToString(), "MuestraAlert('" & Alerta.ToString() & "', '" & Plus & "');", True) + ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), (ClsPaginas.NowADS().Ticks + 1).ToString(), String.Format("MuestraAlerta('{0}','{1}','{2}','{3}','{4}');", Titulo, Mensaje, Img, Botones, JSBtnAceptar), True) + Pag = Nothing + Catch ex As Exception + + End Try + End If + + End Sub + + Public Sub OnError(Obj As Object, Mensaje As String, Exeption As Exception, Optional InfoAdicional As String = "", Optional TipoMensaje As TipoMensaje = TipoMensaje.MsgError) - Dim oldMessage = Mensaje.ToString() - Dim resultado = CLSErrorMessage.GetErrorMesagge(Mensaje, Exeption, TipoMensaje) + Dim oldMessage = Mensaje.ToString() + Dim resultado = CLSErrorMessage.GetErrorMesagge(Mensaje, Exeption, TipoMensaje) Mensaje = resultado.Item1 TipoMensaje = resultado.Item2 GuardaLog(String.Format("{0} DESCRIPCIÓN DETALLADA: {1} {2} {3}", oldMessage, Exeption.ToString, vbCrLf, InfoAdicional), TipoMensaje) - Alert(Obj, Mensaje, TipoMensaje) - If WebConfigurationManager.AppSettings("SiteName") IsNot Nothing AndAlso WebConfigurationManager.AppSettings("SiteName").ToString = "1" Then MandaCorreoError(String.Format("{0} DESCRIPCIÓN DETALLADA: {1} {2} {3}", Mensaje, Exeption.ToString, vbCrLf, InfoAdicional)) - End Sub - - - ''' - ''' item de la lista de notificaciones - ''' - ''' Mensaje a mostrar en la nota. - ''' etiqueta de tiempo: ahora, hace 3 minutos, 10 minutos, 12/3/2015 - ''' Icono clase example fa fa-bell-o - ''' 'danger','success','warning','info' - ''' - Public Function ItemNotificaciones(Mensaje As String, Optional Fecha As String = "", Optional Ico As String = "fa fa-bell-o", Optional Tipo As String = "info", Optional Link As String = "javascript:;", Optional tonewpage As Boolean = True) As String - Dim Time As String = "" - If Fecha <> "" Then Time = String.Format("{0}", Fecha) - Return String.Format("
  • {0}{3}
  • ", Time, Tipo, Ico, Mensaje, Link, If(tonewpage, "target=""_blank""", "")) + Alert(Obj, Mensaje, TipoMensaje) + If WebConfigurationManager.AppSettings("SiteName") IsNot Nothing AndAlso WebConfigurationManager.AppSettings("SiteName").ToString = "1" Then MandaCorreoError(String.Format("{0} DESCRIPCIÓN DETALLADA: {1} {2} {3}", Mensaje, Exeption.ToString, vbCrLf, InfoAdicional)) + End Sub + + + ''' + ''' item de la lista de notificaciones + ''' + ''' Mensaje a mostrar en la nota. + ''' etiqueta de tiempo: ahora, hace 3 minutos, 10 minutos, 12/3/2015 + ''' Icono clase example fa fa-bell-o + ''' 'danger','success','warning','info' + ''' + Public Function ItemNotificaciones(Mensaje As String, Optional Fecha As String = "", Optional Ico As String = "fa fa-bell-o", Optional Tipo As String = "info", Optional Link As String = "javascript:;", Optional tonewpage As Boolean = True) As String + Dim Time As String = "" + If Fecha <> "" Then Time = String.Format("{0}", Fecha) + Return String.Format("
  • {0}{3}
  • ", Time, Tipo, Ico, Mensaje, Link, If(tonewpage, "target=""_blank""", "")) End Function Public Function EnviarNotificacionWhatsApp(NumeroTelefono As String, Mensaje As String) As Boolean @@ -667,41 +667,41 @@ Namespace Extensiones Return Retorno End Function -#End Region +#End Region -#Region "files dropzone" +#Region "files dropzone" - - Public Function getfiles(txt As TextBox) As Files - Dim retorno As New Files - If txt.Text.Trim <> "" Then - Try - Dim files = JsonConvert.DeserializeObject(Of Files)(String.Format("{{ Archivos:{0} }}", txt.Text)) - If Not IsNothing(files) Then - retorno = files - End If - Catch ex As Exception - Alert("", "Ocurrio un errror al obtener los archivos", TipoMensaje.MsgAdvertencia) - End Try - End If - If retorno.Archivos Is Nothing Then - retorno.Archivos = New List(Of Archivo) - End If - Return retorno - End Function - - Public Function FilesMove(oldName As String, newName As String, newDirectorio As String, Optional Sobreescribir As Boolean = False, Optional ConcatenarDirectorioBase As Boolean = True) As Boolean - Dim retorno As Boolean = True - Dim directorioOld As New StringBuilder - Dim directorioNew As New StringBuilder - directorioOld.AppendFormat("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, oldName) - If newName = "" Then - newName = oldName - Else - newName = String.Format("{0}{1}", newName, System.IO.Path.GetExtension(directorioOld.ToString())) - End If - - 'SI VA A LA CARPETA DE EMPRESAS TIENE QUE TOMAR LA RUTA DE EMPRESAS + + Public Function getfiles(txt As TextBox) As Files + Dim retorno As New Files + If txt.Text.Trim <> "" Then + Try + Dim files = JsonConvert.DeserializeObject(Of Files)(String.Format("{{ Archivos:{0} }}", txt.Text)) + If Not IsNothing(files) Then + retorno = files + End If + Catch ex As Exception + Alert("", "Ocurrio un errror al obtener los archivos", TipoMensaje.MsgAdvertencia) + End Try + End If + If retorno.Archivos Is Nothing Then + retorno.Archivos = New List(Of Archivo) + End If + Return retorno + End Function + + Public Function FilesMove(oldName As String, newName As String, newDirectorio As String, Optional Sobreescribir As Boolean = False, Optional ConcatenarDirectorioBase As Boolean = True) As Boolean + Dim retorno As Boolean = True + Dim directorioOld As New StringBuilder + Dim directorioNew As New StringBuilder + directorioOld.AppendFormat("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, oldName) + If newName = "" Then + newName = oldName + Else + newName = String.Format("{0}{1}", newName, System.IO.Path.GetExtension(directorioOld.ToString())) + End If + + 'SI VA A LA CARPETA DE EMPRESAS TIENE QUE TOMAR LA RUTA DE EMPRESAS If ConcatenarDirectorioBase Then If newDirectorio.Contains("Empresas") Then directorioNew.AppendFormat("{0}{1}\", ModExtensiones.DirectorioBaseEmpresas, newDirectorio) @@ -711,25 +711,25 @@ Namespace Extensiones Else 'SI YA TIENE EL DIRECTORIO COMPLETO NO CONCANTENA EL DIRECTORIO directorioNew.AppendFormat("{0}\", newDirectorio) - End If + End If - If Not Directory.Exists(directorioNew.ToString) Then - Directory.CreateDirectory(directorioNew.ToString) - End If - - directorioNew.Append(newName) - Try - My.Computer.FileSystem.MoveFile(directorioOld.ToString, directorioNew.ToString, Sobreescribir) - Catch ex As Exception - Alert("", String.Format("{0} code[FilesMove]", ex.Message), TipoMensaje.MsgAdvertencia) - retorno = False - End Try + If Not Directory.Exists(directorioNew.ToString) Then + Directory.CreateDirectory(directorioNew.ToString) + End If + + directorioNew.Append(newName) + Try + My.Computer.FileSystem.MoveFile(directorioOld.ToString, directorioNew.ToString, Sobreescribir) + Catch ex As Exception + Alert("", String.Format("{0} code[FilesMove]", ex.Message), TipoMensaje.MsgAdvertencia) + retorno = False + End Try directorioOld.Clear() directorioNew.Clear() - Return retorno - End Function - + Return retorno + End Function + Public Function FilesCopy(oldName As String, newName As String, newDirectorio As String, Optional Sobreescribir As Boolean = False, Optional ConcatenarDirectorioBase As Boolean = True) As Boolean Dim retorno As Boolean = True @@ -770,399 +770,399 @@ Namespace Extensiones directorioOld.Clear() directorioNew.Clear() Return retorno - End Function - - - Public Function DirectoryExistsCreate(ByRef NombreDirectorio As String) As Boolean - - 'Verifico que no exista el directory y que se halla creado, si se creo el directorio regresa true - Return Not Directory.Exists(NombreDirectorio) AndAlso Directory.CreateDirectory(NombreDirectorio) IsNot Nothing - - End Function -#End Region - -#Region " obj to entero date, double, etc. formato numero" - - Public Function ToEnterodb(Obj As SqlClient.SqlDataReader, key As String) As Integer - If IsDBNull(Obj(key)) Then - Return 0 - Else - Return CInt(Obj(key)) - End If - End Function - - Public Function ToDoubledb(Obj As SqlClient.SqlDataReader, key As String) As Double - If IsDBNull(Obj(key)) Then - Return 0 - Else - Return CDbl(Obj(key)) - End If End Function - + + Public Function DirectoryExistsCreate(ByRef NombreDirectorio As String) As Boolean + + 'Verifico que no exista el directory y que se halla creado, si se creo el directorio regresa true + Return Not Directory.Exists(NombreDirectorio) AndAlso Directory.CreateDirectory(NombreDirectorio) IsNot Nothing + + End Function +#End Region + +#Region " obj to entero date, double, etc. formato numero" + + Public Function ToEnterodb(Obj As SqlClient.SqlDataReader, key As String) As Integer + If IsDBNull(Obj(key)) Then + Return 0 + Else + Return CInt(Obj(key)) + End If + End Function + + Public Function ToDoubledb(Obj As SqlClient.SqlDataReader, key As String) As Double + If IsDBNull(Obj(key)) Then + Return 0 + Else + Return CDbl(Obj(key)) + End If + End Function + + Public Function ToEntero(Obj As Object) As Integer - If Obj IsNot Nothing AndAlso Obj.ToString.Trim <> "" Then ' porque provoca desbordamiento si pasa mas de una cantidad,Holds signed 32-bit (4-byte) integers that range in value from -2,147,483,648 through 2,147,483,647. - Dim Str As String = HttpUtility.HtmlDecode(Obj.ToString.Trim).Replace(","c, "") - 'si es numerico, si no excede a 10 caracteres, convierte el valor a entero, si excede de 10 digitos, verifica la cantidad permitida. si es menor a su dato, se valida - Return If(IsNumeric(Str), If(Str.Length < 10, CInt(Str), If(CDec(Str) < Int32.MaxValue, CInt(Str), 0)), 0) - Else - Return 0 - End If - End Function - - - Public Function ToLong(Obj As Object) As Long - If Obj IsNot Nothing AndAlso Obj.ToString.Trim <> "" Then - Return If(IsNumeric(Obj), CLng(Obj), 0) - Else - Return 0 - End If - End Function - - - Public Function ToDouble(Str As String, Optional TipoCambio As Double = 1) As Double - Str = HttpUtility.HtmlDecode(Str).Trim.Replace(","c, "") - If Str <> "" Then - Return If(IsNumeric(Str), CDbl(Str) * TipoCambio, 0) - Else - Return 0 - End If - End Function - - - Public Function ToDecimal(Str As String, Optional TipoCambio As Decimal = 1) As Decimal - Str = HttpUtility.HtmlDecode(Str).Trim.Replace(","c, "") - If Str <> "" Then - Return If(IsNumeric(Str), CDec(Str) * TipoCambio, 0) - Else - Return 0 - End If - End Function - - - Public Function ToDecimal(Str As Double, Optional TipoCambio As Decimal = 1) As Decimal - - Return CDec(Str) * TipoCambio - - End Function - - - Public Function TruncateDecimal(value As Decimal, Optional precision As Integer = 2) As Decimal - Dim stepper As Decimal = CDec(Math.Pow(10.0, precision)) - Dim tmp As Decimal = Math.Truncate(stepper * value) - Return tmp / stepper - End Function - - - Public Function ToDate(Str As Object) As Date - If Str IsNot Nothing AndAlso Str.ToString.Trim <> "" AndAlso IsDate(Str.ToString.Trim) Then - Return CDate(Str.ToString.Trim) - Else - Return Nothing - End If - End Function - - - Public Function ToDateTime(Str As Object) As DateTime - If Str IsNot Nothing AndAlso Str.ToString.Trim <> "" AndAlso IsDate(Str.ToString.Trim) Then - Return Convert.ToDateTime(Str.ToString.Trim) - Else - Return Nothing - End If + If Obj IsNot Nothing AndAlso Obj.ToString.Trim <> "" Then ' porque provoca desbordamiento si pasa mas de una cantidad,Holds signed 32-bit (4-byte) integers that range in value from -2,147,483,648 through 2,147,483,647. + Dim Str As String = HttpUtility.HtmlDecode(Obj.ToString.Trim).Replace(","c, "") + 'si es numerico, si no excede a 10 caracteres, convierte el valor a entero, si excede de 10 digitos, verifica la cantidad permitida. si es menor a su dato, se valida + Return If(IsNumeric(Str), If(Str.Length < 10, CInt(Str), If(CDec(Str) < Int32.MaxValue, CInt(Str), 0)), 0) + Else + Return 0 + End If + End Function + + + Public Function ToLong(Obj As Object) As Long + If Obj IsNot Nothing AndAlso Obj.ToString.Trim <> "" Then + Return If(IsNumeric(Obj), CLng(Obj), 0) + Else + Return 0 + End If + End Function + + + Public Function ToDouble(Str As String, Optional TipoCambio As Double = 1) As Double + Str = HttpUtility.HtmlDecode(Str).Trim.Replace(","c, "") + If Str <> "" Then + Return If(IsNumeric(Str), CDbl(Str) * TipoCambio, 0) + Else + Return 0 + End If + End Function + + + Public Function ToDecimal(Str As String, Optional TipoCambio As Decimal = 1) As Decimal + Str = HttpUtility.HtmlDecode(Str).Trim.Replace(","c, "") + If Str <> "" Then + Return If(IsNumeric(Str), CDec(Str) * TipoCambio, 0) + Else + Return 0 + End If + End Function + + + Public Function ToDecimal(Str As Double, Optional TipoCambio As Decimal = 1) As Decimal + + Return CDec(Str) * TipoCambio + + End Function + + + Public Function TruncateDecimal(value As Decimal, Optional precision As Integer = 2) As Decimal + Dim stepper As Decimal = CDec(Math.Pow(10.0, precision)) + Dim tmp As Decimal = Math.Truncate(stepper * value) + Return tmp / stepper + End Function + + + Public Function ToDate(Str As Object) As Date + If Str IsNot Nothing AndAlso Str.ToString.Trim <> "" AndAlso IsDate(Str.ToString.Trim) Then + Return CDate(Str.ToString.Trim) + Else + Return Nothing + End If + End Function + + + Public Function ToDateTime(Str As Object) As DateTime + If Str IsNot Nothing AndAlso Str.ToString.Trim <> "" AndAlso IsDate(Str.ToString.Trim) Then + Return Convert.ToDateTime(Str.ToString.Trim) + Else + Return Nothing + End If End Function - - Public Function ToDateTimeExcat(Str As String, Optional format As String = "dd/MM/yyyy HH:mm") As DateTime + + Public Function ToDateTimeExcat(Str As String, Optional format As String = "dd/MM/yyyy HH:mm") As DateTime Dim fecha As DateTime = New DateTime() DateTime.TryParseExact(Str, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, fecha) Return fecha - End Function - + End Function + Public Function ToBool(Str As String) As Boolean - If Str <> "" Then + If Str <> "" Then Str = HttpUtility.HtmlDecode(Str).Trim Return CBool(Str) - Else - Return False - End If - End Function - - - Public Function FormatoNumero(Str As String, Optional Decimales As Integer = 2) As String - Dim Tmp As String - If IsNumeric(Str.Trim) Then - Tmp = FormatNumber(Str.Trim, Decimales) - Else - Tmp = "0" - End If - Return Tmp - End Function - - - Public Function FormatoNumero(Str As Double, Optional Decimales As Integer = 2) As String - Dim Tmp As String - If IsNumeric(Str) Then - Tmp = FormatNumber(Str, Decimales) - Else - Tmp = "0" - End If - Return Tmp - End Function - - - Public Function FormatoNumero(Str As Decimal, Optional Decimales As Integer = 2) As String - Dim Tmp As String - If IsNumeric(Str) Then - Tmp = FormatNumber(Str, Decimales) - Else - Tmp = "0" - End If - Return Tmp - End Function - + Else + Return False + End If + End Function + + + Public Function FormatoNumero(Str As String, Optional Decimales As Integer = 2) As String + Dim Tmp As String + If IsNumeric(Str.Trim) Then + Tmp = FormatNumber(Str.Trim, Decimales) + Else + Tmp = "0" + End If + Return Tmp + End Function + + + Public Function FormatoNumero(Str As Double, Optional Decimales As Integer = 2) As String + Dim Tmp As String + If IsNumeric(Str) Then + Tmp = FormatNumber(Str, Decimales) + Else + Tmp = "0" + End If + Return Tmp + End Function + + + Public Function FormatoNumero(Str As Decimal, Optional Decimales As Integer = 2) As String + Dim Tmp As String + If IsNumeric(Str) Then + Tmp = FormatNumber(Str, Decimales) + Else + Tmp = "0" + End If + Return Tmp + End Function + Public Function SubStringADS(Str As String, Longitud As Integer) As String - Return Str.Substring(0, If(Str.Length > Longitud, Longitud, Str.Length)) - End Function - - - Public Function Texto2Letras(ByVal Importe As Decimal, Optional CveMoneda As Integer = 1) As String - Dim Moneda, AbrevMoneda As String - Select Case CveMoneda - Case 2 : Moneda = "Dólares" : AbrevMoneda = "USD" - Case 3 : Moneda = "Euro" : AbrevMoneda = "EUR" - Case Else - Moneda = "pesos" : AbrevMoneda = "M.N." - End Select - - If Importe = 0 Then - Return String.Format("cero {0} 00/100 {1}", Moneda, AbrevMoneda) - End If - - Dim Retorno As String - Dim Numero As String = Importe.ToString("F2") ' no se usa N2,porque pone comma, y F2, no la pone - '********Declara variables de tipo cadena************ - Dim entero, dec, flag As String - Dim palabras As New StringBuilder - dec = "" - entero = "" - - '********Declara variables de tipo entero*********** - Dim num, x, y As Integer - - flag = "N" - - '**********Número Negativo*********** - If Mid(Numero, 1, 1) = "-" Then - Numero = Mid(Numero, 2, Numero.ToString.Length - 1).ToString - palabras.Append("menos ") - End If - - '**********Si tiene ceros a la izquierda************* - For x = 1 To Numero.ToString.Length - If Mid(Numero, 1, 1) = "0" Then - Numero = Trim(Mid(Numero, 2, Numero.ToString.Length).ToString) - If Numero.ToString.Length = 0 Then palabras.Clear() - Else - Exit For - End If - Next - - '*********Dividir parte entera y decimal************ - For y = 1 To Len(Numero) - If Mid(Numero, y, 1) = "." Then - flag = "S" - Else - If flag = "N" Then - entero = entero + Mid(Numero, y, 1) - Else - dec = dec + Mid(Numero, y, 1) - End If - End If - Next y - - 'If Len(dec) = 1 Then dec = dec & "0" - dec = dec.PadRight(2, "0"c) - - '**********proceso de conversión*********** - flag = "N" - - If Val(Numero) <= 999999999 Then - For y = Len(entero) To 1 Step -1 - num = Len(entero) - (y - 1) - Select Case y - Case 3, 6, 9 - '**********Asigna las palabras para las centenas*********** - Select Case Mid(entero, num, 1) - Case "1" - If Mid(entero, num + 1, 1) = "0" And Mid(entero, num + 2, 1) = "0" Then - palabras.Append("cien ") - Else - palabras.Append("ciento ") - End If - Case "2" - palabras.Append("doscientos ") - Case "3" - palabras.Append("trescientos ") - Case "4" - palabras.Append("cuatrocientos ") - Case "5" - palabras.Append("quinientos ") - Case "6" - palabras.Append("seiscientos ") - Case "7" - palabras.Append("setecientos ") - Case "8" - palabras.Append("ochocientos ") - Case "9" - palabras.Append("novecientos ") - End Select - Case 2, 5, 8 - '*********Asigna las palabras para las decenas************ - Select Case Mid(entero, num, 1) - Case "0" - 'CASO:260,505.81 - flag = "N" - Case "1" - If Mid(entero, num + 1, 1) = "0" Then - flag = "S" - palabras.Append("diez ") - End If - If Mid(entero, num + 1, 1) = "1" Then - flag = "S" - palabras.Append("once ") - End If - If Mid(entero, num + 1, 1) = "2" Then - flag = "S" - palabras.Append("doce ") - End If - If Mid(entero, num + 1, 1) = "3" Then - flag = "S" - palabras.Append("trece ") - End If - If Mid(entero, num + 1, 1) = "4" Then - flag = "S" - palabras.Append("catorce ") - End If - If Mid(entero, num + 1, 1) = "5" Then - flag = "S" - palabras.Append("quince ") - End If - If Mid(entero, num + 1, 1) > "5" Then - flag = "N" - palabras.Append("dieci") - End If - Case "2" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("veinte ") - flag = "S" - Else - palabras.Append("veinti") - flag = "N" - End If - Case "3" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("treinta ") - flag = "S" - Else - palabras.Append("treinta y ") - flag = "N" - End If - Case "4" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("cuarenta ") - flag = "S" - Else - palabras.Append("cuarenta y ") - flag = "N" - End If - Case "5" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("cincuenta ") - flag = "S" - Else - palabras.Append("cincuenta y ") - flag = "N" - End If - Case "6" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("sesenta ") - flag = "S" - Else - palabras.Append("sesenta y ") - flag = "N" - End If - Case "7" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("setenta ") - flag = "S" - Else - palabras.Append("setenta y ") - flag = "N" - End If - Case "8" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("ochenta ") - flag = "S" - Else - palabras.Append("ochenta y ") - flag = "N" - End If - Case "9" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("noventa ") - flag = "S" - Else - palabras.Append("noventa y ") - flag = "N" - End If - End Select - Case 1, 4, 7 - '*********Asigna las palabras para las unidades********* - Select Case Mid(entero, num, 1) - Case "1" - If flag = "N" Then - If y = 1 Then - palabras.Append("uno ") - Else - palabras.Append("un ") - End If - End If - Case "2" - If flag = "N" Then palabras.Append("dos ") - Case "3" - If flag = "N" Then palabras.Append("tres ") - Case "4" - If flag = "N" Then palabras.Append("cuatro ") - Case "5" - If flag = "N" Then palabras.Append("cinco ") - Case "6" - If flag = "N" Then palabras.Append("seis ") - Case "7" - If flag = "N" Then palabras.Append("siete ") - Case "8" - If flag = "N" Then palabras.Append("ocho ") - Case "9" - If flag = "N" Then palabras.Append("nueve ") - End Select - End Select - - '***********Asigna la palabra mil*************** - If y = 4 Then - - If (Mid(entero, 4, 1) <> "0") Or - (Mid(entero, 2, 1) <> "0") Or - (Mid(entero, 4, 1) = "0" And (Len(entero) >= 4 And Len(entero) <= 6)) Or - (Mid(entero, 5, 1) <> "0" And Len(entero) = 5) Or - (Mid(entero, 6, 1) <> "0" And Len(entero) = 6) Or - (Mid(entero, 5, 1) = "0" And Len(entero) = 7) Or - (Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) <= 5) Or - (Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) <= 6) Or - (Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) < 7) Or - (Mid(entero, 8, 1) = "0" And Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) < 8) Or - (Mid(entero, 3, 1) <> "0" And Len(entero) = 7) Or - (Mid(entero, 3, 1) <> "0" And Len(entero) = 8) Or + Return Str.Substring(0, If(Str.Length > Longitud, Longitud, Str.Length)) + End Function + + + Public Function Texto2Letras(ByVal Importe As Decimal, Optional CveMoneda As Integer = 1) As String + Dim Moneda, AbrevMoneda As String + Select Case CveMoneda + Case 2 : Moneda = "Dólares" : AbrevMoneda = "USD" + Case 3 : Moneda = "Euro" : AbrevMoneda = "EUR" + Case Else + Moneda = "pesos" : AbrevMoneda = "M.N." + End Select + + If Importe = 0 Then + Return String.Format("cero {0} 00/100 {1}", Moneda, AbrevMoneda) + End If + + Dim Retorno As String + Dim Numero As String = Importe.ToString("F2") ' no se usa N2,porque pone comma, y F2, no la pone + '********Declara variables de tipo cadena************ + Dim entero, dec, flag As String + Dim palabras As New StringBuilder + dec = "" + entero = "" + + '********Declara variables de tipo entero*********** + Dim num, x, y As Integer + + flag = "N" + + '**********Número Negativo*********** + If Mid(Numero, 1, 1) = "-" Then + Numero = Mid(Numero, 2, Numero.ToString.Length - 1).ToString + palabras.Append("menos ") + End If + + '**********Si tiene ceros a la izquierda************* + For x = 1 To Numero.ToString.Length + If Mid(Numero, 1, 1) = "0" Then + Numero = Trim(Mid(Numero, 2, Numero.ToString.Length).ToString) + If Numero.ToString.Length = 0 Then palabras.Clear() + Else + Exit For + End If + Next + + '*********Dividir parte entera y decimal************ + For y = 1 To Len(Numero) + If Mid(Numero, y, 1) = "." Then + flag = "S" + Else + If flag = "N" Then + entero = entero + Mid(Numero, y, 1) + Else + dec = dec + Mid(Numero, y, 1) + End If + End If + Next y + + 'If Len(dec) = 1 Then dec = dec & "0" + dec = dec.PadRight(2, "0"c) + + '**********proceso de conversión*********** + flag = "N" + + If Val(Numero) <= 999999999 Then + For y = Len(entero) To 1 Step -1 + num = Len(entero) - (y - 1) + Select Case y + Case 3, 6, 9 + '**********Asigna las palabras para las centenas*********** + Select Case Mid(entero, num, 1) + Case "1" + If Mid(entero, num + 1, 1) = "0" And Mid(entero, num + 2, 1) = "0" Then + palabras.Append("cien ") + Else + palabras.Append("ciento ") + End If + Case "2" + palabras.Append("doscientos ") + Case "3" + palabras.Append("trescientos ") + Case "4" + palabras.Append("cuatrocientos ") + Case "5" + palabras.Append("quinientos ") + Case "6" + palabras.Append("seiscientos ") + Case "7" + palabras.Append("setecientos ") + Case "8" + palabras.Append("ochocientos ") + Case "9" + palabras.Append("novecientos ") + End Select + Case 2, 5, 8 + '*********Asigna las palabras para las decenas************ + Select Case Mid(entero, num, 1) + Case "0" + 'CASO:260,505.81 + flag = "N" + Case "1" + If Mid(entero, num + 1, 1) = "0" Then + flag = "S" + palabras.Append("diez ") + End If + If Mid(entero, num + 1, 1) = "1" Then + flag = "S" + palabras.Append("once ") + End If + If Mid(entero, num + 1, 1) = "2" Then + flag = "S" + palabras.Append("doce ") + End If + If Mid(entero, num + 1, 1) = "3" Then + flag = "S" + palabras.Append("trece ") + End If + If Mid(entero, num + 1, 1) = "4" Then + flag = "S" + palabras.Append("catorce ") + End If + If Mid(entero, num + 1, 1) = "5" Then + flag = "S" + palabras.Append("quince ") + End If + If Mid(entero, num + 1, 1) > "5" Then + flag = "N" + palabras.Append("dieci") + End If + Case "2" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("veinte ") + flag = "S" + Else + palabras.Append("veinti") + flag = "N" + End If + Case "3" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("treinta ") + flag = "S" + Else + palabras.Append("treinta y ") + flag = "N" + End If + Case "4" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("cuarenta ") + flag = "S" + Else + palabras.Append("cuarenta y ") + flag = "N" + End If + Case "5" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("cincuenta ") + flag = "S" + Else + palabras.Append("cincuenta y ") + flag = "N" + End If + Case "6" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("sesenta ") + flag = "S" + Else + palabras.Append("sesenta y ") + flag = "N" + End If + Case "7" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("setenta ") + flag = "S" + Else + palabras.Append("setenta y ") + flag = "N" + End If + Case "8" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("ochenta ") + flag = "S" + Else + palabras.Append("ochenta y ") + flag = "N" + End If + Case "9" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("noventa ") + flag = "S" + Else + palabras.Append("noventa y ") + flag = "N" + End If + End Select + Case 1, 4, 7 + '*********Asigna las palabras para las unidades********* + Select Case Mid(entero, num, 1) + Case "1" + If flag = "N" Then + If y = 1 Then + palabras.Append("uno ") + Else + palabras.Append("un ") + End If + End If + Case "2" + If flag = "N" Then palabras.Append("dos ") + Case "3" + If flag = "N" Then palabras.Append("tres ") + Case "4" + If flag = "N" Then palabras.Append("cuatro ") + Case "5" + If flag = "N" Then palabras.Append("cinco ") + Case "6" + If flag = "N" Then palabras.Append("seis ") + Case "7" + If flag = "N" Then palabras.Append("siete ") + Case "8" + If flag = "N" Then palabras.Append("ocho ") + Case "9" + If flag = "N" Then palabras.Append("nueve ") + End Select + End Select + + '***********Asigna la palabra mil*************** + If y = 4 Then + + If (Mid(entero, 4, 1) <> "0") Or + (Mid(entero, 2, 1) <> "0") Or + (Mid(entero, 4, 1) = "0" And (Len(entero) >= 4 And Len(entero) <= 6)) Or + (Mid(entero, 5, 1) <> "0" And Len(entero) = 5) Or + (Mid(entero, 6, 1) <> "0" And Len(entero) = 6) Or + (Mid(entero, 5, 1) = "0" And Len(entero) = 7) Or + (Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) <= 5) Or + (Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) <= 6) Or + (Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) < 7) Or + (Mid(entero, 8, 1) = "0" And Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) < 8) Or + (Mid(entero, 3, 1) <> "0" And Len(entero) = 7) Or + (Mid(entero, 3, 1) <> "0" And Len(entero) = 8) Or (Mid(entero, 8, 1) = "0" And Mid(entero, 8, 1) = "0" And Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) = 9) Then @@ -1178,117 +1178,117 @@ Namespace Extensiones 'Else ' palabras.Append("mil ") - End If - End If - - '**********Asigna la palabra millón************* - If y = 7 Then - If Len(entero) = 7 And Mid(entero, 1, 1) = "1" Then - palabras.Append("millón ") - Else - palabras.Append("millones ") - End If - End If - Next y - - '**********Une la parte entera y la parte decimal************* - If dec <> "" Then - - palabras.AppendFormat("{0} {1}/100 {2}", Moneda, dec, AbrevMoneda) - - Retorno = palabras.ToString - Else - palabras.AppendFormat("{0} {1}/100 {2}", Moneda, dec, AbrevMoneda) - - Retorno = palabras.ToString - End If - Else - Retorno = "" - End If - - Retorno = UCase(Mid(Retorno, 1, 1)) + Mid(Retorno, 2, Len(Retorno)) - - Return Retorno - End Function - - - + End If + End If + + '**********Asigna la palabra millón************* + If y = 7 Then + If Len(entero) = 7 And Mid(entero, 1, 1) = "1" Then + palabras.Append("millón ") + Else + palabras.Append("millones ") + End If + End If + Next y + + '**********Une la parte entera y la parte decimal************* + If dec <> "" Then + + palabras.AppendFormat("{0} {1}/100 {2}", Moneda, dec, AbrevMoneda) + + Retorno = palabras.ToString + Else + palabras.AppendFormat("{0} {1}/100 {2}", Moneda, dec, AbrevMoneda) + + Retorno = palabras.ToString + End If + Else + Retorno = "" + End If + + Retorno = UCase(Mid(Retorno, 1, 1)) + Mid(Retorno, 2, Len(Retorno)) + + Return Retorno + End Function + + + Public Function RoundAD(Valor As Double, Optional Decimales As Integer = 2) As Double Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) End Function Public Function RoundAD(Valor As Decimal, Optional Decimales As Integer = 2) As Decimal Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) - End Function - - + End Function + + Public Function RoundSQL(Valor As Double, Optional Decimales As Integer = 2) As Double 'Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) 'primero, se redondea a 4, para que concuerde al redondeo de sql, si se redondea a 2 decimales por ejemplo - Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) - End Function - - - Public Function RoundSQL(Valor As Decimal, Optional Decimales As Integer = 2) As Decimal - 'primero, se redondea a 4, para que concuerde al redondeo de sql - Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) - End Function - - Public Function Abs(Valor As Double) As Double - Return Math.Abs(Valor) - End Function - - - Public Function Abs(Valor As Decimal) As Decimal - Return Math.Abs(Valor) + Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) + End Function + + + Public Function RoundSQL(Valor As Decimal, Optional Decimales As Integer = 2) As Decimal + 'primero, se redondea a 4, para que concuerde al redondeo de sql + Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) + End Function + + Public Function Abs(Valor As Double) As Double + Return Math.Abs(Valor) + End Function + + + Public Function Abs(Valor As Decimal) As Decimal + Return Math.Abs(Valor) End Function -#End Region +#End Region -#Region "DataTable operation" +#Region "DataTable operation" 'Dejar el parametro 'dt' en ByVal, para que no se autoasigne el valor, en el caso de filtrar lo GlobalDT(ByRef, pierde los valores y solo deja los filtrados) - - Public Function FiltraParametros(dt As DataTable, RowFilter As String, Optional Orderby As String = "", Optional DistinctColumns() As String = Nothing) As DataTable - Dim TmpDt As New DataTable - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - If DistinctColumns IsNot Nothing Then - TmpDt = Dv.ToTable(True, DistinctColumns) - Else - Try - TmpDt = Dv.ToTable - Catch ex As Exception - TmpDt = Nothing - End Try - End If - - Dv.Dispose() - Else - 'Regresamos la misma tabla para que se conserven las columnas. - TmpDt = dt - End If - - Return TmpDt - End Function - - Public Function FiltraPorIndices(dt As DataTable, Inicio As Integer, Fin As Integer) As DataTable - Dim TmpDt As DataTable = dt.Clone() - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - For i As Integer = Inicio To Fin - Dim Row As DataRow = TmpDt.NewRow - Row.ItemArray = dt.Rows(i).ItemArray - TmpDt.Rows.Add(Row) - Next - Else - 'Regresamos la misma tabla para que se conserven las columnas. - TmpDt = dt - End If - - Return TmpDt + + Public Function FiltraParametros(dt As DataTable, RowFilter As String, Optional Orderby As String = "", Optional DistinctColumns() As String = Nothing) As DataTable + Dim TmpDt As New DataTable + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + If DistinctColumns IsNot Nothing Then + TmpDt = Dv.ToTable(True, DistinctColumns) + Else + Try + TmpDt = Dv.ToTable + Catch ex As Exception + TmpDt = Nothing + End Try + End If + + Dv.Dispose() + Else + 'Regresamos la misma tabla para que se conserven las columnas. + TmpDt = dt + End If + + Return TmpDt + End Function + + Public Function FiltraPorIndices(dt As DataTable, Inicio As Integer, Fin As Integer) As DataTable + Dim TmpDt As DataTable = dt.Clone() + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + For i As Integer = Inicio To Fin + Dim Row As DataRow = TmpDt.NewRow + Row.ItemArray = dt.Rows(i).ItemArray + TmpDt.Rows.Add(Row) + Next + Else + 'Regresamos la misma tabla para que se conserven las columnas. + TmpDt = dt + End If + + Return TmpDt End Function - + Public Function GroupByDt(dtt As DataTable, ByVal RowFilter As String, ByVal Orderby As String, ByVal GroupByColumns As String(), ByVal AggregateColumn As String) As DataTable Dim dv As DataView = New DataView(dtt, RowFilter, Orderby, DataViewRowState.CurrentRows) Dim dtGroup As DataTable = dv.ToTable(True, GroupByColumns) @@ -1304,544 +1304,544 @@ Namespace Extensiones Next Return dtGroup - End Function - - - Public Function GroupByDT(dt As DataTable, ByVal RowFilter As String, Optional ByVal Orderby As String = "", - Optional GroupByColumns As String()() = Nothing, Optional SumColumns As String() = Nothing, Optional AVGColumns As String() = Nothing, - Optional MaxColumns As String() = Nothing, Optional MinColumns As String() = Nothing) As DataTable - - Dim TmpDt As New DataTable - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - TmpDt = Dv.ToTable - If GroupByColumns IsNot Nothing Then - Dim dtGrouped As DataTable - TmpDt.AcceptChanges() - Dim indexgrupo As Int32 = 1 - TmpDt.Columns.Add("GroupADSType", System.Type.GetType("System.Int32")) - For Each rowg As DataRow In TmpDt.Rows - rowg("GroupADSType") = 9999 - Next - Dim order2 As New StringBuilder - If GroupByColumns IsNot Nothing Then - For Each item As String() In GroupByColumns - dtGrouped = Dv.ToTable(True, item) - Dim keygrupo As Integer = 1 - TmpDt.Columns.Add(String.Format("GroupADS{0}", indexgrupo), System.Type.GetType("System.Int32")) - For Each GroupRow As DataRow In dtGrouped.Rows - Dim row As DataRow = TmpDt.NewRow - row("GroupADSType") = indexgrupo - row(String.Format("GroupADS{0}", indexgrupo)) = keygrupo - Dim prefix As String = "" - Dim Query As New StringBuilder - For Each groupitem As String In item - row(groupitem) = GroupRow(groupitem) - Dim coltipo As String = TmpDt.Columns(groupitem).DataType.ToString().ToUpper - If GroupRow.IsNull(groupitem) Then - Query.AppendFormat("{0} {1} IS NULL", prefix, groupitem) - Else - If coltipo.Contains("INT") OrElse coltipo.Contains("DECIMAL") OrElse coltipo.Contains("DOUBLE") OrElse coltipo.Contains("BOOLEAN") Then - If GroupRow(groupitem).ToString.Length > 0 Then - Query.AppendFormat("{0}{1}={2} ", prefix, groupitem, GroupRow(groupitem)) - Else - Query.AppendFormat("{0} {1} IS NULL", prefix, groupitem) - End If - Else - Query.AppendFormat("{0}{1}='{2}' ", prefix, groupitem, GroupRow(groupitem)) - End If - End If - prefix = " AND " - Next - Dim rowsgrupo As DataRow() = TmpDt.Select(Query.ToString) - If rowsgrupo IsNot Nothing Then - For Each rowg As DataRow In rowsgrupo - rowg(String.Format("GroupADS{0}", indexgrupo)) = keygrupo - Next - End If - Query.AppendFormat("{0} GroupADSType=9999 ", prefix) - If SumColumns IsNot Nothing Then - - For Each sumitem As String In SumColumns - row(sumitem) = TmpDt.Compute(String.Format("Sum({0})", sumitem), Query.ToString) - Next - End If - If AVGColumns IsNot Nothing Then - - For Each avgitem As String In AVGColumns - row(avgitem) = TmpDt.Compute(String.Format("Avg({0})", avgitem), Query.ToString) - Next - End If - If MaxColumns IsNot Nothing Then - - For Each maxitem As String In MaxColumns - row(maxitem) = TmpDt.Compute(String.Format("Max({0})", maxitem), Query.ToString) - Next - End If - If MinColumns IsNot Nothing Then - - For Each minitem As String In MinColumns - row(minitem) = TmpDt.Compute(String.Format("Min({0})", minitem), Query.ToString) - Next - End If - If indexgrupo = 2 Then - Dim query2 As New StringBuilder - Dim coltipo As String = TmpDt.Columns(item(0)).DataType.ToString().ToUpper - If GroupRow.IsNull(item(0)) Then - query2.AppendFormat("{0} {1} IS NULL", "", item(0)) - Else - If coltipo.Contains("INT") OrElse coltipo.Contains("DECIMAL") OrElse coltipo.Contains("DOUBLE") OrElse coltipo.Contains("BOOLEAN") Then - If row(item(0)).ToString.Length > 0 Then - query2.AppendFormat("{0}{1}={2} ", "", item(0), row(item(0))) - Else - query2.AppendFormat("{0} {1} IS NULL", "", item(0)) - End If - Else - query2.AppendFormat("{0}{1}='{2}' ", "", item(0), row(item(0))) - End If - End If - query2.Append(" AND GroupADSType=1") - - row("GroupADS1") = TmpDt.Select(query2.ToString)(0)("GroupADS1") - End If - TmpDt.Rows.Add(row) - keygrupo += 1 - Next - indexgrupo += 1 - Next - TmpDt.AcceptChanges() - indexgrupo -= 1 - For i As Integer = 1 To indexgrupo Step 1 - order2.AppendFormat("GroupADS{0},", i) - Next - order2.Append("GroupADSType") - If Orderby.Trim.Length > 0 Then - order2.Append(",") - End If - order2.Append(Orderby) - Dv = New DataView(TmpDt, "", order2.ToString, DataViewRowState.CurrentRows) - TmpDt = Dv.ToTable - End If - End If - Dv.Dispose() - ElseIf dt Is Nothing Then - Return New DataTable - Else - Return dt - End If - Return TmpDt - End Function - - - Public Function FiltroPrimero(dt As DataTable, RowFilter As String, Optional Orderby As String = "") As DataRow - - Dim TmpDr As DataRow = Nothing - - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - If RowFilter <> "" Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - If Dv.ToTable.Rows.Count > 0 Then - TmpDr = Dv.ToTable.Rows(0) - End If - Dv.Dispose() - Else - TmpDr = dt.Rows(0) - End If - dt.Dispose() - End If - - Return TmpDr - End Function - - Public Function FiltroPrimeroPK(dt As DataTable, PrimaryKey As String, Valor As String) As DataRow - - Dim TmpDr As DataRow = Nothing - - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - dt.PrimaryKey = New DataColumn() {dt.Columns(PrimaryKey)} - TmpDr = dt.Rows.Find(Valor) - dt.Dispose() - End If - - Return TmpDr - End Function - - Public Function FiltroUltimo(dt As DataTable, RowFilter As String, Optional Orderby As String = "") As DataRow - Dim TmpDr As DataRow = Nothing - - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - If RowFilter <> "" Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - If Dv.ToTable.Rows.Count > 0 Then - TmpDr = Dv.ToTable.Rows(Dv.ToTable.Rows.Count - 1) - End If - Dv.Dispose() - Else - TmpDr = dt.Rows(dt.Rows.Count - 1) - End If - End If - - Return TmpDr - End Function - - - Public Function ToJson(dt As DataTable) As String - Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer() - Dim rows As New List(Of Dictionary(Of String, Object))() - Dim row As Dictionary(Of String, Object) = Nothing - For Each dr As DataRow In dt.Rows - row = New Dictionary(Of String, Object)() - For Each dc As DataColumn In dt.Columns - row.Add(dc.ColumnName.Trim(), dr(dc)) - Next - rows.Add(row) - Next - Return serializer.Serialize(rows) - End Function - - - Public Function DataTableToJSONIPP(ByVal table As DataTable) As String - Dim JSONString As String = String.Empty - JSONString = JsonConvert.SerializeObject(table) - Return JSONString - End Function - - - Public Function FiltroPrimeroValor(dt As DataTable, Columna As String, Optional RowFilter As String = "", Optional Orderby As String = "") As String - - Dim Retorno As String = "" - - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - If RowFilter <> "" Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - If Dv.ToTable.Rows.Count > 0 Then - Retorno = Dv.ToTable.Rows(0)(Columna).ToString - End If - Dv.Dispose() - Else - Retorno = dt.Rows(0)(Columna).ToString - End If - dt.Dispose() - End If - - Return Retorno - End Function - - - - Public Function DBCampo(ByVal Row As GridViewRow, ByVal Columna As String) As String - Return DataBinder.Eval(Row.DataItem, Columna).ToString - End Function - - - Public Function DataKey(ByVal Row As GridViewRow, ByVal Columna As String) As String - Return DirectCast(Row.NamingContainer, GridView).DataKeys(Row.RowIndex).Values(Columna).ToString - End Function - - - Public Function SUM(DT As DataTable, Campo As String, Optional ByVal Filtro As String = "") As Decimal - Return If(DT IsNot Nothing, DT.Compute(String.Format("SUM({0})", Campo), Filtro).ToString.ToDecimal, 0) - End Function - - Public Function SUMD(DT As DataTable, Campo As String, Optional ByVal Filtro As String = "") As Decimal - Return If(DT IsNot Nothing, DT.Compute(String.Format("SUM({0})", Campo), Filtro).ToString.ToDecimal, 0) - End Function - - - Public Function COUNT(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As Integer - Return DT.Compute(String.Format("COUNT({0})", Campo), Filtro).ToString.ToEntero - End Function - - - Public Function MIN(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As String - Return DT.Compute(String.Format("MIN({0})", Campo), Filtro).ToString - End Function - - - Public Function MAX(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As String - Return DT.Compute(String.Format("MAX({0})", Campo), Filtro).ToString - End Function - - - Public Function AVG(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As Double - Return DT.Compute(String.Format("AVG({0})", Campo), Filtro).ToString.ToDouble - End Function - - - Public Function DataRowToObject(Of T)(row As System.Data.DataRow) As T - Dim Obj = Activator.CreateInstance(Of T)() - If Not IsNothing(row) Then - Dim myType As Type = Obj.GetType() - Dim props As IList(Of Reflection.PropertyInfo) = New List(Of Reflection.PropertyInfo)(myType.GetProperties()) - For Each prop As Reflection.PropertyInfo In props - Dim attr = prop.GetCustomAttributesData() - If Not (Not IsNothing(attr) AndAlso Not IsNothing(attr.FirstOrDefault(Function(M) M.AttributeType.Name = "NotMappedAttribute"))) Then - If prop.CanWrite Then - If row.Table.Columns.Contains(prop.Name) AndAlso Not IsDBNull(row(prop.Name)) Then - - Select Case prop.PropertyType.Name - Case "Boolean" - prop.SetValue(Obj, CBool(row(prop.Name))) - Case "Byte" - prop.SetValue(Obj, CByte(row(prop.Name))) - Case "Char" - prop.SetValue(Obj, CChar(row(prop.Name))) - Case "DateTime" - prop.SetValue(Obj, CDate(row(prop.Name))) - Case "Decimal" - prop.SetValue(Obj, CDec(row(prop.Name))) - Case "Double" - prop.SetValue(Obj, CDbl(row(prop.Name))) - Case "Int32" - prop.SetValue(Obj, CInt(row(prop.Name))) - Case "Int64" - prop.SetValue(Obj, CLng(row(prop.Name))) - Case "SByte" - prop.SetValue(Obj, CSByte(row(prop.Name))) - Case "Int16" - prop.SetValue(Obj, CShort(row(prop.Name))) - Case "Single" - prop.SetValue(Obj, CSng(row(prop.Name))) - Case "String" - prop.SetValue(Obj, CStr(row(prop.Name))) - Case "UInt32" - prop.SetValue(Obj, CUInt(row(prop.Name))) - Case "UInt64" - prop.SetValue(Obj, CULng(row(prop.Name))) - Case "UInt16" - prop.SetValue(Obj, CUShort(row(prop.Name))) - End Select - End If - End If - End If - Next - - End If - Return Obj - End Function - - - Public Function DataTableToObject(Of T)(Tablita As System.Data.DataTable) As List(Of T) - Dim retorno As New List(Of T) - If Not IsNothing(Tablita) Then - Dim Obj = Activator.CreateInstance(Of T)() - Dim myType As Type = Obj.GetType() - - Dim props As IList(Of Reflection.PropertyInfo) = New List(Of Reflection.PropertyInfo)(myType.GetProperties()) - For Each row As System.Data.DataRow In Tablita.Rows - Dim CurrentObj As T = Activator.CreateInstance(Of T)() - For Each prop As Reflection.PropertyInfo In props - Dim attr = prop.GetCustomAttributesData() - If Not (Not IsNothing(attr) AndAlso Not IsNothing(attr.FirstOrDefault(Function(M) M.AttributeType.Name = "NotMappedAttribute"))) Then - If prop.CanWrite Then - If row.Table.Columns.Contains(prop.Name) AndAlso Not IsDBNull(row(prop.Name)) Then - Select Case prop.PropertyType.Name - Case "Boolean" - prop.SetValue(CurrentObj, CBool(row(prop.Name))) - Case "Byte" - prop.SetValue(CurrentObj, CByte(row(prop.Name))) - Case "Char" - prop.SetValue(CurrentObj, CChar(row(prop.Name))) - Case "DateTime" - prop.SetValue(CurrentObj, CDate(row(prop.Name))) - Case "Decimal" - prop.SetValue(CurrentObj, CDec(row(prop.Name))) - Case "Double" - prop.SetValue(CurrentObj, CDbl(row(prop.Name))) - Case "Int32" - prop.SetValue(CurrentObj, CInt(row(prop.Name))) - Case "Int64" - prop.SetValue(CurrentObj, CLng(row(prop.Name))) - Case "SByte" - prop.SetValue(CurrentObj, CSByte(row(prop.Name))) - Case "Int16" - prop.SetValue(CurrentObj, CShort(row(prop.Name))) - Case "Single" - prop.SetValue(CurrentObj, CSng(row(prop.Name))) - Case "String" - prop.SetValue(CurrentObj, CStr(row(prop.Name))) - Case "UInt32" - prop.SetValue(CurrentObj, CUInt(row(prop.Name))) - Case "UInt64" - prop.SetValue(CurrentObj, CULng(row(prop.Name))) - Case "UInt16" - prop.SetValue(CurrentObj, CUShort(row(prop.Name))) - End Select - End If - End If - End If - Next - retorno.Add(CurrentObj) - Next - End If - Return retorno - End Function - - Public Function DataTableToJSON(DT As DataTable) As String - Dim Serializer As New System.Web.Script.Serialization.JavaScriptSerializer() - Dim Rows As New List(Of Dictionary(Of String, Object))() - Dim Row As Dictionary(Of String, Object) - For Each DbRow As DataRow In DT.Rows - Row = New Dictionary(Of String, Object)() - For Each Col As DataColumn In DT.Columns - Row.Add(Col.ColumnName, DbRow(Col)) - Next - Rows.Add(Row) - Next - - Return Serializer.Serialize(Rows) - End Function - - - Public Function ColumnNamesDatatable(dt As DataTable) As List(Of String) - Dim names As New List(Of String) - For Each column As DataColumn In dt.Columns - names.Add(column.ColumnName) - Next - Return names End Function -#End Region + + Public Function GroupByDT(dt As DataTable, ByVal RowFilter As String, Optional ByVal Orderby As String = "", + Optional GroupByColumns As String()() = Nothing, Optional SumColumns As String() = Nothing, Optional AVGColumns As String() = Nothing, + Optional MaxColumns As String() = Nothing, Optional MinColumns As String() = Nothing) As DataTable -#Region "gridview operations" + Dim TmpDt As New DataTable + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + TmpDt = Dv.ToTable + If GroupByColumns IsNot Nothing Then + Dim dtGrouped As DataTable + TmpDt.AcceptChanges() + Dim indexgrupo As Int32 = 1 + TmpDt.Columns.Add("GroupADSType", System.Type.GetType("System.Int32")) + For Each rowg As DataRow In TmpDt.Rows + rowg("GroupADSType") = 9999 + Next + Dim order2 As New StringBuilder + If GroupByColumns IsNot Nothing Then + For Each item As String() In GroupByColumns + dtGrouped = Dv.ToTable(True, item) + Dim keygrupo As Integer = 1 + TmpDt.Columns.Add(String.Format("GroupADS{0}", indexgrupo), System.Type.GetType("System.Int32")) + For Each GroupRow As DataRow In dtGrouped.Rows + Dim row As DataRow = TmpDt.NewRow + row("GroupADSType") = indexgrupo + row(String.Format("GroupADS{0}", indexgrupo)) = keygrupo + Dim prefix As String = "" + Dim Query As New StringBuilder + For Each groupitem As String In item + row(groupitem) = GroupRow(groupitem) + Dim coltipo As String = TmpDt.Columns(groupitem).DataType.ToString().ToUpper + If GroupRow.IsNull(groupitem) Then + Query.AppendFormat("{0} {1} IS NULL", prefix, groupitem) + Else + If coltipo.Contains("INT") OrElse coltipo.Contains("DECIMAL") OrElse coltipo.Contains("DOUBLE") OrElse coltipo.Contains("BOOLEAN") Then + If GroupRow(groupitem).ToString.Length > 0 Then + Query.AppendFormat("{0}{1}={2} ", prefix, groupitem, GroupRow(groupitem)) + Else + Query.AppendFormat("{0} {1} IS NULL", prefix, groupitem) + End If + Else + Query.AppendFormat("{0}{1}='{2}' ", prefix, groupitem, GroupRow(groupitem)) + End If + End If + prefix = " AND " + Next + Dim rowsgrupo As DataRow() = TmpDt.Select(Query.ToString) + If rowsgrupo IsNot Nothing Then + For Each rowg As DataRow In rowsgrupo + rowg(String.Format("GroupADS{0}", indexgrupo)) = keygrupo + Next + End If + Query.AppendFormat("{0} GroupADSType=9999 ", prefix) + If SumColumns IsNot Nothing Then - - Public Function FCHyperLink(ByVal Row As GridViewRow, ByVal Control As String) As HyperLink - Return DirectCast(Row.FindControl(Control), HyperLink) - End Function - - - Public Function FCLabel(ByVal Row As GridViewRow, ByVal Control As String) As Label - Return DirectCast(Row.FindControl(Control), Label) - End Function - - - Public Function FCTextBox(ByVal Row As GridViewRow, ByVal Control As String) As TextBox - Return DirectCast(Row.FindControl(Control), TextBox) - End Function - ' - - Public Function FCDropDownList(ByVal Row As GridViewRow, ByVal Control As String) As DropDownList - Return DirectCast(Row.FindControl(Control), DropDownList) - End Function - - - Public Function FCDropDownLost(ByVal Row As GridViewRow, ByVal Control As String) As Dropdownlost - Return DirectCast(Row.FindControl(Control), Dropdownlost) - End Function - - - Public Function FCGridView(ByVal Row As GridViewRow, ByVal Control As String) As GridView - Return DirectCast(Row.FindControl(Control), GridView) - End Function - - - Public Function FCListBox(ByVal Row As GridViewRow, ByVal Control As String) As ListBox - Return DirectCast(Row.FindControl(Control), ListBox) - End Function - - - Public Function FCRadioButton(ByVal Row As GridViewRow, ByVal Control As String) As RadioButton - Return DirectCast(Row.FindControl(Control), RadioButton) - End Function - - - Public Function FCRadioButtonList(ByVal Row As GridViewRow, ByVal Control As String) As RadioButtonList - Return DirectCast(Row.FindControl(Control), RadioButtonList) - End Function - - - Public Function FCLiteral(ByVal Row As GridViewRow, ByVal Control As String) As Literal - Return DirectCast(Row.FindControl(Control), Literal) - End Function - - - - - - Public Function FCFilteredTextBoxExtender(ByVal Row As GridViewRow, ByVal Control As String) As AjaxControlToolkit.FilteredTextBoxExtender - Return DirectCast(Row.FindControl(Control), AjaxControlToolkit.FilteredTextBoxExtender) - End Function - - - Public Function FCCalendarExtender(ByVal Row As GridViewRow, ByVal Control As String) As AjaxControlToolkit.CalendarExtender - Return DirectCast(Row.FindControl(Control), AjaxControlToolkit.CalendarExtender) - End Function - - - Public Function FCCompareValidator(ByVal Row As GridViewRow, ByVal Control As String) As CompareValidator - Return DirectCast(Row.FindControl(Control), CompareValidator) - End Function - - - Public Function FCImageButton(ByVal Row As GridViewRow, ByVal Control As String) As ImageButton - Return DirectCast(Row.FindControl(Control), ImageButton) - End Function - - - Public Function FCLinkButton(ByVal Row As GridViewRow, ByVal Control As String) As LinkButton - Return DirectCast(Row.FindControl(Control), LinkButton) - End Function - - - Public Function FCImage(ByVal Row As GridViewRow, ByVal Control As String) As Image - Return DirectCast(Row.FindControl(Control), Image) - End Function - - - Public Function FCCheckBox(ByVal Row As GridViewRow, ByVal Control As String) As CheckBox - Return DirectCast(Row.FindControl(Control), CheckBox) - End Function - - - Public Function FCHiddenField(ByVal Row As GridViewRow, ByVal Control As String) As HiddenField - Return DirectCast(Row.FindControl(Control), HiddenField) - End Function - - - Public Function FCButton(ByVal Row As GridViewRow, ByVal Control As String) As Button - Return DirectCast(Row.FindControl(Control), Button) + For Each sumitem As String In SumColumns + row(sumitem) = TmpDt.Compute(String.Format("Sum({0})", sumitem), Query.ToString) + Next + End If + If AVGColumns IsNot Nothing Then + + For Each avgitem As String In AVGColumns + row(avgitem) = TmpDt.Compute(String.Format("Avg({0})", avgitem), Query.ToString) + Next + End If + If MaxColumns IsNot Nothing Then + + For Each maxitem As String In MaxColumns + row(maxitem) = TmpDt.Compute(String.Format("Max({0})", maxitem), Query.ToString) + Next + End If + If MinColumns IsNot Nothing Then + + For Each minitem As String In MinColumns + row(minitem) = TmpDt.Compute(String.Format("Min({0})", minitem), Query.ToString) + Next + End If + If indexgrupo = 2 Then + Dim query2 As New StringBuilder + Dim coltipo As String = TmpDt.Columns(item(0)).DataType.ToString().ToUpper + If GroupRow.IsNull(item(0)) Then + query2.AppendFormat("{0} {1} IS NULL", "", item(0)) + Else + If coltipo.Contains("INT") OrElse coltipo.Contains("DECIMAL") OrElse coltipo.Contains("DOUBLE") OrElse coltipo.Contains("BOOLEAN") Then + If row(item(0)).ToString.Length > 0 Then + query2.AppendFormat("{0}{1}={2} ", "", item(0), row(item(0))) + Else + query2.AppendFormat("{0} {1} IS NULL", "", item(0)) + End If + Else + query2.AppendFormat("{0}{1}='{2}' ", "", item(0), row(item(0))) + End If + End If + query2.Append(" AND GroupADSType=1") + + row("GroupADS1") = TmpDt.Select(query2.ToString)(0)("GroupADS1") + End If + TmpDt.Rows.Add(row) + keygrupo += 1 + Next + indexgrupo += 1 + Next + TmpDt.AcceptChanges() + indexgrupo -= 1 + For i As Integer = 1 To indexgrupo Step 1 + order2.AppendFormat("GroupADS{0},", i) + Next + order2.Append("GroupADSType") + If Orderby.Trim.Length > 0 Then + order2.Append(",") + End If + order2.Append(Orderby) + Dv = New DataView(TmpDt, "", order2.ToString, DataViewRowState.CurrentRows) + TmpDt = Dv.ToTable + End If + End If + Dv.Dispose() + ElseIf dt Is Nothing Then + Return New DataTable + Else + Return dt + End If + Return TmpDt End Function - - Public Function FCHtmlTableRow(ByVal Row As GridViewRow, ByVal Control As String) As HtmlTableRow - Return DirectCast(Row.FindControl(Control), HtmlTableRow) - End Function - - - Public Function FCCustomValidator(ByVal Row As GridViewRow, ByVal Control As String) As CustomValidator - Return DirectCast(Row.FindControl(Control), CustomValidator) - End Function - - - Public Function FCRequiredFieldValidator(ByVal Row As GridViewRow, ByVal Control As String) As RequiredFieldValidator - Return DirectCast(Row.FindControl(Control), RequiredFieldValidator) - End Function - - - Public Function FCMaskedEditExtender(ByVal Row As GridViewRow, ByVal Control As String) As MaskedEditExtender - Return DirectCast(Row.FindControl(Control), MaskedEditExtender) - End Function - - - - Public Function FCHtmlGenericControl(ByVal Row As GridViewRow, ByVal Control As String) As HtmlGenericControl - Return DirectCast(Row.FindControl(Control), HtmlGenericControl) - End Function - - - - Public Function FCValidatorCalloutExtender(ByVal Row As GridViewRow, ByVal Control As String) As ValidatorCalloutExtender - Return DirectCast(Row.FindControl(Control), ValidatorCalloutExtender) + + Public Function FiltroPrimero(dt As DataTable, RowFilter As String, Optional Orderby As String = "") As DataRow + + Dim TmpDr As DataRow = Nothing + + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + If RowFilter <> "" Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + If Dv.ToTable.Rows.Count > 0 Then + TmpDr = Dv.ToTable.Rows(0) + End If + Dv.Dispose() + Else + TmpDr = dt.Rows(0) + End If + dt.Dispose() + End If + + Return TmpDr + End Function + + Public Function FiltroPrimeroPK(dt As DataTable, PrimaryKey As String, Valor As String) As DataRow + + Dim TmpDr As DataRow = Nothing + + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + dt.PrimaryKey = New DataColumn() {dt.Columns(PrimaryKey)} + TmpDr = dt.Rows.Find(Valor) + dt.Dispose() + End If + + Return TmpDr + End Function + + Public Function FiltroUltimo(dt As DataTable, RowFilter As String, Optional Orderby As String = "") As DataRow + Dim TmpDr As DataRow = Nothing + + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + If RowFilter <> "" Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + If Dv.ToTable.Rows.Count > 0 Then + TmpDr = Dv.ToTable.Rows(Dv.ToTable.Rows.Count - 1) + End If + Dv.Dispose() + Else + TmpDr = dt.Rows(dt.Rows.Count - 1) + End If + End If + + Return TmpDr + End Function + + + Public Function ToJson(dt As DataTable) As String + Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer() + Dim rows As New List(Of Dictionary(Of String, Object))() + Dim row As Dictionary(Of String, Object) = Nothing + For Each dr As DataRow In dt.Rows + row = New Dictionary(Of String, Object)() + For Each dc As DataColumn In dt.Columns + row.Add(dc.ColumnName.Trim(), dr(dc)) + Next + rows.Add(row) + Next + Return serializer.Serialize(rows) + End Function + + + Public Function DataTableToJSONIPP(ByVal table As DataTable) As String + Dim JSONString As String = String.Empty + JSONString = JsonConvert.SerializeObject(table) + Return JSONString + End Function + + + Public Function FiltroPrimeroValor(dt As DataTable, Columna As String, Optional RowFilter As String = "", Optional Orderby As String = "") As String + + Dim Retorno As String = "" + + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + If RowFilter <> "" Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + If Dv.ToTable.Rows.Count > 0 Then + Retorno = Dv.ToTable.Rows(0)(Columna).ToString + End If + Dv.Dispose() + Else + Retorno = dt.Rows(0)(Columna).ToString + End If + dt.Dispose() + End If + + Return Retorno + End Function + + + + Public Function DBCampo(ByVal Row As GridViewRow, ByVal Columna As String) As String + Return DataBinder.Eval(Row.DataItem, Columna).ToString + End Function + + + Public Function DataKey(ByVal Row As GridViewRow, ByVal Columna As String) As String + Return DirectCast(Row.NamingContainer, GridView).DataKeys(Row.RowIndex).Values(Columna).ToString + End Function + + + Public Function SUM(DT As DataTable, Campo As String, Optional ByVal Filtro As String = "") As Decimal + Return If(DT IsNot Nothing, DT.Compute(String.Format("SUM({0})", Campo), Filtro).ToString.ToDecimal, 0) + End Function + + Public Function SUMD(DT As DataTable, Campo As String, Optional ByVal Filtro As String = "") As Decimal + Return If(DT IsNot Nothing, DT.Compute(String.Format("SUM({0})", Campo), Filtro).ToString.ToDecimal, 0) + End Function + + + Public Function COUNT(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As Integer + Return DT.Compute(String.Format("COUNT({0})", Campo), Filtro).ToString.ToEntero + End Function + + + Public Function MIN(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As String + Return DT.Compute(String.Format("MIN({0})", Campo), Filtro).ToString + End Function + + + Public Function MAX(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As String + Return DT.Compute(String.Format("MAX({0})", Campo), Filtro).ToString + End Function + + + Public Function AVG(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As Double + Return DT.Compute(String.Format("AVG({0})", Campo), Filtro).ToString.ToDouble + End Function + + + Public Function DataRowToObject(Of T)(row As System.Data.DataRow) As T + Dim Obj = Activator.CreateInstance(Of T)() + If Not IsNothing(row) Then + Dim myType As Type = Obj.GetType() + Dim props As IList(Of Reflection.PropertyInfo) = New List(Of Reflection.PropertyInfo)(myType.GetProperties()) + For Each prop As Reflection.PropertyInfo In props + Dim attr = prop.GetCustomAttributesData() + If Not (Not IsNothing(attr) AndAlso Not IsNothing(attr.FirstOrDefault(Function(M) M.AttributeType.Name = "NotMappedAttribute"))) Then + If prop.CanWrite Then + If row.Table.Columns.Contains(prop.Name) AndAlso Not IsDBNull(row(prop.Name)) Then + + Select Case prop.PropertyType.Name + Case "Boolean" + prop.SetValue(Obj, CBool(row(prop.Name))) + Case "Byte" + prop.SetValue(Obj, CByte(row(prop.Name))) + Case "Char" + prop.SetValue(Obj, CChar(row(prop.Name))) + Case "DateTime" + prop.SetValue(Obj, CDate(row(prop.Name))) + Case "Decimal" + prop.SetValue(Obj, CDec(row(prop.Name))) + Case "Double" + prop.SetValue(Obj, CDbl(row(prop.Name))) + Case "Int32" + prop.SetValue(Obj, CInt(row(prop.Name))) + Case "Int64" + prop.SetValue(Obj, CLng(row(prop.Name))) + Case "SByte" + prop.SetValue(Obj, CSByte(row(prop.Name))) + Case "Int16" + prop.SetValue(Obj, CShort(row(prop.Name))) + Case "Single" + prop.SetValue(Obj, CSng(row(prop.Name))) + Case "String" + prop.SetValue(Obj, CStr(row(prop.Name))) + Case "UInt32" + prop.SetValue(Obj, CUInt(row(prop.Name))) + Case "UInt64" + prop.SetValue(Obj, CULng(row(prop.Name))) + Case "UInt16" + prop.SetValue(Obj, CUShort(row(prop.Name))) + End Select + End If + End If + End If + Next + + End If + Return Obj + End Function + + + Public Function DataTableToObject(Of T)(Tablita As System.Data.DataTable) As List(Of T) + Dim retorno As New List(Of T) + If Not IsNothing(Tablita) Then + Dim Obj = Activator.CreateInstance(Of T)() + Dim myType As Type = Obj.GetType() + + Dim props As IList(Of Reflection.PropertyInfo) = New List(Of Reflection.PropertyInfo)(myType.GetProperties()) + For Each row As System.Data.DataRow In Tablita.Rows + Dim CurrentObj As T = Activator.CreateInstance(Of T)() + For Each prop As Reflection.PropertyInfo In props + Dim attr = prop.GetCustomAttributesData() + If Not (Not IsNothing(attr) AndAlso Not IsNothing(attr.FirstOrDefault(Function(M) M.AttributeType.Name = "NotMappedAttribute"))) Then + If prop.CanWrite Then + If row.Table.Columns.Contains(prop.Name) AndAlso Not IsDBNull(row(prop.Name)) Then + Select Case prop.PropertyType.Name + Case "Boolean" + prop.SetValue(CurrentObj, CBool(row(prop.Name))) + Case "Byte" + prop.SetValue(CurrentObj, CByte(row(prop.Name))) + Case "Char" + prop.SetValue(CurrentObj, CChar(row(prop.Name))) + Case "DateTime" + prop.SetValue(CurrentObj, CDate(row(prop.Name))) + Case "Decimal" + prop.SetValue(CurrentObj, CDec(row(prop.Name))) + Case "Double" + prop.SetValue(CurrentObj, CDbl(row(prop.Name))) + Case "Int32" + prop.SetValue(CurrentObj, CInt(row(prop.Name))) + Case "Int64" + prop.SetValue(CurrentObj, CLng(row(prop.Name))) + Case "SByte" + prop.SetValue(CurrentObj, CSByte(row(prop.Name))) + Case "Int16" + prop.SetValue(CurrentObj, CShort(row(prop.Name))) + Case "Single" + prop.SetValue(CurrentObj, CSng(row(prop.Name))) + Case "String" + prop.SetValue(CurrentObj, CStr(row(prop.Name))) + Case "UInt32" + prop.SetValue(CurrentObj, CUInt(row(prop.Name))) + Case "UInt64" + prop.SetValue(CurrentObj, CULng(row(prop.Name))) + Case "UInt16" + prop.SetValue(CurrentObj, CUShort(row(prop.Name))) + End Select + End If + End If + End If + Next + retorno.Add(CurrentObj) + Next + End If + Return retorno + End Function + + Public Function DataTableToJSON(DT As DataTable) As String + Dim Serializer As New System.Web.Script.Serialization.JavaScriptSerializer() + Dim Rows As New List(Of Dictionary(Of String, Object))() + Dim Row As Dictionary(Of String, Object) + For Each DbRow As DataRow In DT.Rows + Row = New Dictionary(Of String, Object)() + For Each Col As DataColumn In DT.Columns + Row.Add(Col.ColumnName, DbRow(Col)) + Next + Rows.Add(Row) + Next + + Return Serializer.Serialize(Rows) + End Function + + + Public Function ColumnNamesDatatable(dt As DataTable) As List(Of String) + Dim names As New List(Of String) + For Each column As DataColumn In dt.Columns + names.Add(column.ColumnName) + Next + Return names + End Function + +#End Region + +#Region "gridview operations" + + + Public Function FCHyperLink(ByVal Row As GridViewRow, ByVal Control As String) As HyperLink + Return DirectCast(Row.FindControl(Control), HyperLink) + End Function + + + Public Function FCLabel(ByVal Row As GridViewRow, ByVal Control As String) As Label + Return DirectCast(Row.FindControl(Control), Label) + End Function + + + Public Function FCTextBox(ByVal Row As GridViewRow, ByVal Control As String) As TextBox + Return DirectCast(Row.FindControl(Control), TextBox) + End Function + ' + + Public Function FCDropDownList(ByVal Row As GridViewRow, ByVal Control As String) As DropDownList + Return DirectCast(Row.FindControl(Control), DropDownList) + End Function + + + Public Function FCDropDownLost(ByVal Row As GridViewRow, ByVal Control As String) As Dropdownlost + Return DirectCast(Row.FindControl(Control), Dropdownlost) + End Function + + + Public Function FCGridView(ByVal Row As GridViewRow, ByVal Control As String) As GridView + Return DirectCast(Row.FindControl(Control), GridView) + End Function + + + Public Function FCListBox(ByVal Row As GridViewRow, ByVal Control As String) As ListBox + Return DirectCast(Row.FindControl(Control), ListBox) + End Function + + + Public Function FCRadioButton(ByVal Row As GridViewRow, ByVal Control As String) As RadioButton + Return DirectCast(Row.FindControl(Control), RadioButton) + End Function + + + Public Function FCRadioButtonList(ByVal Row As GridViewRow, ByVal Control As String) As RadioButtonList + Return DirectCast(Row.FindControl(Control), RadioButtonList) + End Function + + + Public Function FCLiteral(ByVal Row As GridViewRow, ByVal Control As String) As Literal + Return DirectCast(Row.FindControl(Control), Literal) + End Function + + + + + + Public Function FCFilteredTextBoxExtender(ByVal Row As GridViewRow, ByVal Control As String) As AjaxControlToolkit.FilteredTextBoxExtender + Return DirectCast(Row.FindControl(Control), AjaxControlToolkit.FilteredTextBoxExtender) + End Function + + + Public Function FCCalendarExtender(ByVal Row As GridViewRow, ByVal Control As String) As AjaxControlToolkit.CalendarExtender + Return DirectCast(Row.FindControl(Control), AjaxControlToolkit.CalendarExtender) + End Function + + + Public Function FCCompareValidator(ByVal Row As GridViewRow, ByVal Control As String) As CompareValidator + Return DirectCast(Row.FindControl(Control), CompareValidator) + End Function + + + Public Function FCImageButton(ByVal Row As GridViewRow, ByVal Control As String) As ImageButton + Return DirectCast(Row.FindControl(Control), ImageButton) + End Function + + + Public Function FCLinkButton(ByVal Row As GridViewRow, ByVal Control As String) As LinkButton + Return DirectCast(Row.FindControl(Control), LinkButton) + End Function + + + Public Function FCImage(ByVal Row As GridViewRow, ByVal Control As String) As Image + Return DirectCast(Row.FindControl(Control), Image) + End Function + + + Public Function FCCheckBox(ByVal Row As GridViewRow, ByVal Control As String) As CheckBox + Return DirectCast(Row.FindControl(Control), CheckBox) + End Function + + + Public Function FCHiddenField(ByVal Row As GridViewRow, ByVal Control As String) As HiddenField + Return DirectCast(Row.FindControl(Control), HiddenField) + End Function + + + Public Function FCButton(ByVal Row As GridViewRow, ByVal Control As String) As Button + Return DirectCast(Row.FindControl(Control), Button) + End Function + + + Public Function FCHtmlTableRow(ByVal Row As GridViewRow, ByVal Control As String) As HtmlTableRow + Return DirectCast(Row.FindControl(Control), HtmlTableRow) + End Function + + + Public Function FCCustomValidator(ByVal Row As GridViewRow, ByVal Control As String) As CustomValidator + Return DirectCast(Row.FindControl(Control), CustomValidator) + End Function + + + Public Function FCRequiredFieldValidator(ByVal Row As GridViewRow, ByVal Control As String) As RequiredFieldValidator + Return DirectCast(Row.FindControl(Control), RequiredFieldValidator) + End Function + + + Public Function FCMaskedEditExtender(ByVal Row As GridViewRow, ByVal Control As String) As MaskedEditExtender + Return DirectCast(Row.FindControl(Control), MaskedEditExtender) + End Function + + + + Public Function FCHtmlGenericControl(ByVal Row As GridViewRow, ByVal Control As String) As HtmlGenericControl + Return DirectCast(Row.FindControl(Control), HtmlGenericControl) + End Function + + + + Public Function FCValidatorCalloutExtender(ByVal Row As GridViewRow, ByVal Control As String) As ValidatorCalloutExtender + Return DirectCast(Row.FindControl(Control), ValidatorCalloutExtender) End Function 'AjaxControlToolkit - - Public Function FCRangeValidator(ByVal Row As GridViewRow, ByVal Control As String) As RangeValidator - Return DirectCast(Row.FindControl(Control), RangeValidator) + + Public Function FCRangeValidator(ByVal Row As GridViewRow, ByVal Control As String) As RangeValidator + Return DirectCast(Row.FindControl(Control), RangeValidator) End Function @@ -1912,83 +1912,83 @@ Namespace Extensiones End If End Sub -#End Region +#End Region -#Region "Excel PDF" +#Region "Excel PDF" Public Sub GeneraChequePDF(pCveIE As Integer, tEmpresa As Empresa, Optional IDPoliza As Integer = -1, Optional MuestraAlert As Boolean = True) - Dim Folio, Observacion, UsuarioRegistro, TextoImporte, PagueseA, Ruta, Banco, NumCuenta, AbonoCuenta, SubProyecto, NotificarA, RefCrediproveedor As String - Dim FechaExpedicion As Date = ClsPaginas.NowADS() + Dim Folio, Observacion, UsuarioRegistro, TextoImporte, PagueseA, Ruta, Banco, NumCuenta, AbonoCuenta, SubProyecto, NotificarA, RefCrediproveedor As String + Dim FechaExpedicion As Date = ClsPaginas.NowADS() Dim Importe As Decimal - Dim tCveEmpresa As Integer = tEmpresa.CveEmpresa - Dim CveTipoTransaccion, CveProveedor, CvePersonal As Integer - Dim ObjIE As New ClsBancos() + Dim tCveEmpresa As Integer = tEmpresa.CveEmpresa + Dim CveTipoTransaccion, CveProveedor, CvePersonal As Integer + Dim ObjIE As New ClsBancos() Dim tIdPoliza As Integer Folio = "" - Ruta = tEmpresa.Ruta - - If ObjIE.GetBancosIE(pCveIE, tCveEmpresa) Then - If ObjIE.DtResultados.Rows.Count > 0 Then - - PagueseA = ObjIE.PagueseA - Folio = ObjIE.Folio - Importe = ObjIE.Importe - CveTipoTransaccion = ObjIE.CveTipoTransaccion - Banco = ObjIE.Banco + Ruta = tEmpresa.Ruta + + If ObjIE.GetBancosIE(pCveIE, tCveEmpresa) Then + If ObjIE.DtResultados.Rows.Count > 0 Then + + PagueseA = ObjIE.PagueseA + Folio = ObjIE.Folio + Importe = ObjIE.Importe + CveTipoTransaccion = ObjIE.CveTipoTransaccion + Banco = ObjIE.Banco NumCuenta = ObjIE.NumCuenta - TextoImporte = String.Format("--- {0} ---", Importe.Texto2Letras(ObjIE.CveMoneda)) - FechaExpedicion = ObjIE.FechaDocumento - Observacion = ObjIE.Observaciones - UsuarioRegistro = ObjIE.UsuarioNombre - SubProyecto = ObjIE.SubProyecto - AbonoCuenta = If(ObjIE.EsAbonoEnCuenta, "PARA ABONO EN CUENTA DEL BENEFICIARIO", "") - NotificarA = ObjIE.NotificarA - tIdPoliza = ObjIE.IDPoliza - If ObjIE.Bancos_IEImpreso(True, pCveIE) Then - - End If - End If - End If - - ObjIE.Dispose() - - 'cuando es cheque + TextoImporte = String.Format("--- {0} ---", Importe.Texto2Letras(ObjIE.CveMoneda)) + FechaExpedicion = ObjIE.FechaDocumento + Observacion = ObjIE.Observaciones + UsuarioRegistro = ObjIE.UsuarioNombre + SubProyecto = ObjIE.SubProyecto + AbonoCuenta = If(ObjIE.EsAbonoEnCuenta, "PARA ABONO EN CUENTA DEL BENEFICIARIO", "") + NotificarA = ObjIE.NotificarA + tIdPoliza = ObjIE.IDPoliza + If ObjIE.Bancos_IEImpreso(True, pCveIE) Then + + End If + End If + End If + + ObjIE.Dispose() + + 'cuando es cheque If Folio <> "" AndAlso CveTipoTransaccion = 1 Then - Else - Dim RFC As String = "" - Dim Correo As String = "" - Dim CLABE As String = "" - Dim NoSucursal As String = "" - Dim Telefono As String = "" - Dim IVA As Double = 0 - - Banco = ObjIE.DepositoBanco - NumCuenta = ObjIE.DepositoCuenta - If NumCuenta = "" Then NumCuenta = ObjIE.DepositoCIE - CLABE = ObjIE.DepositoCLABE - If CLABE = "" Then CLABE = ObjIE.DepositoReferencia - NoSucursal = ObjIE.DepositoSucursal - RefCrediproveedor = ObjIE.DepositoRefCrediProveedor - - 'Dim UsuarioResponsable As String = "" - Dim PreP As New ClsBancos - If PreP.GetBancosIEMovimientos(pCveIE, tCveEmpresa) Then - If PreP.DtResultados.Rows.Count > 0 Then - CveProveedor = PreP.DtResultados.Rows(0)("CveProveedor").ToString.ToEntero - CvePersonal = PreP.DtResultados.Rows(0)("CvePersonal").ToString.ToEntero - - IVA = PreP.DtResultados.SUM("Importe", "CveConceptoContable = 19") ' concepto de IVA - + Else + Dim RFC As String = "" + Dim Correo As String = "" + Dim CLABE As String = "" + Dim NoSucursal As String = "" + Dim Telefono As String = "" + Dim IVA As Double = 0 + + Banco = ObjIE.DepositoBanco + NumCuenta = ObjIE.DepositoCuenta + If NumCuenta = "" Then NumCuenta = ObjIE.DepositoCIE + CLABE = ObjIE.DepositoCLABE + If CLABE = "" Then CLABE = ObjIE.DepositoReferencia + NoSucursal = ObjIE.DepositoSucursal + RefCrediproveedor = ObjIE.DepositoRefCrediProveedor + + 'Dim UsuarioResponsable As String = "" + Dim PreP As New ClsBancos + If PreP.GetBancosIEMovimientos(pCveIE, tCveEmpresa) Then + If PreP.DtResultados.Rows.Count > 0 Then + CveProveedor = PreP.DtResultados.Rows(0)("CveProveedor").ToString.ToEntero + CvePersonal = PreP.DtResultados.Rows(0)("CvePersonal").ToString.ToEntero + + IVA = PreP.DtResultados.SUM("Importe", "CveConceptoContable = 19") ' concepto de IVA + If CveProveedor > 0 Then - Dim Prov As New ClsCompProveedores - If Prov.GetProveedores(ClsCompProveedores.TipoConsulta.ParaUsoEnEmpresa, CveProveedor, "-1", "-1", "-1", "-1", "-1", "-1", "-1", -1, tCveEmpresa) Then - If Prov.DtResultados.Rows.Count > 0 Then - - RFC = Prov.DtResultados.Rows(0)("RFC").ToString + Dim Prov As New ClsCompProveedores + If Prov.GetProveedores(ClsCompProveedores.TipoConsulta.ParaUsoEnEmpresa, CveProveedor, "-1", "-1", "-1", "-1", "-1", "-1", "-1", -1, tCveEmpresa) Then + If Prov.DtResultados.Rows.Count > 0 Then + + RFC = Prov.DtResultados.Rows(0)("RFC").ToString Correo = Prov.DtResultados.Rows(0)("ContactoMail").ToString 'Banco = Prov.DtResultados.Rows(0)("BancNombre").ToString 'NumCuenta = Prov.DtResultados.Rows(0)("BancCuenta").ToString @@ -1999,25 +1999,25 @@ Namespace Extensiones ' UsuarioResponsable = Prov.DtResultados.Rows(0)("NotificarA").ToString - End If - End If - Prov.Dispose() - End If - - If CvePersonal > 0 Then - Dim RH As New ClsRH - If RH.GetPersonal(CvePersonal, tCveEmpresa) Then - If RH.DtResultados.Rows.Count > 0 Then - Correo = RH.DtResultados.Rows(0)("Correo").ToString - Banco = RH.DtResultados.Rows(0)("Banco").ToString - NumCuenta = RH.DtResultados.Rows(0)("BancoNumCuenta").ToString - CLABE = RH.DtResultados.Rows(0)("CLABE").ToString - End If - End If - RH.Dispose() - End If - End If - End If + End If + End If + Prov.Dispose() + End If + + If CvePersonal > 0 Then + Dim RH As New ClsRH + If RH.GetPersonal(CvePersonal, tCveEmpresa) Then + If RH.DtResultados.Rows.Count > 0 Then + Correo = RH.DtResultados.Rows(0)("Correo").ToString + Banco = RH.DtResultados.Rows(0)("Banco").ToString + NumCuenta = RH.DtResultados.Rows(0)("BancoNumCuenta").ToString + CLABE = RH.DtResultados.Rows(0)("CLABE").ToString + End If + End If + RH.Dispose() + End If + End If + End If PreP.Dispose() End If @@ -2029,107 +2029,107 @@ Namespace Extensiones End Function - - Public Sub ExportToExcel2(GridView As GridView, NombreArchivoXLSX As String) - - If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then - NombreArchivoXLSX = Regex.Replace(NombreArchivoXLSX.Replace("["c, "").Replace("]"c, ""), "[:\/?*]", String.Empty) - Dim dt As New DataTable(NombreArchivoXLSX) - Dim i As Integer = 0 - Dim ArrColumnasVisibles As New List(Of Integer) 'solo recorro las columnas visibles - - For Each cell As TableCell In GridView.HeaderRow.Cells - Dim titulo As String = HttpUtility.HtmlDecode(TextoCelda(cell)).Trim - If GridView.Columns(i).Visible AndAlso titulo.Length > 0 Then - If dt.Columns.Contains(titulo) Then - titulo = titulo & i - End If - dt.Columns.Add(titulo) - ArrColumnasVisibles.Add(i) - End If - i += 1 - Next - i = 0 - - For Each row As GridViewRow In GridView.Rows - dt.Rows.Add() - i = 0 - For Each j As Integer In ArrColumnasVisibles - - dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(j)) - i = i + 1 - Next - Next - Using wb As New XLWorkbook() - wb.Worksheets.Add(dt) - - - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.Charset = "" - HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX.Replace(",", "").Replace(",", ""))) - Using MyMemoryStream As New MemoryStream() - wb.SaveAs(MyMemoryStream) - MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) - HttpContext.Current.Response.Flush() - HttpContext.Current.Response.[End]() - End Using - End Using - End If - - End Sub - - - Public Sub ExportToExcel(GridView As GridView, NombreArchivoXLS As String, Optional Encabezado As HtmlTable = Nothing, Optional Encabezado2 As LiteralControl = Nothing) - - If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then - - Dim sb As StringBuilder = New StringBuilder() - Dim style As StringBuilder = New StringBuilder() - Dim sw As StringWriter = New StringWriter(sb) - Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) - Dim page As Page = New Page() - Dim Form As HtmlForm = New HtmlForm() - - GridView.EnableViewState = False - RecursivoLimpiaControlesExcel(GridView.Controls) - - style.Append(" ") - - page.EnableEventValidation = False - page.DesignerInitialize() - page.Controls.Add(Form) - If Encabezado IsNot Nothing Then - RecursivoLimpiaControlesExcel(Encabezado.Controls) - Form.Controls.Add(Encabezado) - End If - - If Encabezado2 IsNot Nothing Then - 'RecursivoLimpiaControlesExcel(Encabezado2.Controls) - Form.Controls.Add(Encabezado2) - End If - - Form.Controls.Add(GridView) - page.RenderControl(htw) - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" - HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", NombreArchivoXLS)) - HttpContext.Current.Response.Charset = "UTF-8" - HttpContext.Current.Response.ContentEncoding = Encoding.Default - HttpContext.Current.Response.Write(style.ToString) - HttpContext.Current.Response.Write(sb.ToString()) - HttpContext.Current.Response.End() - sb.Clear() - style.Clear() - End If - + + Public Sub ExportToExcel2(GridView As GridView, NombreArchivoXLSX As String) + + If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then + NombreArchivoXLSX = Regex.Replace(NombreArchivoXLSX.Replace("["c, "").Replace("]"c, ""), "[:\/?*]", String.Empty) + Dim dt As New DataTable(NombreArchivoXLSX) + Dim i As Integer = 0 + Dim ArrColumnasVisibles As New List(Of Integer) 'solo recorro las columnas visibles + + For Each cell As TableCell In GridView.HeaderRow.Cells + Dim titulo As String = HttpUtility.HtmlDecode(TextoCelda(cell)).Trim + If GridView.Columns(i).Visible AndAlso titulo.Length > 0 Then + If dt.Columns.Contains(titulo) Then + titulo = titulo & i + End If + dt.Columns.Add(titulo) + ArrColumnasVisibles.Add(i) + End If + i += 1 + Next + i = 0 + + For Each row As GridViewRow In GridView.Rows + dt.Rows.Add() + i = 0 + For Each j As Integer In ArrColumnasVisibles + + dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(j)) + i = i + 1 + Next + Next + Using wb As New XLWorkbook() + wb.Worksheets.Add(dt) + + + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.Charset = "" + HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX.Replace(",", "").Replace(",", ""))) + Using MyMemoryStream As New MemoryStream() + wb.SaveAs(MyMemoryStream) + MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) + HttpContext.Current.Response.Flush() + HttpContext.Current.Response.[End]() + End Using + End Using + End If + End Sub - + + Public Sub ExportToExcel(GridView As GridView, NombreArchivoXLS As String, Optional Encabezado As HtmlTable = Nothing, Optional Encabezado2 As LiteralControl = Nothing) + + If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then + + Dim sb As StringBuilder = New StringBuilder() + Dim style As StringBuilder = New StringBuilder() + Dim sw As StringWriter = New StringWriter(sb) + Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) + Dim page As Page = New Page() + Dim Form As HtmlForm = New HtmlForm() + + GridView.EnableViewState = False + RecursivoLimpiaControlesExcel(GridView.Controls) + + style.Append(" ") + + page.EnableEventValidation = False + page.DesignerInitialize() + page.Controls.Add(Form) + If Encabezado IsNot Nothing Then + RecursivoLimpiaControlesExcel(Encabezado.Controls) + Form.Controls.Add(Encabezado) + End If + + If Encabezado2 IsNot Nothing Then + 'RecursivoLimpiaControlesExcel(Encabezado2.Controls) + Form.Controls.Add(Encabezado2) + End If + + Form.Controls.Add(GridView) + page.RenderControl(htw) + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" + HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", NombreArchivoXLS)) + HttpContext.Current.Response.Charset = "UTF-8" + HttpContext.Current.Response.ContentEncoding = Encoding.Default + HttpContext.Current.Response.Write(style.ToString) + HttpContext.Current.Response.Write(sb.ToString()) + HttpContext.Current.Response.End() + sb.Clear() + style.Clear() + End If + + End Sub + + Public Sub ExportToExcelGembox(GridView As GridView, NombreArchivoXLSx As String, Usuario As Usuario, Titulo As String, Optional DatoTituloExtra As String = "", Optional DatosFiltros As String = "", Optional AnchoImagen As Integer = 100, Optional AlturaImagen As Integer = 100, Optional DTExtra As DataTable = Nothing) Dim sw1 As New StringWriter() @@ -2363,188 +2363,188 @@ Namespace Extensiones excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") - End Sub - - - - Public Sub ExportToExcel(GridView As HtmlTable, NombreArchivoXLS As String) - Dim sb As StringBuilder = New StringBuilder() - Dim sw As StringWriter = New StringWriter(sb) - Dim style As StringBuilder = New StringBuilder() - Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) - Dim page As Page = New Page() - Dim Form As HtmlForm = New HtmlForm() - - style.Append(" ") - RecursivoLimpiaControlesExcel(GridView.Controls) - - GridView.EnableViewState = False - page.EnableEventValidation = False - page.DesignerInitialize() - page.Controls.Add(Form) - Form.Controls.Add(GridView) - page.RenderControl(htw) - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" - HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", NombreArchivoXLS)) - HttpContext.Current.Response.Charset = "UTF-8" - HttpContext.Current.Response.ContentEncoding = Encoding.Default - HttpContext.Current.Response.Write(style.ToString) - HttpContext.Current.Response.Write(sb.ToString()) - HttpContext.Current.Response.End() + End Sub + + + + Public Sub ExportToExcel(GridView As HtmlTable, NombreArchivoXLS As String) + Dim sb As StringBuilder = New StringBuilder() + Dim sw As StringWriter = New StringWriter(sb) + Dim style As StringBuilder = New StringBuilder() + Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) + Dim page As Page = New Page() + Dim Form As HtmlForm = New HtmlForm() + + style.Append(" ") + RecursivoLimpiaControlesExcel(GridView.Controls) + + GridView.EnableViewState = False + page.EnableEventValidation = False + page.DesignerInitialize() + page.Controls.Add(Form) + Form.Controls.Add(GridView) + page.RenderControl(htw) + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" + HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", NombreArchivoXLS)) + HttpContext.Current.Response.Charset = "UTF-8" + HttpContext.Current.Response.ContentEncoding = Encoding.Default + HttpContext.Current.Response.Write(style.ToString) + HttpContext.Current.Response.Write(sb.ToString()) + HttpContext.Current.Response.End() sb.Clear() - style.Clear() - End Sub - - Public Sub ExportToExcel(datatable As DataTable, NombreArchivoXLSX As String) - - If datatable IsNot Nothing AndAlso datatable.Rows.Count > 0 Then - NombreArchivoXLSX = Regex.Replace(NombreArchivoXLSX.Replace("["c, "").Replace("]"c, ""), "[:\/?*]", String.Empty) - 'Dim dt As New DataTable(NombreArchivoXLSX) - 'Dim i As Integer = 0 - datatable.TableName = NombreArchivoXLSX - Using wb As New XLWorkbook() - wb.Worksheets.Add(datatable) - - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.Charset = "" - HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX)) - Using MyMemoryStream As New MemoryStream() - wb.SaveAs(MyMemoryStream) - MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) - HttpContext.Current.Response.Flush() - HttpContext.Current.Response.[End]() - End Using - HttpContext.Current.Response.End() - End Using - End If - - End Sub - 'Usa la librería ClosedXML - - Public Sub ExportToExcelX(GridView As GridView, NombreArchivoXLSX As String) - - If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then - NombreArchivoXLSX = ValidFileName(NombreArchivoXLSX, 31) - Dim dt As New DataTable(NombreArchivoXLSX) - Dim i As Integer = 0 - Dim ArrColumnasVisibles As New List(Of Integer) 'solo recorro las columnas visibles - - For Each cell As TableCell In GridView.HeaderRow.Cells - Try - If GridView.Columns(i).Visible Then - dt.Columns.Add(HttpUtility.HtmlDecode(TextoCelda(cell))) - ArrColumnasVisibles.Add(i) - End If - Catch - End Try - - i += 1 - Next - i = 0 - - For Each row As GridViewRow In GridView.Rows - dt.Rows.Add() - i = 0 - For Each j As Integer In ArrColumnasVisibles - - dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(j)) - i = i + 1 - - Next - 'For Each col As DataControlField In GridView.Columns - ' If col.Visible Then - - ' dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(i)) - ' i = i + 1 - ' End If - - 'Next - 'For i As Integer = 0 To row.Cells.Count - 1 - ' If row.Cells(i).Visible Then - ' dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(i)) - ' End If - - 'Next - Next - Using wb As New XLWorkbook() - Dim WS As IXLWorksheet = wb.Worksheets.Add(NombreArchivoXLSX) - Dim RangoColTitulos As IXLCells = WS.FirstRow().CellsUsed() - + style.Clear() + End Sub + + Public Sub ExportToExcel(datatable As DataTable, NombreArchivoXLSX As String) + + If datatable IsNot Nothing AndAlso datatable.Rows.Count > 0 Then + NombreArchivoXLSX = Regex.Replace(NombreArchivoXLSX.Replace("["c, "").Replace("]"c, ""), "[:\/?*]", String.Empty) + 'Dim dt As New DataTable(NombreArchivoXLSX) + 'Dim i As Integer = 0 + datatable.TableName = NombreArchivoXLSX + Using wb As New XLWorkbook() + wb.Worksheets.Add(datatable) + + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.Charset = "" + HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX)) + Using MyMemoryStream As New MemoryStream() + wb.SaveAs(MyMemoryStream) + MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) + HttpContext.Current.Response.Flush() + HttpContext.Current.Response.[End]() + End Using + HttpContext.Current.Response.End() + End Using + End If + + End Sub + 'Usa la librería ClosedXML + + Public Sub ExportToExcelX(GridView As GridView, NombreArchivoXLSX As String) + + If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then + NombreArchivoXLSX = ValidFileName(NombreArchivoXLSX, 31) + Dim dt As New DataTable(NombreArchivoXLSX) + Dim i As Integer = 0 + Dim ArrColumnasVisibles As New List(Of Integer) 'solo recorro las columnas visibles + + For Each cell As TableCell In GridView.HeaderRow.Cells + Try + If GridView.Columns(i).Visible Then + dt.Columns.Add(HttpUtility.HtmlDecode(TextoCelda(cell))) + ArrColumnasVisibles.Add(i) + End If + Catch + End Try + + i += 1 + Next + i = 0 + + For Each row As GridViewRow In GridView.Rows + dt.Rows.Add() + i = 0 + For Each j As Integer In ArrColumnasVisibles + + dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(j)) + i = i + 1 + + Next + 'For Each col As DataControlField In GridView.Columns + ' If col.Visible Then + + ' dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(i)) + ' i = i + 1 + ' End If + + 'Next + 'For i As Integer = 0 To row.Cells.Count - 1 + ' If row.Cells(i).Visible Then + ' dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(i)) + ' End If + + 'Next + Next + Using wb As New XLWorkbook() + Dim WS As IXLWorksheet = wb.Worksheets.Add(NombreArchivoXLSX) + Dim RangoColTitulos As IXLCells = WS.FirstRow().CellsUsed() + WS.FirstCell().InsertTable(dt, False) 'Estilo RangoColTitulos.Style.Fill.SetBackgroundColor(XLColor.FromArgb(75, 119, 190)) - RangoColTitulos.Style.Font.SetBold(True) - RangoColTitulos.Style.Font.FontColor = XLColor.White - - WS.Columns().AdjustToContents() - - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.Charset = "" - HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX)) - Using MyMemoryStream As New MemoryStream() - wb.SaveAs(MyMemoryStream) - MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) - HttpContext.Current.Response.Flush() - HttpContext.Current.Response.[End]() - End Using - End Using - End If - - End Sub - 'Usa la librería GemBox - - Public Sub ExportToExcelG(Gv As GridView, NombreArchivoXLSx As String, Optional Titulo As String = "Reporte", Optional Usuario As Usuario = Nothing, Optional Filtros As String = "", Optional AlturaImagen As Double = 100, Optional AnchoImagen As Double = 100) - Dim sw As New StringWriter() - Dim htw As New HtmlTextWriter(sw) - Gv.RenderControl(htw) - GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(SerialGemBoxSpreadsheet) - - Dim excel As GemBox.Spreadsheet.ExcelFile - Dim options As HtmlLoadOptions = GemBox.Spreadsheet.LoadOptions.HtmlDefault - Using htmlStream As New MemoryStream(options.Encoding.GetBytes(sw.ToString())) - excel = GemBox.Spreadsheet.ExcelFile.Load(htmlStream, options) - If Usuario IsNot Nothing Then - Dim TotalRowHeader As Integer = 8 - Dim TotalRowFooter As Integer = 2 - - Dim worksheet As ExcelWorksheet = excel.Worksheets(0) - worksheet.Name = ValidFileName(NombreArchivoXLSx, 31) - worksheet.Rows.InsertEmpty(0, TotalRowHeader) - Dim celdasConTexto As CellRange = worksheet.GetUsedCellRange(True) - celdasConTexto.Style.Font.Name = "Calibri Light" - celdasConTexto.Style.Borders = Nothing - - Dim RangoNombreEmpresa As CellRange = worksheet.Cells.GetSubrangeAbsolute(1, celdasConTexto.FirstColumnIndex, 1, celdasConTexto.LastColumnIndex) - RangoNombreEmpresa.Merged = True - RangoNombreEmpresa.Value = Usuario.Empresa.Empresa - RangoNombreEmpresa.Style.Font.Size = 18 * 20 - RangoNombreEmpresa.Style.Font.Name = "Calibri Light" - RangoNombreEmpresa.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center - RangoNombreEmpresa.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center - - Dim RangoFiltros As CellRange = worksheet.Cells.GetSubrangeAbsolute(6, celdasConTexto.FirstColumnIndex, 6, celdasConTexto.LastColumnIndex) - RangoFiltros.Merged = True - RangoFiltros.Value = Filtros - RangoFiltros.Style.Font.Size = 15 * 20 - RangoFiltros.Style.Font.Name = "Calibri Light" - RangoFiltros.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Left - RangoFiltros.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center - - Dim RangoTitulo As CellRange = worksheet.Cells.GetSubrangeAbsolute(3, celdasConTexto.FirstColumnIndex, 3, celdasConTexto.LastColumnIndex) - RangoTitulo.Merged = True - RangoTitulo.Value = Titulo - RangoTitulo.Style.Font.Size = 20 * 20 - RangoTitulo.Style.Font.Name = "Calibri Light" - RangoTitulo.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center + RangoColTitulos.Style.Font.SetBold(True) + RangoColTitulos.Style.Font.FontColor = XLColor.White + + WS.Columns().AdjustToContents() + + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.Charset = "" + HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX)) + Using MyMemoryStream As New MemoryStream() + wb.SaveAs(MyMemoryStream) + MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) + HttpContext.Current.Response.Flush() + HttpContext.Current.Response.[End]() + End Using + End Using + End If + + End Sub + 'Usa la librería GemBox + + Public Sub ExportToExcelG(Gv As GridView, NombreArchivoXLSx As String, Optional Titulo As String = "Reporte", Optional Usuario As Usuario = Nothing, Optional Filtros As String = "", Optional AlturaImagen As Double = 100, Optional AnchoImagen As Double = 100) + Dim sw As New StringWriter() + Dim htw As New HtmlTextWriter(sw) + Gv.RenderControl(htw) + GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(SerialGemBoxSpreadsheet) + + Dim excel As GemBox.Spreadsheet.ExcelFile + Dim options As HtmlLoadOptions = GemBox.Spreadsheet.LoadOptions.HtmlDefault + Using htmlStream As New MemoryStream(options.Encoding.GetBytes(sw.ToString())) + excel = GemBox.Spreadsheet.ExcelFile.Load(htmlStream, options) + If Usuario IsNot Nothing Then + Dim TotalRowHeader As Integer = 8 + Dim TotalRowFooter As Integer = 2 + + Dim worksheet As ExcelWorksheet = excel.Worksheets(0) + worksheet.Name = ValidFileName(NombreArchivoXLSx, 31) + worksheet.Rows.InsertEmpty(0, TotalRowHeader) + Dim celdasConTexto As CellRange = worksheet.GetUsedCellRange(True) + celdasConTexto.Style.Font.Name = "Calibri Light" + celdasConTexto.Style.Borders = Nothing + + Dim RangoNombreEmpresa As CellRange = worksheet.Cells.GetSubrangeAbsolute(1, celdasConTexto.FirstColumnIndex, 1, celdasConTexto.LastColumnIndex) + RangoNombreEmpresa.Merged = True + RangoNombreEmpresa.Value = Usuario.Empresa.Empresa + RangoNombreEmpresa.Style.Font.Size = 18 * 20 + RangoNombreEmpresa.Style.Font.Name = "Calibri Light" + RangoNombreEmpresa.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center + RangoNombreEmpresa.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center + + Dim RangoFiltros As CellRange = worksheet.Cells.GetSubrangeAbsolute(6, celdasConTexto.FirstColumnIndex, 6, celdasConTexto.LastColumnIndex) + RangoFiltros.Merged = True + RangoFiltros.Value = Filtros + RangoFiltros.Style.Font.Size = 15 * 20 + RangoFiltros.Style.Font.Name = "Calibri Light" + RangoFiltros.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Left + RangoFiltros.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center + + Dim RangoTitulo As CellRange = worksheet.Cells.GetSubrangeAbsolute(3, celdasConTexto.FirstColumnIndex, 3, celdasConTexto.LastColumnIndex) + RangoTitulo.Merged = True + RangoTitulo.Value = Titulo + RangoTitulo.Style.Font.Size = 20 * 20 + RangoTitulo.Style.Font.Name = "Calibri Light" + RangoTitulo.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center RangoTitulo.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center Dim RangoColTitulos As CellRange = worksheet.Cells.GetSubrangeAbsolute(8, celdasConTexto.FirstColumnIndex, 8, celdasConTexto.LastColumnIndex) @@ -2554,23 +2554,23 @@ Namespace Extensiones RangoColTitulos.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center RangoColTitulos.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center RangoColTitulos.Style.FillPattern.SetSolid(GemBox.Spreadsheet.SpreadsheetColor.FromArgb(75, 119, 190)) - RangoColTitulos.Style.Font.Color = GemBox.Spreadsheet.SpreadsheetColor.FromArgb(255, 255, 255) - - For i As Integer = celdasConTexto.FirstColumnIndex To celdasConTexto.LastColumnIndex - Try + RangoColTitulos.Style.Font.Color = GemBox.Spreadsheet.SpreadsheetColor.FromArgb(255, 255, 255) + + For i As Integer = celdasConTexto.FirstColumnIndex To celdasConTexto.LastColumnIndex + Try worksheet.Columns(i).AutoFit(0.95) - Catch ex As Exception - End Try - Next - - Dim IndexEndTable As Integer = Gv.Rows.Count + TotalRowHeader + TotalRowFooter - - worksheet.Rows(IndexEndTable).Cells(2).Value = "Usuario Imprimió" - worksheet.Rows(IndexEndTable + 1).Cells(2).Value = Usuario.Nombre - - worksheet.Rows(IndexEndTable).Cells(6).Value = "Fecha Impresión" - worksheet.Rows(IndexEndTable + 1).Cells(6).Value = ClsPaginas.NowADS().ToString("dd/MM/yyyy") - + Catch ex As Exception + End Try + Next + + Dim IndexEndTable As Integer = Gv.Rows.Count + TotalRowHeader + TotalRowFooter + + worksheet.Rows(IndexEndTable).Cells(2).Value = "Usuario Imprimió" + worksheet.Rows(IndexEndTable + 1).Cells(2).Value = Usuario.Nombre + + worksheet.Rows(IndexEndTable).Cells(6).Value = "Fecha Impresión" + worksheet.Rows(IndexEndTable + 1).Cells(6).Value = ClsPaginas.NowADS().ToString("dd/MM/yyyy") + Dim Imagen As New System.IO.FileInfo($"{Usuario.Empresa.Ruta}/Logo.png") If Imagen.Exists Then @@ -2580,22 +2580,22 @@ Namespace Extensiones sr.BaseStream.CopyTo(ms) worksheet.Pictures.Add(ms, ExcelPictureFormat.Png, "A1", AnchoImagen, AlturaImagen, LengthUnit.Pixel) End Using - End If - End If - - End Using - htw.Dispose() - - excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") - + End If + End If + + End Using + htw.Dispose() + + excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") + End Sub - - Public Sub ExportToExcelG(Dt As DataTable, NombreArchivoXLSx As String, Optional Titulo As String = "Reporte", Optional Usuario As Usuario = Nothing, Optional Filtros As String = "", Optional AlturaImagen As Double = 100, Optional AnchoImagen As Double = 100) + + Public Sub ExportToExcelG(Dt As DataTable, NombreArchivoXLSx As String, Optional Titulo As String = "Reporte", Optional Usuario As Usuario = Nothing, Optional Filtros As String = "", Optional AlturaImagen As Double = 100, Optional AnchoImagen As Double = 100) GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(SerialGemBoxSpreadsheet) If Dt.TableName Is Nothing Then Dt.TableName = NombreArchivoXLSx - Dim excel As New GemBox.Spreadsheet.ExcelFile + Dim excel As New GemBox.Spreadsheet.ExcelFile Dim item As ExcelWorksheet = excel.Worksheets.Add(ValidFileName(Dt.TableName, 31)) item.InsertDataTable(Dt, New InsertDataTableOptions() With @@ -2674,151 +2674,151 @@ Namespace Extensiones worksheet.Pictures.Add(ms, ExcelPictureFormat.Png, "A1", AnchoImagen, AlturaImagen, LengthUnit.Pixel) End Using End If - End If - - excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") - + End If + + excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") + End Sub - - Private Sub RecursivoLimpiaControlesExcel(Controls As ControlCollection) - For Each c As Control In Controls - - If Not c.Controls Is Nothing AndAlso c.Controls.Count > 0 Then - RecursivoLimpiaControlesExcel(c.Controls) - Else - - If (c.GetType() Is GetType(HtmlImage)) OrElse (c.GetType() Is GetType(ImageButton)) Then 'Oculto las imágenes - c.Visible = False - ElseIf c.GetType() Is GetType(LinkButton) Then 'le quito los hypervínculos a el objeto para que se vea como texto - DirectCast(c, LinkButton).Enabled = False - ElseIf c.GetType() Is GetType(HyperLink) Then 'le quito los hypervínculos a el objeto para que se vea como texto - DirectCast(c, HyperLink).NavigateUrl = "" - ElseIf c.GetType() Is GetType(MaskedEditExtender) Then 'le quito los hypervínculos a el objeto para que se vea como texto - DirectCast(c, MaskedEditExtender).Enabled = False - ElseIf c.GetType() Is GetType(LiteralControl) Then 'le quito los objetos regulares de html - If DirectCast(c, LiteralControl).Text.Contains("") Then - Dim tmp As String - Dim ind As Integer - tmp = DirectCast(c, LiteralControl).Text - ind = tmp.IndexOf(">"c) - tmp = tmp.Substring(ind + 1) - ind = tmp.IndexOf("", StringComparison.Ordinal) - tmp = tmp.Substring(0, ind) - DirectCast(c, LiteralControl).Text = tmp - End If - End If - End If - Next - End Sub - Public Function TextoCelda(Celda As TableCell) As String - Dim Retorno As New StringBuilder - If Celda.Controls.Count = 0 Then - Retorno.Append(Celda.Text) - Else - - For Each c As Control In Celda.Controls - - If c.GetType() Is GetType(Label) Then 'le quito los hypervínculos a el objeto para que se vea como texto - Retorno.Append(DirectCast(c, Label).Text) - ElseIf c.GetType() Is GetType(LinkButton) Then 'le quito los hypervínculos a el objeto para que se vea como texto - DirectCast(c, LinkButton).Enabled = False - Retorno.Append(DirectCast(c, LinkButton).Text) - ElseIf c.GetType() Is GetType(HyperLink) Then 'le quito los hypervínculos a el objeto para que se vea como texto - Retorno.Append(DirectCast(c, HyperLink).Text) - ElseIf c.GetType() Is GetType(LiteralControl) Then 'le quito los objetos regulares de html - If DirectCast(c, LiteralControl).Text.Contains("") Then - Dim tmp As String - Dim ind As Integer - tmp = DirectCast(c, LiteralControl).Text - ind = tmp.IndexOf(">"c) - tmp = tmp.Substring(ind + 1) - ind = tmp.IndexOf("", StringComparison.Ordinal) - tmp = tmp.Substring(0, ind) - DirectCast(c, LiteralControl).Text = tmp - Retorno.Append(tmp) - Else - If DirectCast(c, LiteralControl).Text.Trim <> "" Then - Retorno.Append(DirectCast(c, LiteralControl).Text.Trim) - End If - End If - ElseIf c.GetType() Is GetType(Literal) Then 'le quito los objetos regulares de html - If DirectCast(c, Literal).Text.Contains("") Then - Dim tmp As String - Dim ind As Integer - tmp = DirectCast(c, Literal).Text - ind = tmp.IndexOf(">"c) - tmp = tmp.Substring(ind + 1) - ind = tmp.IndexOf("", StringComparison.Ordinal) - tmp = tmp.Substring(0, ind) - DirectCast(c, Literal).Text = tmp - Retorno.Append(tmp) - Else - If DirectCast(c, Literal).Text.Trim <> "" Then - Retorno.Append(DirectCast(c, Literal).Text.Trim) - End If - End If - End If - - Next - End If - - Return HttpUtility.HtmlDecode(Retorno.ToString) - - End Function - Public Sub GetMultiRowHeader(ByVal e As GridViewRowEventArgs, ByVal GetCels As Collections.SortedList, Optional CssClass As String = "") - - If e.Row.RowType = DataControlRowType.Header Then - Dim row As GridViewRow - Dim enumCels As Collections.IDictionaryEnumerator = GetCels.GetEnumerator() - - row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal) - If CssClass <> "" Then row.CssClass = CssClass - While enumCels.MoveNext() - - Dim count As String() = enumCels.Value.ToString().Split(Convert.ToChar(", ")) - Dim Cell As TableCell - Cell = New TableCell() - If count(2).ToString.ToEntero > 1 Then Cell.RowSpan = Convert.ToInt16(count(2).ToString) - If count(1).ToString.ToEntero > 1 Then Cell.ColumnSpan = Convert.ToInt16(count(1).ToString) - Cell.Controls.Add(New LiteralControl(count(0).ToString())) - Cell.HorizontalAlign = HorizontalAlign.Center - ' Cell.ForeColor = System.Drawing.Color.White - If count.Length >= 4 AndAlso count(3).ToString <> "" Then Cell.CssClass = count(3).ToString - row.Cells.Add(Cell) - End While - - If e.Row.Parent IsNot Nothing Then - e.Row.Parent.Controls.AddAt(0, row) - Else - e.Row.Controls(0).Controls.Add(row) - End If - End If - End Sub - Public Sub GetMultiRowHeader(ByVal Gv As GridView, ByVal e As GridViewRowEventArgs, ByVal GetCels As Collections.SortedList, Optional CssClass As String = "") - - If e.Row.RowType = DataControlRowType.Header Then - Dim row As GridViewRow - Dim enumCels As Collections.IDictionaryEnumerator = GetCels.GetEnumerator() - - row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal) - If CssClass <> "" Then row.CssClass = CssClass - While enumCels.MoveNext() - - Dim count As String() = enumCels.Value.ToString().Split(Convert.ToChar(",")) - Dim Cell As TableCell - Cell = New TableCell() - If count(2).ToString.ToEntero > 1 Then Cell.RowSpan = Convert.ToInt16(count(2).ToString) - If count(1).ToString.ToEntero > 1 Then Cell.ColumnSpan = Convert.ToInt16(count(1).ToString) - Cell.Controls.Add(New LiteralControl(count(0).ToString())) - Cell.HorizontalAlign = HorizontalAlign.Center - ' Cell.ForeColor = System.Drawing.Color.White - If count.Length >= 4 AndAlso count(3).ToString <> "" Then Cell.CssClass = count(3).ToString - row.Cells.Add(Cell) - - End While - - Gv.Controls(0).Controls.AddAt(0, row) - End If + + Private Sub RecursivoLimpiaControlesExcel(Controls As ControlCollection) + For Each c As Control In Controls + + If Not c.Controls Is Nothing AndAlso c.Controls.Count > 0 Then + RecursivoLimpiaControlesExcel(c.Controls) + Else + + If (c.GetType() Is GetType(HtmlImage)) OrElse (c.GetType() Is GetType(ImageButton)) Then 'Oculto las imágenes + c.Visible = False + ElseIf c.GetType() Is GetType(LinkButton) Then 'le quito los hypervínculos a el objeto para que se vea como texto + DirectCast(c, LinkButton).Enabled = False + ElseIf c.GetType() Is GetType(HyperLink) Then 'le quito los hypervínculos a el objeto para que se vea como texto + DirectCast(c, HyperLink).NavigateUrl = "" + ElseIf c.GetType() Is GetType(MaskedEditExtender) Then 'le quito los hypervínculos a el objeto para que se vea como texto + DirectCast(c, MaskedEditExtender).Enabled = False + ElseIf c.GetType() Is GetType(LiteralControl) Then 'le quito los objetos regulares de html + If DirectCast(c, LiteralControl).Text.Contains("") Then + Dim tmp As String + Dim ind As Integer + tmp = DirectCast(c, LiteralControl).Text + ind = tmp.IndexOf(">"c) + tmp = tmp.Substring(ind + 1) + ind = tmp.IndexOf("", StringComparison.Ordinal) + tmp = tmp.Substring(0, ind) + DirectCast(c, LiteralControl).Text = tmp + End If + End If + End If + Next + End Sub + Public Function TextoCelda(Celda As TableCell) As String + Dim Retorno As New StringBuilder + If Celda.Controls.Count = 0 Then + Retorno.Append(Celda.Text) + Else + + For Each c As Control In Celda.Controls + + If c.GetType() Is GetType(Label) Then 'le quito los hypervínculos a el objeto para que se vea como texto + Retorno.Append(DirectCast(c, Label).Text) + ElseIf c.GetType() Is GetType(LinkButton) Then 'le quito los hypervínculos a el objeto para que se vea como texto + DirectCast(c, LinkButton).Enabled = False + Retorno.Append(DirectCast(c, LinkButton).Text) + ElseIf c.GetType() Is GetType(HyperLink) Then 'le quito los hypervínculos a el objeto para que se vea como texto + Retorno.Append(DirectCast(c, HyperLink).Text) + ElseIf c.GetType() Is GetType(LiteralControl) Then 'le quito los objetos regulares de html + If DirectCast(c, LiteralControl).Text.Contains("") Then + Dim tmp As String + Dim ind As Integer + tmp = DirectCast(c, LiteralControl).Text + ind = tmp.IndexOf(">"c) + tmp = tmp.Substring(ind + 1) + ind = tmp.IndexOf("", StringComparison.Ordinal) + tmp = tmp.Substring(0, ind) + DirectCast(c, LiteralControl).Text = tmp + Retorno.Append(tmp) + Else + If DirectCast(c, LiteralControl).Text.Trim <> "" Then + Retorno.Append(DirectCast(c, LiteralControl).Text.Trim) + End If + End If + ElseIf c.GetType() Is GetType(Literal) Then 'le quito los objetos regulares de html + If DirectCast(c, Literal).Text.Contains("") Then + Dim tmp As String + Dim ind As Integer + tmp = DirectCast(c, Literal).Text + ind = tmp.IndexOf(">"c) + tmp = tmp.Substring(ind + 1) + ind = tmp.IndexOf("", StringComparison.Ordinal) + tmp = tmp.Substring(0, ind) + DirectCast(c, Literal).Text = tmp + Retorno.Append(tmp) + Else + If DirectCast(c, Literal).Text.Trim <> "" Then + Retorno.Append(DirectCast(c, Literal).Text.Trim) + End If + End If + End If + + Next + End If + + Return HttpUtility.HtmlDecode(Retorno.ToString) + + End Function + Public Sub GetMultiRowHeader(ByVal e As GridViewRowEventArgs, ByVal GetCels As Collections.SortedList, Optional CssClass As String = "") + + If e.Row.RowType = DataControlRowType.Header Then + Dim row As GridViewRow + Dim enumCels As Collections.IDictionaryEnumerator = GetCels.GetEnumerator() + + row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal) + If CssClass <> "" Then row.CssClass = CssClass + While enumCels.MoveNext() + + Dim count As String() = enumCels.Value.ToString().Split(Convert.ToChar(", ")) + Dim Cell As TableCell + Cell = New TableCell() + If count(2).ToString.ToEntero > 1 Then Cell.RowSpan = Convert.ToInt16(count(2).ToString) + If count(1).ToString.ToEntero > 1 Then Cell.ColumnSpan = Convert.ToInt16(count(1).ToString) + Cell.Controls.Add(New LiteralControl(count(0).ToString())) + Cell.HorizontalAlign = HorizontalAlign.Center + ' Cell.ForeColor = System.Drawing.Color.White + If count.Length >= 4 AndAlso count(3).ToString <> "" Then Cell.CssClass = count(3).ToString + row.Cells.Add(Cell) + End While + + If e.Row.Parent IsNot Nothing Then + e.Row.Parent.Controls.AddAt(0, row) + Else + e.Row.Controls(0).Controls.Add(row) + End If + End If + End Sub + Public Sub GetMultiRowHeader(ByVal Gv As GridView, ByVal e As GridViewRowEventArgs, ByVal GetCels As Collections.SortedList, Optional CssClass As String = "") + + If e.Row.RowType = DataControlRowType.Header Then + Dim row As GridViewRow + Dim enumCels As Collections.IDictionaryEnumerator = GetCels.GetEnumerator() + + row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal) + If CssClass <> "" Then row.CssClass = CssClass + While enumCels.MoveNext() + + Dim count As String() = enumCels.Value.ToString().Split(Convert.ToChar(",")) + Dim Cell As TableCell + Cell = New TableCell() + If count(2).ToString.ToEntero > 1 Then Cell.RowSpan = Convert.ToInt16(count(2).ToString) + If count(1).ToString.ToEntero > 1 Then Cell.ColumnSpan = Convert.ToInt16(count(1).ToString) + Cell.Controls.Add(New LiteralControl(count(0).ToString())) + Cell.HorizontalAlign = HorizontalAlign.Center + ' Cell.ForeColor = System.Drawing.Color.White + If count.Length >= 4 AndAlso count(3).ToString <> "" Then Cell.CssClass = count(3).ToString + row.Cells.Add(Cell) + + End While + + Gv.Controls(0).Controls.AddAt(0, row) + End If End Sub 'Public Function GeneraBytesOC(tCveOrdenCompra As Integer, Optional MR As ReportViewer = Nothing, Optional ConBitacora As Boolean = False) As Byte() ' Dim bytes As Byte() = Nothing @@ -2977,7 +2977,7 @@ Namespace Extensiones ' Return bytes 'End Function -#End Region +#End Region #Region "Reporte PDF" Public Function Borderless(table As Element.Table) As Element.Table For Each el As Element.IBlockElement In table.GetChildren() @@ -2985,131 +2985,131 @@ Namespace Extensiones cell.SetBorder(Borders.Border.NO_BORDER) Next Return table - End Function - - - Public Sub GenerarReportePDF(control As Control, nombreReporte As String, Optional fechaI As String = Nothing, Optional fechaF As String = Nothing) - Dim usuario As Usuario = ObjClsPaginas.UsuarioActual - - Using sw As New StringWriter() - Using hw As New HtmlTextWriter(sw) - - 'Anexa las hojas de estilo antes del HTML - Dim stylesheets As New StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/Styles/ReportePDF.html") - sw.WriteLine(stylesheets.ReadToEnd()) - - control.RenderControl(hw) - - Dim pdfDoc As New PdfDocument(New PdfWriter(HttpContext.Current.Response.OutputStream)) - Dim document As New Document(pdfDoc, PageSize.A4) - document.SetMargins(10.0F, 10.0F, 0.0F, 10.0F) - Dim request As HttpRequest = HttpContext.Current.Request - Dim baseUrl As String = request.Url.OriginalString.Replace(request.Url.PathAndQuery, "") + request.ApplicationPath - Dim properties As New ConverterProperties() - properties.SetBaseUri(baseUrl) 'Se tiene que usar la URL en vez del BaseDirectory para que cargue correctamente los StyleBundle que son paths virtuales en el servidor - properties.SetFontProvider(New DefaultFontProvider(True, False, False)) - - 'SECCIÓN ENCABEZADO REPORTE - Dim table As Element.Table = New Element.Table(UnitValue.CreatePercentArray(New Single() {10, 50, 40})).UseAllAvailableWidth() - Dim Imagen As New FileInfo(String.Format("{0}/Logo.png", usuario.Empresa.Ruta)) - If Imagen.Exists Then - Dim Ruta As String = String.Format("{0}/Logo.png", usuario.Empresa.Ruta) - Using sr As New StreamReader(Ruta) - Dim ms As New MemoryStream() - sr.BaseStream.CopyTo(ms) - Dim logo As New Element.Image(iText.IO.Image.ImageDataFactory.Create(Imagen.FullName)) - table.AddCell(New Element.Cell(2, 1).Add(logo.SetAutoScale(True)).SetVerticalAlignment(VerticalAlignment.MIDDLE)) - End Using - Else - table.AddCell(New Element.Cell(2, 1).Add(New Element.Paragraph(""))) - End If - table.AddCell(New Element.Cell(2, 1).Add(New Element.Paragraph(usuario.Empresa.Empresa)).SetVerticalAlignment(VerticalAlignment.MIDDLE)) - table.AddCell(New Element.Cell().Add(New Element.Paragraph(nombreReporte)).SetBold) - If fechaI IsNot Nothing Or fechaF IsNot Nothing Then - table.AddCell(New Element.Paragraph(String.Format("Inicio: {0} Fin: {1}", fechaI, fechaF)).SetFontSize(10)) - Else - table.AddCell(New Element.Paragraph(String.Format("Fecha: {0}", ClsPaginas.NowADS().ToString("dd/MM/yyyy HH:mm"))).SetFontSize(10)) - End If - document.Add(Borderless(table)) - 'FIN ENCABEZADO - - 'CUERPO (TABLAS DEL REPORTE) - 'Se tiene que convertir la salida en elementos y posteriormente agregarlos al documento para que se respeten los márgenes - Dim els As IList(Of Element.IElement) = HtmlConverter.ConvertToElements(sw.ToString(), properties) - For Each el As Element.IBlockElement In els - document.Add(el) - Next - 'FIN CUERPO - - 'SECCIÓN PIE REPORTE - table = New Element.Table(UnitValue.CreatePercentArray(New Single() {2, 1.25})) - table.AddCell(New Element.Paragraph("Usuario imprimió: " + usuario.Nombre).SetFontSize(9)) - table.AddCell(New Element.Paragraph("Fecha de impresión: " + ClsPaginas.NowADS().ToString("dd/MM/yyyy")).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(9)) - document.Add(Borderless(table)) - 'FIN PIE - - 'document.Add(New Element.Paragraph(sw.ToString()).SetFontSize(6)) 'Para ver el HTML que se está mandando - document.Close() - HttpContext.Current.Response.ContentType = "application/pdf" - If fechaI IsNot Nothing Or fechaF IsNot Nothing Then - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0} {1} a {2}.pdf", nombreReporte, fechaI.ToDate.ToString("dd-MM-yyyy"), fechaF.ToDate.ToString("dd-MM-yyyy"))) - Else - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0} {1}.pdf", nombreReporte, ClsPaginas.NowADS().ToString("dd-MM-yyyy"))) - End If - HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache) - 'HtmlConverter.ConvertToPdf(sw.ToString(), HttpContext.Current.Response.OutputStream) - HttpContext.Current.Response.End() - - End Using - End Using + End Function + + + Public Sub GenerarReportePDF(control As Control, nombreReporte As String, Optional fechaI As String = Nothing, Optional fechaF As String = Nothing) + Dim usuario As Usuario = ObjClsPaginas.UsuarioActual + + Using sw As New StringWriter() + Using hw As New HtmlTextWriter(sw) + + 'Anexa las hojas de estilo antes del HTML + Dim stylesheets As New StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/Styles/ReportePDF.html") + sw.WriteLine(stylesheets.ReadToEnd()) + + control.RenderControl(hw) + + Dim pdfDoc As New PdfDocument(New PdfWriter(HttpContext.Current.Response.OutputStream)) + Dim document As New Document(pdfDoc, PageSize.A4) + document.SetMargins(10.0F, 10.0F, 0.0F, 10.0F) + Dim request As HttpRequest = HttpContext.Current.Request + Dim baseUrl As String = request.Url.OriginalString.Replace(request.Url.PathAndQuery, "") + request.ApplicationPath + Dim properties As New ConverterProperties() + properties.SetBaseUri(baseUrl) 'Se tiene que usar la URL en vez del BaseDirectory para que cargue correctamente los StyleBundle que son paths virtuales en el servidor + properties.SetFontProvider(New DefaultFontProvider(True, False, False)) + + 'SECCIÓN ENCABEZADO REPORTE + Dim table As Element.Table = New Element.Table(UnitValue.CreatePercentArray(New Single() {10, 50, 40})).UseAllAvailableWidth() + Dim Imagen As New FileInfo(String.Format("{0}/Logo.png", usuario.Empresa.Ruta)) + If Imagen.Exists Then + Dim Ruta As String = String.Format("{0}/Logo.png", usuario.Empresa.Ruta) + Using sr As New StreamReader(Ruta) + Dim ms As New MemoryStream() + sr.BaseStream.CopyTo(ms) + Dim logo As New Element.Image(iText.IO.Image.ImageDataFactory.Create(Imagen.FullName)) + table.AddCell(New Element.Cell(2, 1).Add(logo.SetAutoScale(True)).SetVerticalAlignment(VerticalAlignment.MIDDLE)) + End Using + Else + table.AddCell(New Element.Cell(2, 1).Add(New Element.Paragraph(""))) + End If + table.AddCell(New Element.Cell(2, 1).Add(New Element.Paragraph(usuario.Empresa.Empresa)).SetVerticalAlignment(VerticalAlignment.MIDDLE)) + table.AddCell(New Element.Cell().Add(New Element.Paragraph(nombreReporte)).SetBold) + If fechaI IsNot Nothing Or fechaF IsNot Nothing Then + table.AddCell(New Element.Paragraph(String.Format("Inicio: {0} Fin: {1}", fechaI, fechaF)).SetFontSize(10)) + Else + table.AddCell(New Element.Paragraph(String.Format("Fecha: {0}", ClsPaginas.NowADS().ToString("dd/MM/yyyy HH:mm"))).SetFontSize(10)) + End If + document.Add(Borderless(table)) + 'FIN ENCABEZADO + + 'CUERPO (TABLAS DEL REPORTE) + 'Se tiene que convertir la salida en elementos y posteriormente agregarlos al documento para que se respeten los márgenes + Dim els As IList(Of Element.IElement) = HtmlConverter.ConvertToElements(sw.ToString(), properties) + For Each el As Element.IBlockElement In els + document.Add(el) + Next + 'FIN CUERPO + + 'SECCIÓN PIE REPORTE + table = New Element.Table(UnitValue.CreatePercentArray(New Single() {2, 1.25})) + table.AddCell(New Element.Paragraph("Usuario imprimió: " + usuario.Nombre).SetFontSize(9)) + table.AddCell(New Element.Paragraph("Fecha de impresión: " + ClsPaginas.NowADS().ToString("dd/MM/yyyy")).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(9)) + document.Add(Borderless(table)) + 'FIN PIE + + 'document.Add(New Element.Paragraph(sw.ToString()).SetFontSize(6)) 'Para ver el HTML que se está mandando + document.Close() + HttpContext.Current.Response.ContentType = "application/pdf" + If fechaI IsNot Nothing Or fechaF IsNot Nothing Then + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0} {1} a {2}.pdf", nombreReporte, fechaI.ToDate.ToString("dd-MM-yyyy"), fechaF.ToDate.ToString("dd-MM-yyyy"))) + Else + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0} {1}.pdf", nombreReporte, ClsPaginas.NowADS().ToString("dd-MM-yyyy"))) + End If + HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache) + 'HtmlConverter.ConvertToPdf(sw.ToString(), HttpContext.Current.Response.OutputStream) + HttpContext.Current.Response.End() + + End Using + End Using End Sub #End Region - Public Function IsFileLocked(path As String, Optional access As FileAccess = FileAccess.Write) As Boolean - Try - If File.Exists(path) Then - Using fs As New FileStream(path, FileMode.Open, access, FileShare.ReadWrite) - End Using - End If - Catch e As IOException - Return True ' (Marshal.GetHRForException(e) And &HFFFF) = 32 - End Try - - Return False - End Function - - - Public Function SetFileToBase64String(ByVal fileName As String) As String - Dim ReturnValue As String = "" - If My.Computer.FileSystem.FileExists(fileName) Then - Using BinaryFile As FileStream = New FileStream(fileName, FileMode.Open) - Dim BinRead As BinaryReader = New BinaryReader(BinaryFile) - Dim BinBytes As Byte() = BinRead.ReadBytes(CInt(BinaryFile.Length)) - ReturnValue = Convert.ToBase64String(BinBytes) - BinaryFile.Close() - End Using - End If - Return ReturnValue - End Function - - - - Function Base64ToImage(ByVal base64string As String) As System.Drawing.Image - 'Setup image and get data stream together - Dim img As System.Drawing.Image - Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream - Dim b64 As String = base64string.Replace(" ", "+") - Dim b() As Byte - - 'Converts the base64 encoded msg to image data - b = Convert.FromBase64String(b64) - MS = New System.IO.MemoryStream(b) - - 'creates image - img = System.Drawing.Image.FromStream(MS) - - Return img - End Function - + Public Function IsFileLocked(path As String, Optional access As FileAccess = FileAccess.Write) As Boolean + Try + If File.Exists(path) Then + Using fs As New FileStream(path, FileMode.Open, access, FileShare.ReadWrite) + End Using + End If + Catch e As IOException + Return True ' (Marshal.GetHRForException(e) And &HFFFF) = 32 + End Try + + Return False + End Function + + + Public Function SetFileToBase64String(ByVal fileName As String) As String + Dim ReturnValue As String = "" + If My.Computer.FileSystem.FileExists(fileName) Then + Using BinaryFile As FileStream = New FileStream(fileName, FileMode.Open) + Dim BinRead As BinaryReader = New BinaryReader(BinaryFile) + Dim BinBytes As Byte() = BinRead.ReadBytes(CInt(BinaryFile.Length)) + ReturnValue = Convert.ToBase64String(BinBytes) + BinaryFile.Close() + End Using + End If + Return ReturnValue + End Function + + + + Function Base64ToImage(ByVal base64string As String) As System.Drawing.Image + 'Setup image and get data stream together + Dim img As System.Drawing.Image + Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream + Dim b64 As String = base64string.Replace(" ", "+") + Dim b() As Byte + + 'Converts the base64 encoded msg to image data + b = Convert.FromBase64String(b64) + MS = New System.IO.MemoryStream(b) + + 'creates image + img = System.Drawing.Image.FromStream(MS) + + Return img + End Function + Public Function ToBase64Encode(ByVal plainText As String) As String Dim plainTextBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(plainText) @@ -3120,121 +3120,121 @@ Namespace Extensiones Public Function ToBase64Decode(ByVal base64EncodedData As String) As String Dim base64EncodedBytes As Byte() = System.Convert.FromBase64String(base64EncodedData) Return System.Text.Encoding.UTF8.GetString(base64EncodedBytes) - End Function - Public Function DecriptaConexion() As String - Dim Salida As String - Dim stringtodecrypt As String = ConfigurationManager.ConnectionStrings("Conexion").ConnectionString - Dim SEncryptionKey As String = "$gj7+5&j" - - If stringtodecrypt <> "" Then - Salida = stringtodecrypt.Replace(" ", "+") - Dim inputByteArray(Salida.Length) As Byte - Dim key() As Byte = {} - Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} - - key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) - Dim des As New DESCryptoServiceProvider() - inputByteArray = Convert.FromBase64String(Salida) - - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Dim encoding As Encoding = Encoding.UTF8 - - Salida = encoding.GetString(ms.ToArray()) - des.Dispose() : ms.Dispose() : cs.Dispose() : key = Nothing - Return Salida - End If - - Return "" - End Function - - Public Function Decripta(ByVal stringToDecrypt As String, Optional ByVal TipoEncryption As String = "DES") As String - - Dim Salida As String - - If stringToDecrypt <> "" Then - Salida = stringToDecrypt.Replace(" ", "+") - Dim inputByteArray(Salida.Length) As Byte - - Try - Select Case TipoEncryption - Case "DES" - _Key = Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) - Dim des As New DESCryptoServiceProvider() - inputByteArray = Convert.FromBase64String(Salida) - - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, des.CreateDecryptor(_Key, _IV), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Dim encoding As Encoding = Text.Encoding.UTF8 - - Salida = encoding.GetString(ms.ToArray()) - des.Dispose() : ms.Dispose() : cs.Dispose() - Case "AES" - _Key = Text.Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32)) - Dim aes As New AesCryptoServiceProvider() - inputByteArray = Convert.FromBase64String(Salida) - - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, aes.CreateDecryptor(_Key, _IVAES), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Dim encoding As Encoding = Text.Encoding.UTF8 - - Salida = encoding.GetString(ms.ToArray()) - aes.Dispose() : ms.Dispose() : cs.Dispose() - End Select - - Catch e As Exception - 'Alert("Parametros incorrectos", TipoMensaje.MsgError) - Return "" - End Try - Else - Return "" - End If - - Return Salida - End Function - - Public Function Encripta(ByVal stringToEncrypt As String, Optional ByVal TipoEncryption As String = "DES") As String - If stringToEncrypt = "" Then Return "" - - Dim Retorno As String = "" - Select Case TipoEncryption - Case "DES" - _Key = Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) - Dim des As New DESCryptoServiceProvider() - Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt) - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, des.CreateEncryptor(_Key, _IV), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Retorno = Convert.ToBase64String(ms.ToArray()) - des.Dispose() : ms.Dispose() : cs.Dispose() - Case "AES" - _Key = Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32)) - Dim aes As New AesCryptoServiceProvider() - Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt) - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, aes.CreateEncryptor(_Key, _IVAES), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Retorno = Convert.ToBase64String(ms.ToArray()) - aes.Dispose() : ms.Dispose() : cs.Dispose() - End Select - - - Return Retorno - + End Function + Public Function DecriptaConexion() As String + Dim Salida As String + Dim stringtodecrypt As String = ConfigurationManager.ConnectionStrings("Conexion").ConnectionString + Dim SEncryptionKey As String = "$gj7+5&j" + + If stringtodecrypt <> "" Then + Salida = stringtodecrypt.Replace(" ", "+") + Dim inputByteArray(Salida.Length) As Byte + Dim key() As Byte = {} + Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} + + key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) + Dim des As New DESCryptoServiceProvider() + inputByteArray = Convert.FromBase64String(Salida) + + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Dim encoding As Encoding = Encoding.UTF8 + + Salida = encoding.GetString(ms.ToArray()) + des.Dispose() : ms.Dispose() : cs.Dispose() : key = Nothing + Return Salida + End If + + Return "" End Function -#Region "Contabilidad" + Public Function Decripta(ByVal stringToDecrypt As String, Optional ByVal TipoEncryption As String = "DES") As String - Public Function ContabilizaMovimientoAlmacen(ByRef ObjConta As ClsContabilidad, Fecha As Date, Concepto As String, Modulo As String, CveMovimientoSalida As Integer, CveMovimientoEntrada As Integer, Importe As Decimal, CveUsuario As Integer, CveEmpresa As Integer, Contabilizable As Boolean) As Integer - Dim Retorno As Integer = -1 + Dim Salida As String + + If stringToDecrypt <> "" Then + Salida = stringToDecrypt.Replace(" ", "+") + Dim inputByteArray(Salida.Length) As Byte + + Try + Select Case TipoEncryption + Case "DES" + _Key = Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) + Dim des As New DESCryptoServiceProvider() + inputByteArray = Convert.FromBase64String(Salida) + + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, des.CreateDecryptor(_Key, _IV), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Dim encoding As Encoding = Text.Encoding.UTF8 + + Salida = encoding.GetString(ms.ToArray()) + des.Dispose() : ms.Dispose() : cs.Dispose() + Case "AES" + _Key = Text.Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32)) + Dim aes As New AesCryptoServiceProvider() + inputByteArray = Convert.FromBase64String(Salida) + + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, aes.CreateDecryptor(_Key, _IVAES), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Dim encoding As Encoding = Text.Encoding.UTF8 + + Salida = encoding.GetString(ms.ToArray()) + aes.Dispose() : ms.Dispose() : cs.Dispose() + End Select + + Catch e As Exception + 'Alert("Parametros incorrectos", TipoMensaje.MsgError) + Return "" + End Try + Else + Return "" + End If + + Return Salida + End Function + + Public Function Encripta(ByVal stringToEncrypt As String, Optional ByVal TipoEncryption As String = "DES") As String + If stringToEncrypt = "" Then Return "" + + Dim Retorno As String = "" + Select Case TipoEncryption + Case "DES" + _Key = Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) + Dim des As New DESCryptoServiceProvider() + Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt) + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, des.CreateEncryptor(_Key, _IV), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Retorno = Convert.ToBase64String(ms.ToArray()) + des.Dispose() : ms.Dispose() : cs.Dispose() + Case "AES" + _Key = Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32)) + Dim aes As New AesCryptoServiceProvider() + Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt) + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, aes.CreateEncryptor(_Key, _IVAES), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Retorno = Convert.ToBase64String(ms.ToArray()) + aes.Dispose() : ms.Dispose() : cs.Dispose() + End Select + + + Return Retorno + + End Function + +#Region "Contabilidad" + + Public Function ContabilizaMovimientoAlmacen(ByRef ObjConta As ClsContabilidad, Fecha As Date, Concepto As String, Modulo As String, CveMovimientoSalida As Integer, CveMovimientoEntrada As Integer, Importe As Decimal, CveUsuario As Integer, CveEmpresa As Integer, Contabilizable As Boolean) As Integer + Dim Retorno As Integer = -1 Dim ErrorMovInv As Boolean = False Dim CvePrePoliza As Integer = ObjConta.AddPrePolizas(Modulo, 53, 0, 0, 1, Fecha, Concepto, CveUsuario, CveEmpresa) @@ -3246,186 +3246,186 @@ Namespace Extensiones ErrorMovInv = True End If - If Not ErrorMovInv Then Retorno = CvePrePoliza - - Return Retorno - End Function -#End Region + If Not ErrorMovInv Then Retorno = CvePrePoliza -#Region "GPS" - Public Function InfoWindow(Header As String, ExtraBody As String, CveDispositivo As Integer, row As DataRow, Optional PermisoComandos As Boolean = True) As String - Dim SBuilder As New StringBuilder - SBuilder.Clear() - SBuilder.Append($"
    ") - SBuilder.Append($"") - SBuilder.Append($"
    ") - SBuilder.Append($"") - SBuilder.Append($"") - If row("SPD").ToString <> "-1" Then - SBuilder.Append($"") - End If - If ExtraBody <> "" AndAlso ExtraBody <> "-1" Then - SBuilder.Append(ExtraBody) - End If - If PermisoComandos Then - SBuilder.Append($"") - End If - SBuilder.AppendFormat("", row("Lat").ToString, row("Lng").ToString) - SBuilder.Append($"
    Fecha : {row("FechaTrama")}
    Conductor : {row("Conductor").ToString}
    Velocidad : {row("SPD").ToString} KM/H
    Comandos
    Ver en google maps
    ") - Return SBuilder.ToString - End Function - - Public Function SQLToGmaps(CoordsSQL As String, Tipo As String) As String - Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "") - Dim CoordsPuntos() As String = CoordsPoligono.Split(","c) - Dim Var As String = If(Tipo = "POINT", "", "[") - For Each coordenada As String In CoordsPuntos - If coordenada Is CoordsPuntos.Last Then - Dim latlng() As String = coordenada.Trim.Split(" "c) - Var = $"{Var}{{lat: {latlng(1)}, lng: {latlng(0)} }}" - Else - Dim latlng() As String = coordenada.Trim.Split(" "c) - Var = $"{Var}{{lat: {latlng(1)}, lng: {latlng(0)} }}," - End If - Next - If Tipo <> "POINT" Then Var = $"{Var}]" - Return Var - End Function - - Public Function SQLToGmapsJArray(CoordsSQL As String, Tipo As String) As Newtonsoft.Json.Linq.JArray - Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "") - Dim CoordsPuntos() As String = CoordsPoligono.Split(","c) - - Dim Json As New Newtonsoft.Json.Linq.JArray(From coord In CoordsPuntos - Let c = coord.Trim.Split(" "c) - Select New Newtonsoft.Json.Linq.JObject( - New Newtonsoft.Json.Linq.JProperty("lat", c(1).ToDouble), - New Newtonsoft.Json.Linq.JProperty("lng", c(0).ToDouble) - ) - ) - - Return Json - End Function - - Public Function EncodeGeocerca(GeoCerca As String) As String - Dim Str As New StringBuilder - Dim PrimerSplit As Boolean = True - GeoCerca = GeoCerca.Replace("POLYGON ((", "").Replace("))", "") - Dim S() As String = GeoCerca.Split(","c) - - For Each valor As String In S - If PrimerSplit Then - Str.Append(Encode(valor.Split(" "c)(1).ToDouble, valor.Split(" "c)(0).ToDouble)) - PrimerSplit = False - Else - Str.Append(Encode(valor.Split(" "c)(2).ToDouble, valor.Split(" "c)(1).ToDouble)) - End If - Next - Return Str.ToString - End Function - - Public Function Encode(lats As Double, lngs As Double) As String - Dim str As New StringBuilder() - Dim encodeDiff = DirectCast(Function(diff) As Integer - Dim shifted As Integer = diff << 1 - If diff < 0 Then - shifted = Not shifted - End If - Dim [rem] As Integer = shifted - While [rem] >= &H20 - str.Append(Chr((&H20 Or ([rem] And &H1F)) + 63)) - [rem] >>= 5 - End While - str.Append(Chr([rem] + 63)) - Return 0 - End Function, Action(Of Integer)) - Dim lastLat As Integer = 0 - Dim lastLng As Integer = 0 - Dim lat As Integer = CInt(Math.Round(lats * 100000.0)) - Dim lng As Integer = CInt(Math.Round(lngs * 100000.0)) - encodeDiff(lat - lastLat) - encodeDiff(lng - lastLng) - lastLat = lat - lastLng = lng - Return str.ToString() - End Function - - Public Function EncodeGeocercaString(GeoCerca As String) As String - Dim Str As New StringBuilder - Dim PrimerSplit As Boolean = True - GeoCerca = GeoCerca.Replace("POLYGON ((", "").Replace("))", "") - Dim S() As String = GeoCerca.Split(","c) - - For Each valor As String In S - If PrimerSplit Then - Str.Append(($"{valor.Split(" "c)(1)},{valor.Split(" "c)(0)}")) - PrimerSplit = False - Else - Str.Append(($"|{valor.Split(" "c)(2)},{valor.Split(" "c)(1)}")) - End If - Next - Return Str.ToString + Return Retorno + End Function +#End Region + +#Region "GPS" + Public Function InfoWindow(Header As String, ExtraBody As String, CveDispositivo As Integer, row As DataRow, Optional PermisoComandos As Boolean = True) As String + Dim SBuilder As New StringBuilder + SBuilder.Clear() + SBuilder.Append($"
    ") + SBuilder.Append($"") + SBuilder.Append($"
    ") + SBuilder.Append($"") + SBuilder.Append($"") + If row("SPD").ToString <> "-1" Then + SBuilder.Append($"") + End If + If ExtraBody <> "" AndAlso ExtraBody <> "-1" Then + SBuilder.Append(ExtraBody) + End If + If PermisoComandos Then + SBuilder.Append($"") + End If + SBuilder.AppendFormat("", row("Lat").ToString, row("Lng").ToString) + SBuilder.Append($"
    Fecha : {row("FechaTrama")}
    Conductor : {row("Conductor").ToString}
    Velocidad : {row("SPD").ToString} KM/H
    Comandos
    Ver en google maps
    ") + Return SBuilder.ToString + End Function + + Public Function SQLToGmaps(CoordsSQL As String, Tipo As String) As String + Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "") + Dim CoordsPuntos() As String = CoordsPoligono.Split(","c) + Dim Var As String = If(Tipo = "POINT", "", "[") + For Each coordenada As String In CoordsPuntos + If coordenada Is CoordsPuntos.Last Then + Dim latlng() As String = coordenada.Trim.Split(" "c) + Var = $"{Var}{{lat: {latlng(1)}, lng: {latlng(0)} }}" + Else + Dim latlng() As String = coordenada.Trim.Split(" "c) + Var = $"{Var}{{lat: {latlng(1)}, lng: {latlng(0)} }}," + End If + Next + If Tipo <> "POINT" Then Var = $"{Var}]" + Return Var + End Function + + Public Function SQLToGmapsJArray(CoordsSQL As String, Tipo As String) As Newtonsoft.Json.Linq.JArray + Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "") + Dim CoordsPuntos() As String = CoordsPoligono.Split(","c) + + Dim Json As New Newtonsoft.Json.Linq.JArray(From coord In CoordsPuntos + Let c = coord.Trim.Split(" "c) + Select New Newtonsoft.Json.Linq.JObject( + New Newtonsoft.Json.Linq.JProperty("lat", c(1).ToDouble), + New Newtonsoft.Json.Linq.JProperty("lng", c(0).ToDouble) + ) + ) + + Return Json End Function -#End Region - Private Function GeneraCadenaDinamica(Optional Longitud As Integer = 8) As String - - Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnnopqrstuvwxyz" - Dim r As New Random - Dim sb As New StringBuilder - For i As Integer = 1 To Longitud - Dim idx As Integer = r.Next(0, 62) - sb.Append(s.Substring(idx, 1)) - Next - - Return sb.ToString - - End Function - - - Public Function Contiene(Valor As Integer, ParamArray Valores() As Integer) As Boolean - - Return Array.IndexOf(Valores, Valor) >= 0 - - End Function - - - Public Function Contiene(Valor As String, ParamArray Valores() As String) As Boolean - - Return Array.IndexOf(Valores, Valor) >= 0 - + Public Function EncodeGeocerca(GeoCerca As String) As String + Dim Str As New StringBuilder + Dim PrimerSplit As Boolean = True + GeoCerca = GeoCerca.Replace("POLYGON ((", "").Replace("))", "") + Dim S() As String = GeoCerca.Split(","c) + + For Each valor As String In S + If PrimerSplit Then + Str.Append(Encode(valor.Split(" "c)(1).ToDouble, valor.Split(" "c)(0).ToDouble)) + PrimerSplit = False + Else + Str.Append(Encode(valor.Split(" "c)(2).ToDouble, valor.Split(" "c)(1).ToDouble)) + End If + Next + Return Str.ToString + End Function + + Public Function Encode(lats As Double, lngs As Double) As String + Dim str As New StringBuilder() + Dim encodeDiff = DirectCast(Function(diff) As Integer + Dim shifted As Integer = diff << 1 + If diff < 0 Then + shifted = Not shifted + End If + Dim [rem] As Integer = shifted + While [rem] >= &H20 + str.Append(Chr((&H20 Or ([rem] And &H1F)) + 63)) + [rem] >>= 5 + End While + str.Append(Chr([rem] + 63)) + Return 0 + End Function, Action(Of Integer)) + Dim lastLat As Integer = 0 + Dim lastLng As Integer = 0 + Dim lat As Integer = CInt(Math.Round(lats * 100000.0)) + Dim lng As Integer = CInt(Math.Round(lngs * 100000.0)) + encodeDiff(lat - lastLat) + encodeDiff(lng - lastLng) + lastLat = lat + lastLng = lng + Return str.ToString() + End Function + + Public Function EncodeGeocercaString(GeoCerca As String) As String + Dim Str As New StringBuilder + Dim PrimerSplit As Boolean = True + GeoCerca = GeoCerca.Replace("POLYGON ((", "").Replace("))", "") + Dim S() As String = GeoCerca.Split(","c) + + For Each valor As String In S + If PrimerSplit Then + Str.Append(($"{valor.Split(" "c)(1)},{valor.Split(" "c)(0)}")) + PrimerSplit = False + Else + Str.Append(($"|{valor.Split(" "c)(2)},{valor.Split(" "c)(1)}")) + End If + Next + Return Str.ToString + End Function + +#End Region + Private Function GeneraCadenaDinamica(Optional Longitud As Integer = 8) As String + + Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnnopqrstuvwxyz" + Dim r As New Random + Dim sb As New StringBuilder + For i As Integer = 1 To Longitud + Dim idx As Integer = r.Next(0, 62) + sb.Append(s.Substring(idx, 1)) + Next + + Return sb.ToString + + End Function + + + Public Function Contiene(Valor As Integer, ParamArray Valores() As Integer) As Boolean + + Return Array.IndexOf(Valores, Valor) >= 0 + + End Function + + + Public Function Contiene(Valor As String, ParamArray Valores() As String) As Boolean + + Return Array.IndexOf(Valores, Valor) >= 0 + End Function -#Region "selected" - - Public Sub SelectedValueExist(Obj As DropDownList, Valor As Object) - - If (Obj.Items.FindByValue(Valor.ToString()) IsNot Nothing) Then Obj.SelectedValue = Valor.ToString - - End Sub - - Public Sub SelectedValueExistInsert(Obj As DropDownList, Valor As Object, Texto As String) - - If (Obj.Items.FindByValue(Valor.ToString()) IsNot Nothing) Then - Obj.SelectedValue = Valor.ToString() - Else +#Region "selected" + + Public Sub SelectedValueExist(Obj As DropDownList, Valor As Object) + + If (Obj.Items.FindByValue(Valor.ToString()) IsNot Nothing) Then Obj.SelectedValue = Valor.ToString + + End Sub + + Public Sub SelectedValueExistInsert(Obj As DropDownList, Valor As Object, Texto As String) + + If (Obj.Items.FindByValue(Valor.ToString()) IsNot Nothing) Then + Obj.SelectedValue = Valor.ToString() + Else If Obj.Items.Count > 0 Then Obj.Items.Insert(1, New ListItem(Texto, Valor.ToString())) Else Obj.Items.Insert(0, New ListItem(Texto, Valor.ToString())) - End If - Obj.SelectedValue = Valor.ToString() - End If - - End Sub - - Public Sub SelectedTextExist(Obj As DropDownList, Valor As Object) - - If (Obj.Items.FindByText(Valor.ToString()) IsNot Nothing) Then Obj.SelectedValue = Obj.Items.FindByText(Valor.ToString()).Value - + End If + Obj.SelectedValue = Valor.ToString() + End If + End Sub - + + Public Sub SelectedTextExist(Obj As DropDownList, Valor As Object) + + If (Obj.Items.FindByText(Valor.ToString()) IsNot Nothing) Then Obj.SelectedValue = Obj.Items.FindByText(Valor.ToString()).Value + + End Sub + Public Sub SelectedTextLikeIfExist(Rbl As DropDownList, Valor As String) If Valor <> "" Then Rbl.ClearSelection() @@ -3435,276 +3435,276 @@ Namespace Extensiones End If Next End If - End Sub - - Public Sub SelectedValuesIfExist(ByRef Rbl As RadioButtonList, ByRef Value As String) - Try - Dim valores As String() = Value.Split(CType(",", Char())) - For Each item As ListItem In Rbl.Items - If item.Value.Contiene(valores) Then - item.Selected = True - End If - Next - Catch ex As Exception - - End Try - End Sub - - Public Sub SelectedValuesIfExist(ByRef Rbl As CheckBoxList, ByRef Value As String) - Try - Dim valores As String() = Value.Split(CType(",", Char())) - For Each item As ListItem In Rbl.Items - If item.Value.Contiene(valores) Then - item.Selected = True - End If - Next - Catch ex As Exception - - End Try - End Sub - - Public Function GetSelectedValues(ByRef Ddl As CheckBoxList) As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.AppendFormat("{0}{1}", prefix, item.Value) - prefix = "," - End If - Next - Return retorno.ToString() - End Function - - Public Function GetSelectedText(ByRef Ddl As CheckBoxList) As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.AppendFormat("{0}{1}", prefix, item.Text) - prefix = "," - End If - Next - Return retorno.ToString() - End Function - - Public Sub SelectedValuesIfExist(ByRef Ddl As ListBox, ByRef Value As String) - Try - Dim valores As String() = Value.Split(CType(",", Char())) - For Each item As ListItem In Ddl.Items - If item.Value.Contiene(valores) Then - item.Selected = True - End If - Next - Catch ex As Exception - - End Try - End Sub - - - Public Function GetSelectedValues(ByRef Ddl As ListBox, Optional beforeValue As String = "", Optional AfterValue As String = "") As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.Append($"{prefix}{beforeValue}{item.Value}{AfterValue}") - prefix = "," - End If - Next - Return retorno.ToString() - End Function - - Public Function GetSelectedText(Ddl As ListBox) As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.AppendFormat("{0}{1}", prefix, item.Text) - prefix = "," - End If - Next - Return retorno.ToString() + End Sub + + Public Sub SelectedValuesIfExist(ByRef Rbl As RadioButtonList, ByRef Value As String) + Try + Dim valores As String() = Value.Split(CType(",", Char())) + For Each item As ListItem In Rbl.Items + If item.Value.Contiene(valores) Then + item.Selected = True + End If + Next + Catch ex As Exception + + End Try + End Sub + + Public Sub SelectedValuesIfExist(ByRef Rbl As CheckBoxList, ByRef Value As String) + Try + Dim valores As String() = Value.Split(CType(",", Char())) + For Each item As ListItem In Rbl.Items + If item.Value.Contiene(valores) Then + item.Selected = True + End If + Next + Catch ex As Exception + + End Try + End Sub + + Public Function GetSelectedValues(ByRef Ddl As CheckBoxList) As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.AppendFormat("{0}{1}", prefix, item.Value) + prefix = "," + End If + Next + Return retorno.ToString() + End Function + + Public Function GetSelectedText(ByRef Ddl As CheckBoxList) As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.AppendFormat("{0}{1}", prefix, item.Text) + prefix = "," + End If + Next + Return retorno.ToString() + End Function + + Public Sub SelectedValuesIfExist(ByRef Ddl As ListBox, ByRef Value As String) + Try + Dim valores As String() = Value.Split(CType(",", Char())) + For Each item As ListItem In Ddl.Items + If item.Value.Contiene(valores) Then + item.Selected = True + End If + Next + Catch ex As Exception + + End Try + End Sub + + + Public Function GetSelectedValues(ByRef Ddl As ListBox, Optional beforeValue As String = "", Optional AfterValue As String = "") As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.Append($"{prefix}{beforeValue}{item.Value}{AfterValue}") + prefix = "," + End If + Next + Return retorno.ToString() + End Function + + Public Function GetSelectedText(Ddl As ListBox) As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.AppendFormat("{0}{1}", prefix, item.Text) + prefix = "," + End If + Next + Return retorno.ToString() + End Function +#End Region + Public Enum TipoContaReferencia As Integer + Compra = 1 + Proveedor = 2 + Banco = 3 + Venta = 4 + End Enum + + + Public Function ContaReferencia(Valor As String, Tipo As TipoContaReferencia) As String + Dim Retorno As String = "" + Select Case Tipo + Case TipoContaReferencia.Compra : Retorno = "C||" + Case TipoContaReferencia.Proveedor : Retorno = "P||" + Case TipoContaReferencia.Banco : Retorno = "B||" + Case TipoContaReferencia.Venta : Retorno = "V||" + End Select + + Return String.Format("{0}{1}", Retorno, Valor) + End Function + + Public Function ContaReferenciaLiga(Valor As String) As String + Dim tTemp As String() = Valor.Split({"||"}, StringSplitOptions.None) + Dim Retorno As String = "" + If tTemp.Length = 2 Then + Select Case tTemp(0) + Case "C" : Retorno = String.Format("/Compras/Compras.aspx?CveCompra={0}", tTemp(1)) + Case "P" : Retorno = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", tTemp(1)) + Case "B" : Retorno = String.Format("/Bancos/IE.aspx?CveIE={0}", tTemp(1)) + Case "V" : Retorno = String.Format("/Ventas/Ventas.aspx?CveVenta={0}", tTemp(1)) + + End Select + End If + + + Return Retorno + End Function + + Private Sub MandaCorreoError(Mensaje As String) + Try + Dim ObjMail As New ClsSisMail() + + Dim ObjEmp As New ClsSisEmpresas + If ObjEmp.GetEmpresas(1, "-1", "-1", "-1", "-1") Then + + If ObjMail.SendMail(ObjEmp.Empresa, "rene.molina@adssistemas.mx", "Error del Sistema", Mensaje) Then + + End If + + End If + ObjEmp.Dispose() + + Catch ex As Exception + + End Try + End Sub + + + Public Function ParametrosInfo(ObjCol As SqlClient.SqlParameterCollection) As String + Dim Retorno As New StringBuilder + Retorno.AppendFormat("Parametros:", vbCrLf) + Dim Valor As String + For Each Par As SqlClient.SqlParameter In ObjCol + If Par.Value IsNot Nothing Then Valor = Par.Value.ToString Else Valor = "Nothing" + Retorno.AppendFormat("{0}={1}{2}", Par.ParameterName, Valor, vbCrLf) + Next + + Return Retorno.ToString + End Function + + + Public Sub RegistraScript(Obj As Object, Script As String) + ClsPaginas.RegistraScript(Script) + End Sub + + + Public Function LastDayOfMonth(ByVal Fecha As Date) As Date + Return New DateTime(Fecha.Year, Fecha.Month, 1).AddMonths(1).AddDays(-1) + End Function + + + Public Function FirstDayOfMonth(ByVal Fecha As Date) As Date + Return New DateTime(Fecha.Year, Fecha.Month, 1) + End Function + + Private ReadOnly Property ObjClsPaginas As ClsPaginas + Get + Return DirectCast(System.Web.HttpContext.Current.CurrentHandler, ClsPaginas) + End Get + End Property + + + + + + Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, + ByVal aData As NameValueCollection) + aThis.Clear() + Dim sb As StringBuilder = New StringBuilder() + + sb.Append("") + sb.AppendFormat("") + sb.AppendFormat("
    ", aDestination) + + For Each key As String In aData + sb.AppendFormat("", key, aData(key)) + Next + + sb.Append("
    ") + sb.Append("") + sb.Append("") + + aThis.Write(sb.ToString()) + + aThis.End() + End Sub + + ''' + ''' Convierte una cadena y obtiene su parte numerica + ''' + ''' + ''' + ''' + + Public Function StrToNum(ByVal Str As String) As Integer + Dim returnVal As String = String.Empty + Dim collection As MatchCollection = Regex.Matches(Str, "\d+") + returnVal = collection.Cast(Of Match)().Aggregate(returnVal, Function(Current, m) Current + m.ToString()) + Return returnVal.ToEntero + End Function + + Public Function SerialGemBoxDocument() As String + Return "DMPZ-P9LT-ELXN-XH4H" + + End Function + Public Function SerialGemBoxSpreadsheet() As String + Return "ESWN-4QFD-26JF-1SZ8" + + End Function + + + Public Function QueryToDataTable(Of T)(ByVal source As IEnumerable(Of T), flag As Boolean) As DataTable + Return New ObjectShredder(Of T)().Shred(source, Nothing, Nothing) + End Function + + ' + 'Public Function CopyToDataTable(Of T)(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable + ' Return New ObjectShredder(Of T)().Shred(source, table, options) + 'End Function + + + Public Function GetSelectedValuesM(Ddl As ListBox, Optional conComillasimple As Boolean = False) As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.AppendFormat("{0}{2}{1}{2}", prefix, item.Value, If(conComillasimple, "'", "")) + prefix = "," + End If + Next + Return retorno.ToString() + End Function + + + Public Sub SelectedValuesIfExistM(Ddl As ListBox, Value As String, Optional conComillasimple As Boolean = False) + Try + Dim valores As String() = Value.Split(CType(",", Char())) + For Each item As ListItem In Ddl.Items + If String.Format("{1}{0}{1}", item.Value, If(conComillasimple, "'", "")).Contiene(valores) Then + item.Selected = True + End If + Next + Catch ex As Exception + + End Try + End Sub + + Public Function ConvertFromUnixTimestamp(ByVal timestamp As Double) As DateTime + Dim origin As DateTime = New DateTime(1970, 1, 1, 0, 0, 0, 0) + Return origin.AddSeconds(timestamp) End Function -#End Region - Public Enum TipoContaReferencia As Integer - Compra = 1 - Proveedor = 2 - Banco = 3 - Venta = 4 - End Enum - - - Public Function ContaReferencia(Valor As String, Tipo As TipoContaReferencia) As String - Dim Retorno As String = "" - Select Case Tipo - Case TipoContaReferencia.Compra : Retorno = "C||" - Case TipoContaReferencia.Proveedor : Retorno = "P||" - Case TipoContaReferencia.Banco : Retorno = "B||" - Case TipoContaReferencia.Venta : Retorno = "V||" - End Select - - Return String.Format("{0}{1}", Retorno, Valor) - End Function - - Public Function ContaReferenciaLiga(Valor As String) As String - Dim tTemp As String() = Valor.Split({"||"}, StringSplitOptions.None) - Dim Retorno As String = "" - If tTemp.Length = 2 Then - Select Case tTemp(0) - Case "C" : Retorno = String.Format("/Compras/Compras.aspx?CveCompra={0}", tTemp(1)) - Case "P" : Retorno = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", tTemp(1)) - Case "B" : Retorno = String.Format("/Bancos/IE.aspx?CveIE={0}", tTemp(1)) - Case "V" : Retorno = String.Format("/Ventas/Ventas.aspx?CveVenta={0}", tTemp(1)) - - End Select - End If - - - Return Retorno - End Function - - Private Sub MandaCorreoError(Mensaje As String) - Try - Dim ObjMail As New ClsSisMail() - - Dim ObjEmp As New ClsSisEmpresas - If ObjEmp.GetEmpresas(1, "-1", "-1", "-1", "-1") Then - - If ObjMail.SendMail(ObjEmp.Empresa, "rene.molina@adssistemas.mx", "Error del Sistema", Mensaje) Then - - End If - - End If - ObjEmp.Dispose() - - Catch ex As Exception - - End Try - End Sub - - - Public Function ParametrosInfo(ObjCol As SqlClient.SqlParameterCollection) As String - Dim Retorno As New StringBuilder - Retorno.AppendFormat("Parametros:", vbCrLf) - Dim Valor As String - For Each Par As SqlClient.SqlParameter In ObjCol - If Par.Value IsNot Nothing Then Valor = Par.Value.ToString Else Valor = "Nothing" - Retorno.AppendFormat("{0}={1}{2}", Par.ParameterName, Valor, vbCrLf) - Next - - Return Retorno.ToString - End Function - - - Public Sub RegistraScript(Obj As Object, Script As String) - ClsPaginas.RegistraScript(Script) - End Sub - - - Public Function LastDayOfMonth(ByVal Fecha As Date) As Date - Return New DateTime(Fecha.Year, Fecha.Month, 1).AddMonths(1).AddDays(-1) - End Function - - - Public Function FirstDayOfMonth(ByVal Fecha As Date) As Date - Return New DateTime(Fecha.Year, Fecha.Month, 1) - End Function - - Private ReadOnly Property ObjClsPaginas As ClsPaginas - Get - Return DirectCast(System.Web.HttpContext.Current.CurrentHandler, ClsPaginas) - End Get - End Property - - - - - - Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, - ByVal aData As NameValueCollection) - aThis.Clear() - Dim sb As StringBuilder = New StringBuilder() - - sb.Append("") - sb.AppendFormat("") - sb.AppendFormat("
    ", aDestination) - - For Each key As String In aData - sb.AppendFormat("", key, aData(key)) - Next - - sb.Append("
    ") - sb.Append("") - sb.Append("") - - aThis.Write(sb.ToString()) - - aThis.End() - End Sub - - ''' - ''' Convierte una cadena y obtiene su parte numerica - ''' - ''' - ''' - ''' - - Public Function StrToNum(ByVal Str As String) As Integer - Dim returnVal As String = String.Empty - Dim collection As MatchCollection = Regex.Matches(Str, "\d+") - returnVal = collection.Cast(Of Match)().Aggregate(returnVal, Function(Current, m) Current + m.ToString()) - Return returnVal.ToEntero - End Function - - Public Function SerialGemBoxDocument() As String - Return "DMPZ-P9LT-ELXN-XH4H" - - End Function - Public Function SerialGemBoxSpreadsheet() As String - Return "ESWN-4QFD-26JF-1SZ8" - - End Function - - - Public Function QueryToDataTable(Of T)(ByVal source As IEnumerable(Of T), flag As Boolean) As DataTable - Return New ObjectShredder(Of T)().Shred(source, Nothing, Nothing) - End Function - - ' - 'Public Function CopyToDataTable(Of T)(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable - ' Return New ObjectShredder(Of T)().Shred(source, table, options) - 'End Function - - - Public Function GetSelectedValuesM(Ddl As ListBox, Optional conComillasimple As Boolean = False) As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.AppendFormat("{0}{2}{1}{2}", prefix, item.Value, If(conComillasimple, "'", "")) - prefix = "," - End If - Next - Return retorno.ToString() - End Function - - - Public Sub SelectedValuesIfExistM(Ddl As ListBox, Value As String, Optional conComillasimple As Boolean = False) - Try - Dim valores As String() = Value.Split(CType(",", Char())) - For Each item As ListItem In Ddl.Items - If String.Format("{1}{0}{1}", item.Value, If(conComillasimple, "'", "")).Contiene(valores) Then - item.Selected = True - End If - Next - Catch ex As Exception - - End Try - End Sub - - Public Function ConvertFromUnixTimestamp(ByVal timestamp As Double) As DateTime - Dim origin As DateTime = New DateTime(1970, 1, 1, 0, 0, 0, 0) - Return origin.AddSeconds(timestamp) - End Function Public Function GetLastWeekdayOfMonth(ByVal fecha As DateTime, day As DayOfWeek) As DateTime Dim lastDayOfMonth As DateTime = New DateTime(fecha.Year, fecha.Month, 1).AddMonths(1).AddDays(-1) @@ -3712,7 +3712,7 @@ Namespace Extensiones Dim lastDay As Integer = CInt(lastDayOfMonth.DayOfWeek) Return lastDayOfMonth.AddDays(If(lastDay >= wantedDay, wantedDay - lastDay, wantedDay - lastDay - 7)) End Function - + Public Function GetFirstWeekdayOfMonth(ByVal fecha As DateTime, day As DayOfWeek) As DateTime Dim result As DateTime = New DateTime(fecha.Year, fecha.Month, 1) @@ -3764,9 +3764,9 @@ Namespace Extensiones Next Return text - End Function - - + End Function + + Function ToEscapeXML(ByVal str As String) As String Dim text As String = "" @@ -3791,9 +3791,9 @@ Namespace Extensiones ' Verificar si existe el parámetro RFCPackCertifica Return parameters.Contains(parameterName) - End Function + End Function End Module -#End Region +#End Region #Region "C L A S E S" @@ -3822,210 +3822,210 @@ Namespace Extensiones Property headerstr As List(Of String) - End Class - Public Class Archivo - Public Sub New() - filename = "" - path = "Temp\" - descripcion = "" - End Sub - - Public Property filename As String - Public Property path As String - Public Property descripcion As String - Public ReadOnly Property Extension As String - Get - Return System.IO.Path.GetExtension(String.Format("{0}{1}{2}", If(path.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory), path, filename)).Replace(".", "") - End Get - End Property - Public ReadOnly Property filenameO As String - Get - Return If((filename.IndexOf("-") + 1) = filename.Length, filename, filename.Substring(filename.IndexOf("-") + 1)) - End Get - End Property - Public ReadOnly Property FileUrl As String - Get - Return String.Format("{0}{1}{2}", If(path.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory), path, filename) - End Get - End Property - End Class - Public Class Files - Public Property Archivos As List(Of Archivo) - End Class - Public Class ObjectShredder(Of T) - ' Fields - Private _fi As FieldInfo() - Private _ordinalMap As Dictionary(Of String, Integer) - Private _pi As PropertyInfo() - Private _type As Type - - ' Constructor - Public Sub New() - Me._type = GetType(T) - Me._fi = Me._type.GetFields - Me._pi = Me._type.GetProperties - Me._ordinalMap = New Dictionary(Of String, Integer) - End Sub - - Public Function ShredObject(ByVal table As DataTable, ByVal instance As T) As Object() - Dim fi As FieldInfo() = Me._fi - Dim pi As PropertyInfo() = Me._pi - If (Not instance.GetType Is GetType(T)) Then - ' If the instance is derived from T, extend the table schema - ' and get the properties and fields. - Me.ExtendTable(table, instance.GetType) - fi = instance.GetType.GetFields - pi = instance.GetType.GetProperties - End If - - ' Add the property and field values of the instance to an array. - Dim values As Object() = New Object(table.Columns.Count - 1) {} - Dim f As FieldInfo - For Each f In fi - values(Me._ordinalMap.Item(f.Name)) = f.GetValue(instance) - Next - Dim p As PropertyInfo - For Each p In pi - values(Me._ordinalMap.Item(p.Name)) = p.GetValue(instance, Nothing) - Next - - ' Return the property and field values of the instance. - Return values - End Function - - - ' Summary: Loads a DataTable from a sequence of objects. - ' source parameter: The sequence of objects to load into the DataTable. - ' table parameter: The input table. The schema of the table must match that - ' the type T. If the table is null, a new table is created - ' with a schema created from the public properties and fields - ' of the type T. - ' options parameter: Specifies how values from the source sequence will be applied to - ' existing rows in the table. - ' Returns: A DataTable created from the source sequence. - - Public Function Shred(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable - - ' Load the table from the scalar sequence if T is a primitive type. - If GetType(T).IsPrimitive Then - Return Me.ShredPrimitive(source, table, options) - End If - - ' Create a new table if the input table is null. - If (table Is Nothing) Then - table = New DataTable(GetType(T).Name) - End If - - ' Initialize the ordinal map and extend the table schema based on type T. - table = Me.ExtendTable(table, GetType(T)) - - ' Enumerate the source sequence and load the object values into rows. - table.BeginLoadData() - Using e As IEnumerator(Of T) = source.GetEnumerator - Do While e.MoveNext - If options.HasValue Then - table.LoadDataRow(Me.ShredObject(table, e.Current), options.Value) - Else - table.LoadDataRow(Me.ShredObject(table, e.Current), True) - End If - Loop - End Using - table.EndLoadData() - - ' Return the table. - Return table - End Function - - - Public Function ShredPrimitive(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable - ' Create a new table if the input table is null. - If (table Is Nothing) Then - table = New DataTable(GetType(T).Name) - End If - If Not table.Columns.Contains("Value") Then - table.Columns.Add("Value", GetType(T)) - End If - - ' Enumerate the source sequence and load the scalar values into rows. - table.BeginLoadData() - Using e As IEnumerator(Of T) = source.GetEnumerator - Dim values As Object() = New Object(table.Columns.Count - 1) {} - Do While e.MoveNext - values(table.Columns.Item("Value").Ordinal) = e.Current - If options.HasValue Then - table.LoadDataRow(values, options.Value) - Else - table.LoadDataRow(values, True) - End If - Loop - End Using - table.EndLoadData() - - ' Return the table. - Return table - End Function - - Public Function ExtendTable(ByVal table As DataTable, ByVal type As Type) As DataTable - ' Extend the table schema if the input table was null or if the value - ' in the sequence is derived from type T. - Dim f As FieldInfo - Dim p As PropertyInfo - - For Each f In type.GetFields - If Not Me._ordinalMap.ContainsKey(f.Name) Then - Dim dc As DataColumn - - ' Add the field as a column in the table if it doesn't exist - ' already. - dc = If(table.Columns.Contains(f.Name), table.Columns.Item(f.Name), table.Columns.Add(f.Name, f.FieldType)) - - ' Add the field to the ordinal map. - Me._ordinalMap.Add(f.Name, dc.Ordinal) - End If - - Next - - For Each p In type.GetProperties - If Not Me._ordinalMap.ContainsKey(p.Name) Then - ' Add the property as a column in the table if it doesn't exist - ' already. - Dim dc As DataColumn - dc = If(table.Columns.Contains(p.Name), table.Columns.Item(p.Name), table.Columns.Add(p.Name, p.PropertyType)) - - ' Add the property to the ordinal map. - Me._ordinalMap.Add(p.Name, dc.Ordinal) - End If - Next - - ' Return the table. - Return table - End Function - - - - End Class -#End Region + Public Class Archivo + Public Sub New() + filename = "" + path = "Temp\" + descripcion = "" + End Sub -#Region "A T R I B U T O S" - Public Class BasicAuthenticationAttribute - Inherits AuthorizationFilterAttribute + Public Property filename As String + Public Property path As String + Public Property descripcion As String + Public ReadOnly Property Extension As String + Get + Return System.IO.Path.GetExtension(String.Format("{0}{1}{2}", If(path.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory), path, filename)).Replace(".", "") + End Get + End Property + Public ReadOnly Property filenameO As String + Get + Return If((filename.IndexOf("-") + 1) = filename.Length, filename, filename.Substring(filename.IndexOf("-") + 1)) + End Get + End Property + Public ReadOnly Property FileUrl As String + Get + Return String.Format("{0}{1}{2}", If(path.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory), path, filename) + End Get + End Property + End Class + Public Class Files + Public Property Archivos As List(Of Archivo) + End Class + Public Class ObjectShredder(Of T) + ' Fields + Private _fi As FieldInfo() + Private _ordinalMap As Dictionary(Of String, Integer) + Private _pi As PropertyInfo() + Private _type As Type + + ' Constructor + Public Sub New() + Me._type = GetType(T) + Me._fi = Me._type.GetFields + Me._pi = Me._type.GetProperties + Me._ordinalMap = New Dictionary(Of String, Integer) + End Sub + + Public Function ShredObject(ByVal table As DataTable, ByVal instance As T) As Object() + Dim fi As FieldInfo() = Me._fi + Dim pi As PropertyInfo() = Me._pi + If (Not instance.GetType Is GetType(T)) Then + ' If the instance is derived from T, extend the table schema + ' and get the properties and fields. + Me.ExtendTable(table, instance.GetType) + fi = instance.GetType.GetFields + pi = instance.GetType.GetProperties + End If + + ' Add the property and field values of the instance to an array. + Dim values As Object() = New Object(table.Columns.Count - 1) {} + Dim f As FieldInfo + For Each f In fi + values(Me._ordinalMap.Item(f.Name)) = f.GetValue(instance) + Next + Dim p As PropertyInfo + For Each p In pi + values(Me._ordinalMap.Item(p.Name)) = p.GetValue(instance, Nothing) + Next + + ' Return the property and field values of the instance. + Return values + End Function + + + ' Summary: Loads a DataTable from a sequence of objects. + ' source parameter: The sequence of objects to load into the DataTable. + ' table parameter: The input table. The schema of the table must match that + ' the type T. If the table is null, a new table is created + ' with a schema created from the public properties and fields + ' of the type T. + ' options parameter: Specifies how values from the source sequence will be applied to + ' existing rows in the table. + ' Returns: A DataTable created from the source sequence. + + Public Function Shred(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable + + ' Load the table from the scalar sequence if T is a primitive type. + If GetType(T).IsPrimitive Then + Return Me.ShredPrimitive(source, table, options) + End If + + ' Create a new table if the input table is null. + If (table Is Nothing) Then + table = New DataTable(GetType(T).Name) + End If + + ' Initialize the ordinal map and extend the table schema based on type T. + table = Me.ExtendTable(table, GetType(T)) + + ' Enumerate the source sequence and load the object values into rows. + table.BeginLoadData() + Using e As IEnumerator(Of T) = source.GetEnumerator + Do While e.MoveNext + If options.HasValue Then + table.LoadDataRow(Me.ShredObject(table, e.Current), options.Value) + Else + table.LoadDataRow(Me.ShredObject(table, e.Current), True) + End If + Loop + End Using + table.EndLoadData() + + ' Return the table. + Return table + End Function + + + Public Function ShredPrimitive(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable + ' Create a new table if the input table is null. + If (table Is Nothing) Then + table = New DataTable(GetType(T).Name) + End If + If Not table.Columns.Contains("Value") Then + table.Columns.Add("Value", GetType(T)) + End If + + ' Enumerate the source sequence and load the scalar values into rows. + table.BeginLoadData() + Using e As IEnumerator(Of T) = source.GetEnumerator + Dim values As Object() = New Object(table.Columns.Count - 1) {} + Do While e.MoveNext + values(table.Columns.Item("Value").Ordinal) = e.Current + If options.HasValue Then + table.LoadDataRow(values, options.Value) + Else + table.LoadDataRow(values, True) + End If + Loop + End Using + table.EndLoadData() + + ' Return the table. + Return table + End Function + + Public Function ExtendTable(ByVal table As DataTable, ByVal type As Type) As DataTable + ' Extend the table schema if the input table was null or if the value + ' in the sequence is derived from type T. + Dim f As FieldInfo + Dim p As PropertyInfo + + For Each f In type.GetFields + If Not Me._ordinalMap.ContainsKey(f.Name) Then + Dim dc As DataColumn + + ' Add the field as a column in the table if it doesn't exist + ' already. + dc = If(table.Columns.Contains(f.Name), table.Columns.Item(f.Name), table.Columns.Add(f.Name, f.FieldType)) + + ' Add the field to the ordinal map. + Me._ordinalMap.Add(f.Name, dc.Ordinal) + End If + + Next + + For Each p In type.GetProperties + If Not Me._ordinalMap.ContainsKey(p.Name) Then + ' Add the property as a column in the table if it doesn't exist + ' already. + Dim dc As DataColumn + dc = If(table.Columns.Contains(p.Name), table.Columns.Item(p.Name), table.Columns.Add(p.Name, p.PropertyType)) + + ' Add the property to the ordinal map. + Me._ordinalMap.Add(p.Name, dc.Ordinal) + End If + Next + + ' Return the table. + Return table + End Function + + + + + End Class +#End Region + +#Region "A T R I B U T O S" + Public Class BasicAuthenticationAttribute + Inherits AuthorizationFilterAttribute Private Const SigfoxPath As String = "/api/sigfox" Private Const LoginPath As String = "/api/usuario/Login" - Public Property Usuario As String + Public Property Usuario As String Public Property Contra As String Public Sub New() - End Sub - Public Sub New(Usuario As String, Contra As String) - Me.Usuario = Usuario - Me.Contra = Contra - End Sub - - Public Overrides Sub OnAuthorization(ByVal actionContext As HttpActionContext) + End Sub + Public Sub New(Usuario As String, Contra As String) + Me.Usuario = Usuario + Me.Contra = Contra + End Sub + + Public Overrides Sub OnAuthorization(ByVal actionContext As HttpActionContext) Dim authHeader As Headers.AuthenticationHeaderValue = actionContext.Request.Headers.Authorization - Dim noautorizado As Boolean = True - If authHeader IsNot Nothing Then + Dim noautorizado As Boolean = True + If authHeader IsNot Nothing Then If Left(actionContext.Request.RequestUri.AbsolutePath, 11).ToUpper() = SigfoxPath.ToUpper() Then Dim usernamePasswordArray As String() = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(":"c) Dim userName As String = usernamePasswordArray(0) @@ -4060,19 +4060,19 @@ Namespace Extensiones End Try End If - + End If If noautorizado Then HandleUnathorized(actionContext) - End If - End Sub - - Private Shared Sub HandleUnathorized(ByVal actionContext As HttpActionContext) - actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized) - actionContext.Response.Headers.Add("WWW-Authenticate", "Basic Scheme='Data' location = 'http://localhost:") - End Sub - End Class -#End Region + End If + End Sub -End Namespace + Private Shared Sub HandleUnathorized(ByVal actionContext As HttpActionContext) + actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized) + actionContext.Response.Headers.Add("WWW-Authenticate", "Basic Scheme='Data' location = 'http://localhost:") + End Sub + End Class +#End Region + +End Namespace diff --git a/Ashx/CargaEventos.ashx b/Ashx/CargaEventos.ashx index d16322ed9..835024ff1 100644 --- a/Ashx/CargaEventos.ashx +++ b/Ashx/CargaEventos.ashx @@ -554,7 +554,44 @@ Public Class CargaEventos : Implements IHttpHandler, IRequiresSessionState Dim cevent As CalendarEvent = New CalendarEvent() cevent.id = dr("CveContrato").ToString.ToEntero - cevent.title = If(dr("CodigoAF").ToString.Trim.Length > 0, $"#{dr("CodigoAF").ToString}-{dr("DescripcionContrato").ToString}", $"-{dr("DescripcionContrato").ToString}") + cevent.CveTipoAF = dr("CveTipoAF").ToString.ToEntero + cevent.title = $"-{dr("DescripcionContrato").ToString}" + + + If usuarioActual_.CveEmpresa = 188 AndAlso dr("CveTipoAF").ToString.Trim.Length > 0 Then + + Dim TipoAfAbrebiado As String = "" + Select Case cevent.CveTipoAF + Case 181 + TipoAfAbrebiado = "Bus" + Exit Select + 'Case 183 + ' TipoAfAbrebiado = "" + ' Exit Select + Case 184 + TipoAfAbrebiado = "Spr" + Exit Select + 'Case 185 + ' TipoAfAbrebiado = "Uti" + ' Exit Select + Case 191 + TipoAfAbrebiado = "Van" + Exit Select + Case 192 + TipoAfAbrebiado = "Sed" + Exit Select + Case Else + Exit Select + End Select + + cevent.title = $"-{TipoAfAbrebiado}#{dr("CodigoAF").ToString}-{dr("DescripcionContrato").ToString}" + 'cevent.colorfont = "blue" + + Else + cevent.title = $"#{dr("CodigoAF").ToString}-{dr("DescripcionContrato").ToString}" + End If + + cevent.description = dr("DescripcionContrato").ToString cevent.start = String.Format("{0:s}", dr("FechaInicial").ToString.ToDateTime) cevent.end = If(tipoVista = "fecha", String.Format("{0:s}", dr("FechaInicial").ToString.ToDateTime.AddHours(1)), String.Format("{0:s}", dr("FechaFinal").ToString.ToDateTime)) @@ -570,7 +607,7 @@ Public Class CargaEventos : Implements IHttpHandler, IRequiresSessionState cevent.Pesos = dr("ImporteMax").ToString.ToDecimal cevent.Anticipo = dr("ImporteMin").ToString.ToDecimal cevent.CveActivoFijo = dr("CveAF").ToString.ToEntero - cevent.CveTipoAF = dr("CveTipoAF").ToString.ToEntero + cevent.CantidadPasajeros = dr("CantidadPasajeros").ToString cevent.NumeroContrato = dr("NumeroContrato").ToString cevent.Observaciones = dr("Observaciones").ToString diff --git a/Contabilidad/LibroMayor2.aspx b/Contabilidad/LibroMayor2.aspx index 176e9ab44..d0525b61d 100644 --- a/Contabilidad/LibroMayor2.aspx +++ b/Contabilidad/LibroMayor2.aspx @@ -23,13 +23,21 @@ + + +
  • + Generar EXCEL +
  • +
    + + + +
    -
  • - Generar EXCEL -
  • -
  • + + <%--
  • Imprimir -
  • + --%>
    @@ -143,13 +151,16 @@ + +
    + @@ -164,15 +175,19 @@ - +
    CuentaConcepto Referencia Referencia MovtoSubProyectoSubProyecto Cargos Abonos Saldo
    +
    + + + + +
    @@ -187,6 +202,7 @@
    @@ -222,6 +238,7 @@
    @@ -229,6 +246,9 @@
    + + +
    @@ -239,8 +259,7 @@
    - + + diff --git a/Contabilidad/LibroMayor2.aspx.vb b/Contabilidad/LibroMayor2.aspx.vb index 800fb365f..5cc1c9ffe 100644 --- a/Contabilidad/LibroMayor2.aspx.vb +++ b/Contabilidad/LibroMayor2.aspx.vb @@ -2,8 +2,12 @@ Option Strict On Imports System.Data +Imports ADServerControl.DragableList +Imports System.IO Imports Extensiones Imports Microsoft.Reporting.WebForms +Imports ClosedXML.Excel +Imports System.Drawing Partial Class Conta_LibroMayor2 Inherits ClsPaginas @@ -12,7 +16,11 @@ Partial Class Conta_LibroMayor2 #Region "PROPIEDADES" Private Property DtDatos As DataTable Get - DtDatos = DirectCast(ViewState("DtDatos"), DataTable) + If ViewState("DtDatos") Is Nothing Then + ViewState("DtDatos") = New DataTable + End If + + Return DirectCast(ViewState("DtDatos"), DataTable) End Get Set(ByVal value As DataTable) @@ -82,14 +90,12 @@ Partial Class Conta_LibroMayor2 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Page.IsPostBack Then - 'If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.CveEmpresa <> 119 Then - ' Response.Redirect($"/Contabilidad/RepMovimientosAuxiliaresCatalogo.aspx") - 'End If + Dim ErrorParametros As Boolean = True CargaTipoCuentas() - 'TxtCuenta.Enabled = False + txtFechaI.Text = NowADS().FirstDayOfMonth.ToShortDateString txtFechaF.Text = NowADS().LastDayOfMonth.ToShortDateString @@ -109,7 +115,7 @@ Partial Class Conta_LibroMayor2 txtFechaI.Text = FechaInicio.ToShortDateString Else FechaInicio = DateSerial(Year(FechaFin), Month(FechaFin), 1) - TxtFechaF.Text = FechaInicio.ToShortDateString + txtFechaF.Text = FechaInicio.ToShortDateString End If If Request("CveProyecto") IsNot Nothing AndAlso IsNumeric(Request("CveProyecto")) Then @@ -126,20 +132,9 @@ Partial Class Conta_LibroMayor2 If Request("TP") IsNot Nothing AndAlso IsNumeric(Request("TP")) AndAlso Request("TP").ToEntero > 0 Then TipoReporte = Request("TP").ToString - ' DdlTipoReporte.SelectedValue = TipoReporte.ToString End If - ''If DdlTipoCuentas.Items.FindByValue(IdCuenta.ToString) IsNot Nothing Then - '' DdlTipoCuentas.SelectedValue = IdCuenta.ToString - ''Else - '' DdlTipoCuentas.SelectedValue = "-2" - '' TxtCuenta.Enabled = True - - '' If DTCuentas.FiltraParametros(String.Format("Cvecuenta = {0}", IdCuenta)).Rows.Count > 0 Then - '' TxtCuenta.Text = DTCuentas.FiltraParametros(String.Format("CveCuenta = {0}", IdCuenta)).Rows(0)("Codigo").ToString - '' End If - ''End If End If End If @@ -163,23 +158,11 @@ Partial Class Conta_LibroMayor2 CargaDatos() End If - ' Imprimir_click(sender, e) - 'RegistraScript("Enable();") + End Sub #Region "C A R G A - D A T O S" - Public Function WSCuentas() As String - Dim Str As New StringBuilder - Dim i As Integer = 0 - Dim dt As DataTable = DTCuentas - For Each dr As DataRow In dt.Rows - i += 1 - Str.AppendFormat("{{value:""{0}"",label:""{1}""}}{2}", dr("CveCuenta"), dr("Codigo").ToString.Replace("""", ""), If(i < dt.Rows.Count, ",", "")) - Next - - Return Str.ToString - End Function Private Sub CargaTipoCuentas() Dim ObjTipoCuenta As New ClsContabilidad @@ -200,15 +183,11 @@ Partial Class Conta_LibroMayor2 Protected Sub DdlProyecto_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlProyecto.SelectedIndexChanged CargarSubProyecto(DdlSubproyecto, DdlProyecto.SelectedValue, "Todos") End Sub - Private Sub CargaDatos() + Private Sub CargaDatos(Optional RenderGv As Boolean = True) Dim CveProyecto As Integer = DdlProyecto.SelectedValue.ToEntero Dim CveSubProyecto As Integer = DdlSubproyecto.SelectedValue.ToEntero TipoReporte = DdlTipoReporte.SelectedValue.ToString - 'If TipoReporte = "1" And DdlCuentas.SelectedValue.ToEntero < 0 Then - ' Alert("No ha seleccionado cuenta, Favor de especificar una", TipoMensaje.MsgAdvertencia) - ' Exit Sub - 'End If Cuenta = DdlCuentas.SelectedItem.ToString Dim ObjConta As New ClsContabilidad @@ -216,7 +195,10 @@ Partial Class Conta_LibroMayor2 DtDatos = ObjConta.DtResultados DtTotales = DtDatos.Clone - CargaGrid() + If RenderGv Then + CargaGrid() + End If + Else DtDatos = Nothing End If @@ -287,6 +269,11 @@ Partial Class Conta_LibroMayor2 UpDatos.Update() End Sub Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) + + If e.Row.RowType = DataControlRowType.Header Then + e.Row.FCLabel("LblSubProyecto").Text = LblSubProyecto.Text + End If + If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("Concepto") = "" Then @@ -378,7 +365,7 @@ Partial Class Conta_LibroMayor2 #End Region - Protected Sub Imprimir_click(sender As Object, e As EventArgs) Handles Imprimir.Click + Protected Sub Imprimir_click(sender As Object, e As EventArgs) If DdlCuentas.SelectedValue.ToEntero = -1 Then Alert("El campo Cuenta es obligatorio.", TipoMensaje.MsgError) Else @@ -392,62 +379,365 @@ Partial Class Conta_LibroMayor2 Protected Sub ImgExcel_Click(sender As Object, e As EventArgs) Handles ImgExcel.Click ImprimirReporte("Excel") - - 'Dim htmlTabe As New HtmlTable - 'Dim RutaLogo As String = $"{UsuarioActual.Empresa.Ruta}Logo.png" - 'Dim strinLiteral As String = "" - - 'Dim EncabezadoLiteral As New LiteralControl - - - - 'If System.IO.File.Exists(RutaLogo) Then - ' RutaLogo = $"http://{Request.Url.Host }/Empresas/{UsuarioActual.CveEmpresa}/Logo.png" - - ' strinLiteral = $" - ' - ' - ' - ' - ' - ' - '

    {UsuarioActual.Empresa.Empresa}
    Movimientos Auxiliares del Catálogo

    Fecha:{NowADS().ToString("dd/MM/yyyy")}
    - ' Filtros Cuenta: {DdlCuentas.SelectedItem.Text} Fecha inicio: { TxtFechaDel.Text} Fecha Fin: {TxtFechaAl.Text} - ' - '
    " - 'Else - ' strinLiteral = $" - ' - ' - ' - ' - ' - ' - '

    {UsuarioActual.Empresa.Empresa}
    Movimientos Auxiliares del Catálogo

    Fecha:{NowADS().ToString("dd/MM/yyyy")}
    - ' Filtros Cuenta: {DdlCuentas.SelectedItem.Text} Fecha inicio: { TxtFechaDel.Text} Fecha Fin: {TxtFechaAl.Text} - ' - - '
    " - 'End If - - 'EncabezadoLiteral.Text = strinLiteral - 'GvDatos.ExportToExcel($"MovimientosAuxiliares_{NowADS().ToString("yyyyMMddmmss")}", Encabezado2:=EncabezadoLiteral) - End Sub Private Sub ImprimirReporte(Optional Formato As String = "PDF") - Dim params As New List(Of ReportParameter) - params.Add(New ReportParameter("pEmp", UsuarioActual.Empresa.Empresa)) - Dim Imagen As New System.IO.FileInfo($"{UsuarioActual.Empresa.Ruta}/Logo.png") - params.Add(New ReportParameter("pImg", If(Imagen.Exists, $"file://{Imagen.FullName}", ""))) - params.Add(New ReportParameter("pFechaFin", FechaFin.ToString("dd/MM/yyyy"))) - params.Add(New ReportParameter("pFechaInicio", FechaInicio.ToString("dd/MM/yyyy"))) - params.Add(New ReportParameter("CveMoneda", "1")) - params.Add(New ReportParameter("Cuenta", Cuenta)) - ImprimirPDF("Empresas/Grales/Formatos/RepMovimientosAuxiliaresCatalogo.rdlc", DtDatos, params, "MovimientosAuxiliares", Formato) + Dim WBLibroMayor = New ClosedXML.Excel.XLWorkbook + Dim TipoReporte = DdlTipoReporte.SelectedValue.ToEntero + + FechaInicio = If(txtFechaI.Text = "" Or txtFechaI.Text = "__/__/____", NowADS(), txtFechaI.Text.ToDate) + FechaFin = If(txtFechaF.Text = "" Or txtFechaF.Text = "__/__/____", NowADS(), txtFechaF.Text.ToDate) + + DtDatos.Rows.Clear() + CargaDatos(False) + + If DtDatos.Rows.Count > 0 Then + Dim sp As String = If(DdlSubproyecto.SelectedValue.ToEntero > 0, DdlSubproyecto.SelectedItem.Text, "") + WBLibroMayor.AddWorksheet(WSDocumento(sp, DtDatos)) + WBLibroMayor.Worksheet(1).Name = $"LibroMayor" + End If + + Dim msB = New MemoryStream() + WBLibroMayor.SaveAs(msB) + + Dim BB As Byte() = msB.ToArray + msB.Dispose() + + Response.Clear() + Response.Buffer = True + Response.AddHeader("content-disposition", "attachment; filename=Balanza_" & Now.ToString("yyyyMMddhhmmss") & ".xlsx") + Response.ContentType = "application/vnd.ms-excel" + Response.BinaryWrite(BB) + + Response.End() End Sub + + + Function WSDocumento(SubProyecto As String, DtDatos As DataTable) As IXLWorksheet + + + Dim WBAnexoSalvar = New ClosedXML.Excel.XLWorkbook + Dim WBReporte = New ClosedXML.Excel.XLWorkbook() + WBReporte.Worksheets.Add("1") + + Dim WSReporte = WBReporte.Worksheet(1) + + Dim RutaLogo As String = String.Format("{0}Logo.png", UsuarioActual.Empresa.Ruta) + If File.Exists(RutaLogo) Then + + Dim imagePath As String = RutaLogo + Dim img As Bitmap = New Bitmap(imagePath) + Dim picture = WSReporte.AddPicture(img).MoveTo(WSReporte.Cell("A1")) + picture.Scale(0.5) + + End If + + Dim Tamaniofuente As Integer = 13 + Dim Range = WSReporte.Range("A1:D1") + + WSReporte.Style.Font.FontSize = 10 + WSReporte.Style.Font.FontName = "Arial Narrow" + + WSReporte.Style.Alignment.WrapText = True + + Range.Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + + WSReporte.Range("A1:J1").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A2:J2").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A3:J3").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A4:J4").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A5:J5").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + + WSReporte.Range("A1:A5").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + + WSReporte.Column(1).Width = 15 + WSReporte.Column(2).Width = 15 + WSReporte.Column(3).Width = 14 + WSReporte.Column(4).Width = 70 + WSReporte.Column(5).Width = 35 + WSReporte.Column(6).Width = 20 + WSReporte.Column(7).Width = 14 + WSReporte.Column(8).Width = 14 + WSReporte.Column(9).Width = 14 + WSReporte.Column(10).Width = 14 + + + WSReporte.Cell(1, 1).Value = UsuarioActual.Empresa.Empresa + WSReporte.Cell(2, 1).Value = $"Libro Mayor del {txtFechaI.Text} al {txtFechaF.Text}" + + If SubProyecto.Length > 0 Then + WSReporte.Cell(5, 1).Value = $"Sub Proyecto: {SubProyecto}" + WSReporte.Cell(5, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left + WSReporte.Cell(5, 1).Style.Font.Bold = True + End If + + + WSReporte.Cell(6, 1).Value = "Fecha" + WSReporte.Cell(6, 2).Value = $"Cuenta{vbCrLf}Tipo" + WSReporte.Cell(6, 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + WSReporte.Cell(6, 2).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + + WSReporte.Cell(6, 3).Value = $"Número" + WSReporte.Cell(6, 4).Value = $"Concepto" + WSReporte.Cell(6, 5).Value = $"Referencia" + WSReporte.Cell(6, 6).Value = $"Referencia Movto" + WSReporte.Cell(6, 7).Value = $"{LblSubProyecto.Text}" + WSReporte.Cell(6, 8).Value = $"Cargos" + WSReporte.Cell(6, 9).Value = $"Abonos" + WSReporte.Cell(6, 10).Value = $"Saldo" + + WSReporte.Range("A6:J6").Style.Font.Bold = True + WSReporte.Range("A6:J6").Style.Font.FontSize = 10 + WSReporte.Range("A6:J6").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + WSReporte.Range("A6:J6").Style.Border.TopBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range("A6:J6").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range("A6:J6").Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + Dim CuerrentRow As Integer = 7 + + CuerrentRow = CuerrentRow + 1 + + For Each Drow As DataRow In DtDatos.Rows + + + + If Drow("Concepto").ToString = "" Then + + + WSReporte.Range($"A{CuerrentRow }:J{CuerrentRow }").Style.Font.Bold = True + WSReporte.Range($"A{CuerrentRow }:J{CuerrentRow }").Style.Font.FontSize = FontSize.XXLarge '35 + + + If Drow("SaldoActual").ToString = "" Then + 'CType(e.Row.FindControl("tr2"), HtmlTableRow).Visible = False + 'Cuando Es Total + + WSReporte.Cell(CuerrentRow, 1).Value = Drow("Codigo").ToString + WSReporte.Cell(CuerrentRow, 4).Value = Drow("Nombre").ToString + WSReporte.Cell(CuerrentRow, 9).Value = "Saldo Inicial:" + WSReporte.Cell(CuerrentRow, 10).Value = Drow("SaldoInicial").ToString + + WSReporte.Cell(CuerrentRow, 10).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + WSReporte.Cell(CuerrentRow, 10).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + If Drow("SaldoInicial").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 10).Style.Font.FontColor = XLColor.Red + End If + + Else + 'CType(e.Row.FindControl("tr1"), HtmlTableRow).Visible = False + + WSReporte.Cell(CuerrentRow, 1).Value = Drow("Fecha").ToString + WSReporte.Cell(CuerrentRow, 2).Value = Drow("TipoPoliza").ToString + WSReporte.Cell(CuerrentRow, 3).Value = Drow("Folio").ToString + WSReporte.Cell(CuerrentRow, 4).Value = Drow("Concepto").ToString + WSReporte.Cell(CuerrentRow, 5).Value = Drow("Referencia").ToString + WSReporte.Cell(CuerrentRow, 6).Value = Drow("ReferenciaAdmin").ToString + WSReporte.Cell(CuerrentRow, 7).Value = Drow("SubProyecto").ToString + + + If TotalPadre Then + WSReporte.Cell(CuerrentRow, 5).Value = String.Format("Total {0}:", Drow("Nombre").ToString) + WSReporte.Cell(CuerrentRow, 5).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + Else + TotalPadre = True + WSReporte.Cell(CuerrentRow, 5).Style.Font.Bold = False + WSReporte.Cell(CuerrentRow, 5).Value = "Total:" + WSReporte.Cell(CuerrentRow, 5).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + End If + + WSReporte.Cell(CuerrentRow, 8).Value = Drow("Cargos").ToString.FormatoNumero(If("1" = "1", 2, 4)) + WSReporte.Cell(CuerrentRow, 9).Value = Drow("Abonos").ToString.FormatoNumero(If("1" = "1", 2, 4)) + WSReporte.Cell(CuerrentRow, 10).Value = Drow("SaldoActual").ToString.FormatoNumero(If("1" = "1", 2, 4)) + + + WSReporte.Range($"H{CuerrentRow}:J{CuerrentRow}").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + WSReporte.Range($"H{CuerrentRow}:J{CuerrentRow}").Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + + If Drow("Cargos").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 8).Style.Font.FontColor = XLColor.Red + End If + + If Drow("Abonos").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 9).Style.Font.FontColor = XLColor.Red + End If + + If Drow("SaldoActual").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 10).Style.Font.FontColor = XLColor.Red + End If + + End If + + Else + + + WSReporte.Cell(CuerrentRow, 1).Value = Drow("Fecha").ToString + WSReporte.Cell(CuerrentRow, 2).Value = Drow("TipoPoliza").ToString + WSReporte.Cell(CuerrentRow, 3).Value = Drow("Folio").ToString + WSReporte.Cell(CuerrentRow, 4).Value = Drow("Concepto").ToString + WSReporte.Cell(CuerrentRow, 5).Value = Drow("Referencia").ToString + WSReporte.Cell(CuerrentRow, 6).Value = Drow("ReferenciaAdmin").ToString + WSReporte.Cell(CuerrentRow, 7).Value = Drow("SubProyecto").ToString + + TotalPadre = False + + WSReporte.Range($"A{CuerrentRow }:J{CuerrentRow }").Style.Font.Bold = False + WSReporte.Cell(CuerrentRow, 10).Value = Drow("Folio").ToString + + WSReporte.Cell(CuerrentRow, 8).Value = Drow("CargosMovto").ToString.FormatoNumero(If("1" = "1", 2, 4)) + WSReporte.Cell(CuerrentRow, 9).Value = Drow("AbonosMovto").ToString.FormatoNumero(If("1" = "1", 2, 4)) + WSReporte.Cell(CuerrentRow, 10).Value = Drow("Saldo").ToString.FormatoNumero(If("1" = "1", 2, 4)) + + WSReporte.Range($"H{CuerrentRow}:J{CuerrentRow}").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + + WSReporte.Range($"H{CuerrentRow}:J{CuerrentRow}").Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + + If Drow("CargosMovto").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 8).Style.Font.FontColor = XLColor.Red + End If + + If Drow("AbonosMovto").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 9).Style.Font.FontColor = XLColor.Red + End If + + If Drow("Saldo").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 10).Style.Font.FontColor = XLColor.Red + End If + + End If + + CuerrentRow = CuerrentRow + 1 + Next + + + For xy As Integer = 6 To CuerrentRow + WSReporte.Cell(xy, 10).Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Cell(xy, 1).Style.Border.LeftBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + Next + + 'CuerrentRow = CuerrentRow + 1 + + 'WSReporte.Cell(CuerrentRow, 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + 'WSReporte.Cell(CuerrentRow, 2).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + + 'WSReporte.Cell(CuerrentRow, 3).Value = $"Saldos Iniciales{vbCrLf}Deudor Acreedor" + 'WSReporte.Cell(CuerrentRow, 4).Value = $"Cargos" + 'WSReporte.Cell(CuerrentRow, 5).Value = $"Abonos" + 'WSReporte.Cell(CuerrentRow, 6).Value = $"Saldo Actuales{vbCrLf} Deudor Acreedo" + + + + WSReporte.Range($"A{CuerrentRow}:J{CuerrentRow}").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + + + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Font.Bold = True + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Font.FontSize = 10 + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.TopBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + 'CuerrentRow = CuerrentRow + 1 + + 'Dim ultimaFila As DataRow = DtDatos.Rows(DtDatos.Rows.Count - 1) + + 'Dim LastSaldoID As Decimal = ultimaFila("SaldoID").ToString.ToDecimal + 'Dim LastTotalAbonos As Decimal = ultimaFila("TotalAbonos").ToString.ToDecimal + 'Dim LastTotalCargos As Decimal = ultimaFila("TotalCargos").ToString.ToDecimal + 'Dim LastSaldoAD As Decimal = ultimaFila("SaldoAD").ToString.ToDecimal + 'Dim LastSaldoIA As Decimal = ultimaFila("SaldoIA").ToString.ToDecimal + 'Dim LastSaldoAA As Decimal = ultimaFila("SaldoAA").ToString.ToDecimal + + 'WSReporte.Cell(CuerrentRow, 2).Value = "Sumas Iguales" + 'WSReporte.Cell(CuerrentRow, 3).Value = LastSaldoID + 'WSReporte.Cell(CuerrentRow, 4).Value = LastTotalCargos + 'WSReporte.Cell(CuerrentRow, 5).Value = LastTotalAbonos + 'WSReporte.Cell(CuerrentRow, 6).Value = LastSaldoAD + + 'WSReporte.Cell(CuerrentRow, 3).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + 'WSReporte.Cell(CuerrentRow, 4).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + 'WSReporte.Cell(CuerrentRow, 5).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + 'WSReporte.Cell(CuerrentRow, 6).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + + CuerrentRow = CuerrentRow + 1 + + 'WSReporte.Cell(CuerrentRow, 3).Value = LastSaldoIA + 'WSReporte.Cell(CuerrentRow, 6).Value = LastSaldoAA + + + 'WSReporte.Cell(CuerrentRow, 3).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + 'WSReporte.Cell(CuerrentRow, 6).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + 'WSReporte.Range($"B{CuerrentRow}:F{CuerrentRow}").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + WSReporte.PageSetup.PrintAreas.Add($"A1:G{CuerrentRow + 0 + 1}") + WSReporte.PageSetup.Margins.Top = 0.3 + WSReporte.PageSetup.Margins.Left = 0.8 + WSReporte.PageSetup.Margins.Right = 0.8 + WSReporte.PageSetup.FitToPages(1, 1) + + WBReporte.Worksheet(1).CopyTo(WBAnexoSalvar, "LibroMayor") + + Return WBReporte.Worksheet(1) + + End Function + + + + Public Function CloneGridView(ByVal originalGridView As GridView) As GridView + ' Crear un nuevo GridView + Dim clonedGridView As New GridView() + + ' Copiar propiedades básicas del GridView + clonedGridView.ID = originalGridView.ID & "_Copy" + clonedGridView.AutoGenerateColumns = originalGridView.AutoGenerateColumns + clonedGridView.CssClass = originalGridView.CssClass + clonedGridView.GridLines = originalGridView.GridLines + clonedGridView.HeaderStyle.CopyFrom(originalGridView.HeaderStyle) + clonedGridView.RowStyle.CopyFrom(originalGridView.RowStyle) + clonedGridView.AlternatingRowStyle.CopyFrom(originalGridView.AlternatingRowStyle) + clonedGridView.FooterStyle.CopyFrom(originalGridView.FooterStyle) + clonedGridView.EmptyDataText = originalGridView.EmptyDataText + clonedGridView.ShowHeader = originalGridView.ShowHeader + clonedGridView.ShowFooter = originalGridView.ShowFooter + + ' Copiar columnas + For Each col As DataControlField In originalGridView.Columns + ' Crear una copia de la columna + Dim clonedCol As DataControlField = CType(Activator.CreateInstance(col.GetType()), DataControlField) + clonedCol.HeaderStyle.CopyFrom(col.HeaderStyle) + clonedCol.ItemStyle.CopyFrom(col.ItemStyle) + clonedCol.FooterStyle.CopyFrom(col.FooterStyle) + + ' Si es un BoundField, copiar propiedades específicas + If TypeOf col Is BoundField Then + Dim originalBoundField As BoundField = CType(col, BoundField) + Dim clonedBoundField As BoundField = CType(clonedCol, BoundField) + + clonedBoundField.DataField = originalBoundField.DataField + clonedBoundField.HeaderText = originalBoundField.HeaderText + clonedBoundField.SortExpression = originalBoundField.SortExpression + clonedBoundField.ReadOnly = originalBoundField.ReadOnly + End If + + ' Añadir la columna clonada al nuevo GridView + clonedGridView.Columns.Add(clonedCol) + Next + + ' Copiar el DataSource (opcional, dependiendo de si deseas copiar los datos actuales) + clonedGridView.DataSource = originalGridView.DataSource + clonedGridView.DataBind() + + Return clonedGridView + End Function + + Public Overrides Sub VerifyRenderingInServerForm(control As Control) End Sub diff --git a/Contabilidad/RepBalanzaComprobacion.aspx b/Contabilidad/RepBalanzaComprobacion.aspx index 703e6c717..ac8bff60e 100644 --- a/Contabilidad/RepBalanzaComprobacion.aspx +++ b/Contabilidad/RepBalanzaComprobacion.aspx @@ -3,16 +3,22 @@
  • - Exporta Excel + Exporta Excel <%--   --%>
  • +
  • + + Exportar por + +
    + +
    +
  • Imprimir <%--  --%>
  • -
  • - Imprimir por Sub Proyecto -
  • +
    @@ -218,3 +224,63 @@ + + + + + \ No newline at end of file diff --git a/Contabilidad/RepBalanzaComprobacion.aspx.vb b/Contabilidad/RepBalanzaComprobacion.aspx.vb index d8ca1cafc..f8e63ff9c 100644 --- a/Contabilidad/RepBalanzaComprobacion.aspx.vb +++ b/Contabilidad/RepBalanzaComprobacion.aspx.vb @@ -9,6 +9,7 @@ Imports ClosedXML.Excel Imports Profact.TimbraCFDI40 Imports System.IO Imports System.Drawing +Imports System.Web.Services @@ -111,9 +112,7 @@ Partial Class Contabilidad2_RepBalanzaComprobacion End If CargarCentrosDeCosto(DdlProyecto, DdlSubproyecto, LblProyecto, LblSubProyecto) - If UsuarioActual.CveRol = 1 Then - BtnImprimirPoSubProyecto.Visible = True - End If + LblAccionesSubProyecto.Text = LblSubProyecto.Text End If End Sub @@ -265,52 +264,11 @@ Partial Class Contabilidad2_RepBalanzaComprobacion End Sub - Protected Sub BtnImprimirPoSubProyecto_Click(sender As Object, e As EventArgs) - - Dim WBAnexoBalanza = New ClosedXML.Excel.XLWorkbook - Dim TipoReporte = DdlTipoReporte.SelectedValue.ToEntero - - FechaInicio = If(TxtFechaDel.Text = "" Or TxtFechaDel.Text = "__/__/____", NowADS(), TxtFechaDel.Text.ToDate) - FechaFin = If(TxtFechaAl.Text = "" Or TxtFechaAl.Text = "__/__/____", NowADS(), TxtFechaAl.Text.ToDate) - - Dim SPCounter As Integer = 1 - For Each drSP As DataRow In GlobalDTSubProyectos(UsuarioActual.CveEmpresa).Rows - - Dim ObjConta As New ClsContabilidad - If ObjConta.GetBalanzaComprobacion(FechaInicio, FechaFin, 2, TipoReporte, -1, drSP("CveSubProyecto").ToString.ToEntero, UsuarioActual.CveEmpresa, DdlVista.SelectedValue.ToEntero, DdlNivel.SelectedValue.ToEntero) Then - DtDatos = ObjConta.DtResultados - Else - DtDatos = Nothing - Alert("Ocurrio un error al cargar los datos del Anexo del Catálogo", TipoMensaje.MsgError) - Exit For - End If - ObjConta.Dispose() - - If DtDatos.Rows.Count > 0 Then - WBAnexoBalanza.AddWorksheet(WSDocumento(drSP("SubProyecto").ToString, DtDatos)) - Dim spNombre As String = drSP("SubProyecto").ToString().Replace(":", "_").Replace("/", "_").Replace("\", "_").Replace("?", "_").Replace("*", "_").Replace("[", "_").Replace("]", "_") - WBAnexoBalanza.Worksheet(SPCounter).Name = $"{SPCounter}_{spNombre}" - SPCounter = SPCounter + 1 - - End If + 'Protected Sub BtnImprimirPoSubProyecto_Click(sender As Object, e As EventArgs) - Next - Dim msB = New MemoryStream() - WBAnexoBalanza.SaveAs(msB) - - Dim BB As Byte() = msB.ToArray - msB.Dispose() - - Response.Clear() - Response.Buffer = True - Response.AddHeader("content-disposition", "attachment; filename=Balanza_" & Now.ToString("yyyyMMddhhmmss") & ".xlsx") - Response.ContentType = "application/vnd.ms-excel" - Response.BinaryWrite(BB) - Response.End() - - End Sub + 'End Sub Function WSDocumento(SubProyecto As String, DtDatos As DataTable) As IXLWorksheet @@ -498,4 +456,59 @@ Partial Class Contabilidad2_RepBalanzaComprobacion End Function + + Protected Sub BtnImprimirPorsubProyecto_Click(sender As Object, e As EventArgs) + Dim WBAnexoBalanza = New ClosedXML.Excel.XLWorkbook + 'Dim TipoReporte = DdlTipoReporte.SelectedValue.ToEntero + + FechaInicio = If(TxtFechaDel.Text = "" Or TxtFechaDel.Text = "__/__/____", NowADS(), TxtFechaDel.Text.ToDate) + FechaFin = If(TxtFechaAl.Text = "" Or TxtFechaAl.Text = "__/__/____", NowADS(), TxtFechaAl.Text.ToDate) + + Dim SPCounter As Integer = 1 + Dim DtSP As DataTable = GlobalDTSubProyectos(UsuarioActual.CveEmpresa, Estatus:=-1).FiltraParametros("", "SubProyecto") + For Each drSP As DataRow In DtSP.Rows + + Dim ObjConta As New ClsContabilidad + If ObjConta.GetBalanzaComprobacion(FechaInicio, FechaFin, 1, 1, -1, drSP("CveSubProyecto").ToString.ToEntero, UsuarioActual.CveEmpresa, 0, -1) Then + DtDatos = ObjConta.DtResultados + Else + DtDatos = Nothing + Alert("Ocurrio un error al cargar los datos del Anexo del Catálogo", TipoMensaje.MsgError) + Exit For + End If + ObjConta.Dispose() + + If DtDatos.Rows.Count > 0 Then + WBAnexoBalanza.AddWorksheet(WSDocumento(drSP("SubProyecto").ToString, DtDatos)) + Dim spNombre As String = drSP("SubProyecto").ToString().Replace(":", "_").Replace("/", "_").Replace("\", "_").Replace("?", "_").Replace("*", "_").Replace("[", "_").Replace("]", "_") + WBAnexoBalanza.Worksheet(SPCounter).Name = $"{SPCounter}_{spNombre}" + SPCounter = SPCounter + 1 + + End If + + + Next + + Dim msB = New MemoryStream() + WBAnexoBalanza.SaveAs(msB) + + Dim BB As Byte() = msB.ToArray + msB.Dispose() + + Response.Clear() + Response.Buffer = True + Response.AddHeader("content-disposition", "attachment; filename=Balanza_" & Now.ToString("yyyyMMddhhmmss") & ".xlsx") + Response.ContentType = "application/vnd.ms-excel" + Response.BinaryWrite(BB) + 'Response.Write("Ready") + + Response.End() + End Sub + + + Public Shared Function MyStaticFunction(ByVal parameter As String) As String + ' Lógica de tu función aquí + Return "Resultado: " & parameter + End Function + End Class diff --git a/Empresas/Grales/Formatos/Traslado.rdlc b/Empresas/Grales/Formatos/Traslado.rdlc index ebc88a24d..891ee3351 100644 --- a/Empresas/Grales/Formatos/Traslado.rdlc +++ b/Empresas/Grales/Formatos/Traslado.rdlc @@ -72,16 +72,16 @@ - 1.94437cm + 1.09771cm 3.27787cm - 2.19837cm + 1.5514cm - 9.27592cm + 10.76955cm 1.41521cm @@ -187,7 +187,7 @@ - Unidad Medida + U.M. @@ -503,7 +503,7 @@ @@ -537,7 +537,7 @@ @@ -552,6 +552,7 @@ =IIf(rownumber(nothing) = 1, "2pt", "0pt") + true diff --git a/Inventarios/EntradasSalidas.aspx b/Inventarios/EntradasSalidas.aspx index 4788c2718..0aa50ae21 100644 --- a/Inventarios/EntradasSalidas.aspx +++ b/Inventarios/EntradasSalidas.aspx @@ -1673,11 +1673,14 @@ + + - + +
    @@ -1982,8 +1985,8 @@ - function ValidaDecimal6digitsM0(val, args) { - if (args.Value.match(/^[1-9]\d*(\.\d{1,6})?$/)) + function ValidaDecimal6digitsM0(val, args) { + if (args.Value.match(/^(0|[1-9]\d*)(\.\d{1,6})?$/)) args.IsValid = true; else args.IsValid = false; diff --git a/Transportes/RepContratos.aspx b/Transportes/RepContratos.aspx index f35f0f535..c1cc27917 100644 --- a/Transportes/RepContratos.aspx +++ b/Transportes/RepContratos.aspx @@ -284,9 +284,12 @@
    - - + + + <%--
    - ', + $('#calendar').fullCalendar('destroy'); + $('#calendar').fullCalendar({ + defaultDate: fechaInicio, + header: h, + monthNames: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"], + monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'], + dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'], + dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'], + buttonText: { + today: 'Hoy', + week: 'Semana', + month: 'Mes', + day: 'Día' + }, + eventClick: updateEvent, + selectable: true, + selectHelper: true, + select: selectDate, + editable: true, + minTime: "00:00:00", + maxTime: "24:00:00", + eventOverlap: false, // No permitir la superposición de eventos + slotEventOverlap: false, // No permitir la superposición en vistas de agenda + eventRender: function (event, element) { + element.css({ + 'margin-bottom': '1px', + 'margin-left': '1px', + 'white-space': 'normal', // Permitir el ajuste de texto + 'height': 'auto', // Ajustar la altura automáticamente + 'overflow': 'hidden' // Ocultar cualquier desbordamiento + }); + element.find('.fc-title').css({ + 'white-space': 'normal', // Asegurar que el texto se ajuste + 'line-height': '1.2em' // Ajustar la altura de línea para mejor legibilidad + }); + + var firstFourChars = event.title.substring(0, 4); + var restOfTitle = event.title.substring(4); + + // Aplica el HTML personalizado al elemento del título del evento + //element.find('.fc-title').html('' + firstFourChars + '' + restOfTitle); + }, + events: { + url: '/Ashx/CargaEventos.ashx', + type: 'GET', + data: { + U: ' <%= UsuarioActual.CveUsuario %>', E: '<%= UsuarioActual.CveEmpresa %>', tipoVista: '<%= RBTipoVista.Text %>', METODO: 'contrato_transportes', @@ -1023,15 +1029,16 @@ }, eventDrop: eventDropped, eventResize: eventResized, - viewRender: function(view, element) { - + viewRender: function (view, element) { + let pointDate = view.intervalStart; - let currentMonth = pointDate.month() + 1; + let currentMonth = pointDate.month() + 1; let currentYear = pointDate.year(); $('#<%=HidCurrentMonth.ClientID%>').val(currentMonth); $('#<%=HidCurrentYear.ClientID%>').val(currentYear); } + }); }