jueves, 8 de octubre de 2020

Como ordenar los resultados de una consulta 1,2,5,6,3,4 con ORDER BY SQL SERVER. Otra forma de ordernar forzando los resultados con ORDER BY

 Se crea una tabla con dos campos donde el primero tenga el mismo orden de la consulta que quieres ordenar, y el segundo campo lo colocamos con el orden deseado

ejemplo: Script

necesitamos ordenar un resultado de la forma siguiente:

1,2,3,4,5,6,7,8,10,11,12,9

con el nueve al final de todo.

pasos 1

creamos la tabla que va forzar el orden


CREATE  TABLE ORDENADOR_EQUIVALENTE

(numero VARCHAR(10), 

 valor VARCHAR(10)

 )


insertamos los datos:


campo número esta ordenado y tiene los mismo de la consulta.

campo valor esta ordenado como vos queres y con letras.


 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '01','a')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '02','b')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '03','c')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '04','d')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '05','e')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '06','f')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '07','g')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '08','h')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '09','l')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '10','i')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '11','j')

 INSERT INTO ORDENADOR_EQUIVALENTE  VALUES( '12','k')

solo debemos relacionarla en el lugar presiso y que sea el campo numero el que se relacione 

ej.

 INNER JOIN ORDENADOR_EQUIVALENTE OE ON OE.numero = MAESTRA.IDESTADOHDR


y el campo valor el que ordene en la clausu: 

ej.

ORDER BY OE.valor ASC,HIS.TS desc

listo.




viernes, 18 de septiembre de 2020

crear tabla temporal y asignacion de registros / insertar registros desde una consulta SQL SERVER / insert records from a SQL SERVER query

 


----CREAMOS LA TABLA TEMPORAL

-- CREATE TABLE #temporal( IdPedidoDetalle BIGINT,IdPedido  bigint,IdArt  bigint,IdColor  bigint ,IdTalle  bigint,Cantidad  int,Precio  int,Ts  datetime)

-- INSERT INTO #temporal 

--SELECT IdPedidoDetalle, IdPedido, IdArt, IdColor, IdTalle, Cantidad, Precio, Ts FROM RDSAWSSQL.CATALOGO.dbo.SIGMA_CATALOGO_PEDIDO_DETALLES  AS scpd WITH (NOLOCK) WHERE SCPD.ts  BETWEEN @FDESDE AND @FHASTA

--------------------------------

--CREATE TABLE #temporal_cambio (IdPedidoDetalleCambio BIGINT,IdPedido  bigint,IdArt  bigint,IdColor  bigint ,IdTalle  bigint,Cantidad  int,Ts  datetime)

-- INSERT INTO #temporal_cambio 

--SELECT IdPedidoDetalleCambio,IdPedido,IdArt,IdColor,IdTalle,Cantidad,Ts FROM RDSAWSSQL.CATALOGO.dbo.SIGMA_CATALOGO_PEDIDO_DETALLES_CAMBIOS AS d WITH (NOLOCK) WHERE ts > @fdesde  

------

--CREATE TABLE #TEMPORAL_CABECERA

--       ( IdPedido bigint ,IdCliente  bigint ,IdToken  int,IdEstado  int,TipoCompra  varchar(100),QuienRetira  varchar(400),QuienRecibe varchar(400),Observaciones  varchar(400),CodigoEnvio  varchar(500),FechaAlta  datetime

--          ,Ts  datetime,NroFactura  varchar(200),Operacion  varchar(200),ObservacionesVendedor  varchar(max),EsResolucion  int,IdDireccion  bigint)

--INSERT into #TEMPORAL_CABECERA 

--SELECT IdPedido,IdCliente,IdToken,IdEstado,TipoCompra,QuienRetira,QuienRecibe,Observaciones,CodigoEnvio,FechaAlta,Ts,NroFactura,Operacion,ObservacionesVendedor,EsResolucion,IdDireccion

-- FROM RDSAWSSQL.CATALOGO.dbo.SIGMA_CATALOGO_PEDIDOS_CABECERA AS cb WITH (NOLOCK) WHERE cb.ts >  @FDESDE

-------

--CREATE TABLE #TEMPORAL_PEDIDO_HISTORICO (IdHistorial bigint,IdPedido  bigint,IdEstado  int,IdUsuario  int,Ts  datetime)

--INSERT INTO #TEMPORAL_PEDIDO_HISTORICO        

--SELECT IdHistorial,IdPedido,IdEstado,IdUsuario,Ts FROM  RDSAWSSQL.CATALOGO.dbo.SIGMA_CATALOGO_PEDIDOS_ESTADOS_HISTORIAL AS D WHERE D.TS > '20200801'

------

viernes, 21 de agosto de 2020

Class Principal Gestion de Devolucion

 Public Class Principal

#Region "Declaraciones"

    Private LABASE As String

    Private SERVIDOR As String

    Private mDtResultado As New DataTable

    Private ConeccionExitosa As Boolean

    Private ResuBoolean As Boolean = False

    Private LogueoExitoso As Boolean

    Private AvisarAlSalir As Boolean

    Private sUsuario As String

    Private FrmGestiondeDevolucion As GestiondeDevolucion

    Private FrmAuditoria As AuditoriaCorreos

#End Region


#Region "Eventos"


    Private Sub Principal_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Try

            IniciarAplicacion()

            OperacionesControles()

        Catch ex As Exception

            GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Errores, "#ERROR: al intentar abrir la aplicación. " & vbCrLf & ex.Message.ToString).ShowDialog()

        End Try

    End Sub

#End Region


#Region "Funciones"


    Private Sub OperacionesControles()

        RegistroControles()

        EjecutarPermisos()

    End Sub

    Private Sub RegistroControles()

        ControlesPermisos.RegistrarControles(Me)

    End Sub


    Private Sub EjecutarPermisos()

        ControlesPermisos.DesactivarControlesAplicacion(Me)

        ControlesPermisos.ActivarControlesPorPefil(Me, My.Application.IDAPLICACION, My.Application.IDPERFIL)

        ControlesPermisos.ActivarControlesPorUsuario(Me, My.Application.IDAPLICACION, My.Application.IDUSUARIO)

    End Sub


    Private Sub IniciarAplicacion()

        InfoUsuario()

        InfoBD()

        ValidarVersiones(My.Application.IDAPLICACION)

        If ConectarUsuarioAAplicacionSinSeguridad(My.Application.IDUSUARIO, My.Application.IDAPLICACION, My.Computer.Name.ToString, My.Application.Info.Version.ToString) = False Then

            Me.Close()

        Else

            LogueoExitoso = True

        End If



    End Sub

    Private Function ConectarUsuarioAAplicacionSinSeguridad(ByVal unUsuario As Integer, ByVal unaAplicacion As Integer, ByVal unaPC As String,

                                         ByVal unaVersion As String) As Boolean

        mDtResultado = New DataTable

        ResuBoolean = False

        mDtResultado = AccesoBase.SetSP("SP_HERRAMIENTAS_SIGMA_CONECTAR_USUARIO_A_APLICACION_SIN_BLOQUEO").SetParam(unUsuario, unaAplicacion, unaPC, unaVersion)

        If mDtResultado IsNot Nothing Then

            ' 1 - INSERTO CORRECTAMENTE

            '-1 - FALLO EL INSERT

            ' 2 - HIZO EL UPDATE DEL ESTADO CORRECTAMENTE

            '-2 - FALLO EL UPDATE DEL ESTADO 

            Select Case mDtResultado.Rows(0).Item(0)

                Case 1

                    ResuBoolean = True

                Case -1

                    GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Errores, "Falló el ingreso del dato en la tabla 'HERRAMIENTAS_SIGMA_USUARIOS_CONECTADOS'").ShowDialog()

                Case 2

                    ResuBoolean = True

                Case -2

                    GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Errores, "Falló la actualización del dato en la tabla 'HERRAMIENTAS_SIGMA_USUARIOS_CONECTADOS'").ShowDialog()

            End Select

        Else

            ResuBoolean = False

        End If


        Return ResuBoolean

    End Function

    Private Sub ValidarVersiones(ByVal unIdAplicacion As Integer)

        Try

            mDtResultado = New DataTable

            mDtResultado = AccesoBase.SetSP("SP_MAESTRO_VERSIONES_LEER").SetParam(unIdAplicacion)

            If mDtResultado IsNot Nothing Then

                If mDtResultado.Rows(0).Item("VERSIONACTUAL") = My.Application.Info.Version.ToString Then

                    'Ok tiene la version actual

                Else

                    If mDtResultado.Rows(0).Item("VERSIONANTERIOR") = My.Application.Info.Version.ToString Then

                        'Tiene la versión anterior

                        If mDtResultado.Rows(0).Item("URGENTE") = 0 Then

                            'No es urgente

                        Else

                            'La actualización debe ser inmediatamente

                            GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Adveretencia, "Su versión está desactualizada, por favor salga del Sigma y vuelva a ingresar.").ShowDialog()


                            Application.ExitThread()

                        End If

                    Else

                        'Tiene una versión no registrada - mail a sistemas


                        'EnviarMail("desarrollo@mimo.com.ar", "Sigma - Versión no registrada", "URGENTE. La computadora " & My.Computer.Name & " (usuario " & My.Application.IDUSUARIO & ") posee una versión no registrada de la aplicación: " & My.Application.Info.AssemblyName & " (" & VVidaplic & "). version: " & My.Application.Info.Version.ToString)


                        GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Adveretencia, "Su versión no está registrada. Envío de email automático a Sistemas.").ShowDialog()

                        Application.ExitThread()

                    End If

                End If

            Else

                GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Adveretencia, "Ocurrio un error al validar la versión, se cerrará la aplicación. ").ShowDialog()

                Application.ExitThread()

            End If

        Catch ex As Exception

            GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Adveretencia, "Ocurrio un error al validar la versión, se cerrará la aplicación. " & vbCrLf & ex.Message.ToString).ShowDialog()

            Application.ExitThread()

        End Try

    End Sub

    Public Sub InfoBD()


        If AccesoBase.ObtenerBase <> "SIGMA" Then

            LABASE = " | Base: " & UCase(AccesoBase.ObtenerBase)

            SERVIDOR = " | Servidor: " & IIf(UCase(AccesoBase.ObtenerServidor) = "SR01SIG01" Or UCase(AccesoBase.ObtenerServidor) = "192.168.1.20", "PRODUCCIÓN", "TESTING")

        Else

            LABASE = ""

            'SERVIDOR = " | Servidor: " & UCase(objRemRN.ppServidor)

            SERVIDOR = " | Servidor: " & IIf(UCase(AccesoBase.ObtenerServidor) = "SR01SIG01" Or UCase(AccesoBase.ObtenerServidor) = "192.168.1.20", "PRODUCCIÓN", "TESTING")

        End If


        Me.Text = Me.Text & SERVIDOR & LABASE & " | Versión  " & My.Application.Info.Version.ToString


        ''Cargo la infro al supertip

        'Dim sTooltip2 As SuperToolTip = New SuperToolTip

        'Dim args As SuperToolTipSetupArgs = New SuperToolTipSetupArgs

        'args.Title.Text = "Mensaje del sistema"

        'args.Contents.Text = "Usted se encuentra en: " & vbCrLf & SERVIDOR & LABASE & vbCrLf & " | Versión  " & My.Application.Info.Version.ToString

        'args.Contents.Image = My.Resources.database_32x32

        ''args.Footer.Text = "Equipo de sistemas"

        'sTooltip2.Setup(args)


        '' Assign the created SuperToolTip to a BarItem.

        ''BarStaticItem_BASE.SuperTip = sTooltip2

    End Sub


    Private Sub InfoUsuario()

        sUsuario = ObtenerUsuarioLogueado(My.Application.IDUSUARIO)


    End Sub


    Private Function ObtenerUsuarioLogueado(ByVal idUsuario As Integer) As String

        mDtResultado = New DataTable

        mDtResultado = AccesoBase.SetSP("SP_ECOMMERCE_DEVOLUCION_OBTENER_USUARIO_LOGUEADO").SetParam(idUsuario)

        If mDtResultado IsNot Nothing Then

            Return mDtResultado.Rows(0).Item(0)

        Else

            Return Nothing

        End If

    End Function


    Private Sub BBI_Devoluciones_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BBI_Devoluciones.ItemClick

        Try


            FrmGestiondeDevolucion = New GestiondeDevolucion

            FrmGestiondeDevolucion.Show()

        Catch ex As Exception

            GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Errores, "#ERROR: al intentar abrir 'Gestión de Devolucion'." & vbCrLf & ex.Message.ToString).ShowDialog()

        End Try

    End Sub


    Private Sub BBI_AuditoriaCorreo_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BBI_AuditoriaCorreo.ItemClick

        Try


            FrmAuditoria = New AuditoriaCorreos

            FrmAuditoria.Show()

        Catch ex As Exception

            GestorMensajes.MensajeDelSistema(MensajeSistema.TipoDeMensaje.Errores, "#ERROR: al intentar abrir 'Gestión Auditoria de Correos'." & vbCrLf & ex.Message.ToString).ShowDialog()

        End Try

    End Sub


#End Region


End Class

lunes, 3 de agosto de 2020

ControlesPermisos MENU ITEM


Public Class ControlesPermisos
#Region "DECLARACION"

    Private Shared Menu As System.Windows.Forms.ToolStripMenuItem
    Private Shared SubMenu As System.Windows.Forms.ToolStripDropDownItem
    Private Shared submenu_ As System.Windows.Forms.ToolStripItem
    Public Shared mDtListadoControles = New DataTable
    Private Shared objPedidosRN = New VMPedidosRN.PedidosRN

#End Region

#Region "FUNCIONES"


    Public Shared Sub RegistrarControles(ByRef unform As Form) ' esta registra los controles de la aplicacion seguridad plues nada mas
        Dim nombreControl As String
        Dim descripcionControl As String = "testing-Seguridad"
        Dim descripcionControlRibbon As String = "testing-Ribbon"
        Try
            objPedidosRN = New VMPedidosRN.PedidosRN
            objPedidosRN.InicializarBase()

            'objAdmVentas_RN = New AdmVentas_RN.AdmVentas_RN
            'objAdmVentas_RN.InicializarBase()
            'Solapas = New DevExpress.XtraBars.Ribbon.RibbonPage
            'Grupo = New DevExpress.XtraBars.Ribbon.RibbonPageGroup
            'Category = New DevExpress.XtraBars.Ribbon.RibbonPageCategory
            'Dim sol As String = Category.Name

            Dim Ctrl As Control
            For i As Integer = 0 To unform.Controls.Count - 1
                Ctrl = unform.Controls.Item(i)
                If Ctrl.Name <> "" Then
                    If TypeOf (Ctrl) Is System.Windows.Forms.Control Then 'TypeOf (Ctrl) Is System.Windows.Forms.Form Or
                        nombreControl = Ctrl.Name
                        RegistroItems(Ctrl, unform)
                    Else
                        nombreControl = Ctrl.Name
                        objPedidosRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_INGRESAR_CONTROL_POR_APLICACION(My.Application.IDAPLICACION, nombreControl, descripcionControl)
                    End If
                End If

            Next
        Catch ex As Exception
            MessageBox.Show("" + ex.ToString)
        End Try
    End Sub


    'registro automatico de los controles ingresados al menu
    Public Shared Sub RegistroItems(ByRef unControl As System.Windows.Forms.Control, ByRef unform As Form)
        Dim Menu As System.Windows.Forms.ToolStripMenuItem
        Dim SubMenu As System.Windows.Forms.ToolStripDropDownItem
        Dim submenu_ As System.Windows.Forms.ToolStripItem
        Dim I, H As Integer
        Dim NombreControl, DescripcionControl As String
        Try
            For Each Menu In unform.MainMenuStrip.Items
                NombreControl = Menu.Name
                DescripcionControl = Menu.Text
                If DescripcionControl = "" Then
                    DescripcionControl = Menu.Name
                Else
                    DescripcionControl = Menu.Text
                End If

                objPedidosRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_INGRESAR_CONTROL_POR_APLICACION(My.Application.IDAPLICACION, NombreControl, DescripcionControl)
                For I = 0 To Menu.DropDownItems.Count - 1
                    If Menu.DropDownItems.Item(I).GetType().FullName = "System.Windows.Forms.ToolStripMenuItem" Then '---->Menu
                        SubMenu = Menu.DropDownItems.Item(I) '--->opciones del menu
                        NombreControl = SubMenu.Name
                        DescripcionControl = SubMenu.Text
                        If DescripcionControl = "" Then
                            DescripcionControl = Menu.Name + " / " + SubMenu.Name
                        Else
                            DescripcionControl = Menu.Text + " / " + SubMenu.Text
                        End If

                        objPedidosRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_INGRESAR_CONTROL_POR_APLICACION(My.Application.IDAPLICACION, NombreControl, DescripcionControl)
                        For H = 0 To SubMenu.DropDownItems.Count - 1
                            If SubMenu.DropDownItems.Item(H).GetType().FullName = "System.Windows.Forms.ToolStripMenuItem" Then '---->Menu
                                submenu_ = SubMenu.DropDownItems.Item(H) '--->opciones del menu
                                NombreControl = submenu_.Name
                                DescripcionControl = submenu_.Text
                                If DescripcionControl = "" Then
                                    DescripcionControl = Menu.Name + " / " + SubMenu.Name + " / " + submenu_.Name '"OpcMenu,Sin Definir"
                                Else
                                    DescripcionControl = Menu.Text + " / " + SubMenu.Text + " / " + submenu_.Text '"OpcMenu,Sin Definir"
                                End If
                                objPedidosRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_INGRESAR_CONTROL_POR_APLICACION(My.Application.IDAPLICACION, NombreControl, DescripcionControl)
                            End If
                        Next
                    End If
                Next
            Next
        Catch ex As Exception
            MessageBox.Show("#ERROR RC002, No se pudo realizar el registro de los controles: " + ex.ToString)
        End Try

    End Sub


    Public Shared Sub DesactivarControlesAplicacion(ByRef unForm As Form) 'se desactivan incialmente los controles para poder controlarlos
        Dim Menu As System.Windows.Forms.ToolStripMenuItem
        Dim SubMenu As System.Windows.Forms.ToolStripDropDownItem
        Dim submenu_ As System.Windows.Forms.ToolStripItem
        Dim I, H As Integer
        Dim NombreControl As String

        Try
            For Each Menu In unForm.MainMenuStrip.Items
                NombreControl = Menu.Name
                Menu.Enabled = False
                Menu.Visible = False
                For I = 0 To Menu.DropDownItems.Count - 1
                    If Menu.DropDownItems.Item(I).GetType().FullName = "System.Windows.Forms.ToolStripMenuItem" Then '---->Menu
                        SubMenu = Menu.DropDownItems.Item(I) '--->opciones del menu
                        NombreControl = SubMenu.Name
                        SubMenu.Enabled = False
                        SubMenu.Visible = False
                        For H = 0 To SubMenu.DropDownItems.Count - 1
                            If SubMenu.DropDownItems.Item(H).GetType().FullName = "System.Windows.Forms.ToolStripMenuItem" Then '---->Menu
                                submenu_ = SubMenu.DropDownItems.Item(H) '--->opciones del menu
                                NombreControl = submenu_.Name
                                submenu_.Enabled = False
                                submenu_.Visible = False
                            End If
                        Next
                    End If
                Next
            Next
        Catch ex As Exception
            MessageBox.Show("#ERROR DC1002, No se pudieron desactivar los controles: " + ex.ToString)
        End Try

    End Sub
    Public Shared Sub ActivarControlesPorPefil(ByRef unForm As Form, ByVal unIdAplicacion As Integer, ByVal unIdPerfil As Integer)
        Dim Menu As System.Windows.Forms.ToolStripMenuItem
        Dim SubMenu As System.Windows.Forms.ToolStripDropDownItem
        Dim submenu_ As System.Windows.Forms.ToolStripItem
        Dim I, H As Integer
        Dim NombreControl As String
        Try

            '    ''2) Obtengo el listado de los controles habilitados POR PERFIL desde el sistema de seguridad
            Dim mDtListadoControles = New DataTable

            objPedidosRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_LISTADO_CONTROLES_POR_PERFIL(My.Application.IDAPLICACION, My.Application.IDPERFIL)
            mDtListadoControles = objPedidosRN.Tabla
            If Not IsNothing(mDtListadoControles) Then

                For Each Menu In unForm.MainMenuStrip.Items
                    NombreControl = Menu.Name
                    'Menu.Enabled = False                    
                    ActivarControlPorSeguridad(Menu, mDtListadoControles)
                    For I = 0 To Menu.DropDownItems.Count - 1
                        If Menu.DropDownItems.Item(I).GetType().FullName = "System.Windows.Forms.ToolStripMenuItem" Then '---->Menu
                            SubMenu = Menu.DropDownItems.Item(I) '--->opciones del menu
                            NombreControl = SubMenu.Name                           
                            'SubMenu.Enabled = False
                            ActivarControlPorSeguridad(SubMenu, mDtListadoControles)
                            For H = 0 To SubMenu.DropDownItems.Count - 1
                                If SubMenu.DropDownItems.Item(H).GetType().FullName = "System.Windows.Forms.ToolStripMenuItem" Then '---->Menu
                                    submenu_ = SubMenu.DropDownItems.Item(H) '--->opciones del menu
                                    NombreControl = submenu_.Name
                                    ActivarControlPorSeguridad(submenu_, mDtListadoControles)
                                End If
                            Next
                        End If

                    Next
                Next
            End If
        Catch ex As Exception
            MessageBox.Show("#ERROR RC002, No se pudo realizar el activación de los controles: " + ex.ToString)
        End Try

    End Sub
    Public Shared Sub ActivarControlesPorUsuario(ByRef unForm As Form, ByVal unIdAplicacion As Integer, ByVal unIdPerfil As Integer)
        Dim Menu As System.Windows.Forms.ToolStripMenuItem
        Dim SubMenu As System.Windows.Forms.ToolStripDropDownItem
        Dim submenu_ As System.Windows.Forms.ToolStripItem
        Dim I, H As Integer
        Dim NombreControl As String
        Try

            ''2) Obtengo el listado de los controles habilitados POR USUARIO desde el sistema de seguridad
            Dim mDtListadoControlesUSu = New DataTable
            objPedidosRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_LISTADO_CONTROLES_POR_USUARIO(My.Application.IDAPLICACION, My.Application.IDUSUARIO)
            mDtListadoControlesUSu = objPedidosRN.Tabla

            If Not IsNothing(mDtListadoControlesUSu) Then
                For Each Menu In unForm.MainMenuStrip.Items
                    NombreControl = Menu.Name
                    'Menu.Enabled = False
                    ActivarControlPorSeguridad(Menu, mDtListadoControlesUSu)
                    For I = 0 To Menu.DropDownItems.Count - 1
                        If Menu.DropDownItems.Item(I).GetType().FullName = "System.Windows.Forms.ToolStripMenuItem" Then '---->Menu
                            SubMenu = Menu.DropDownItems.Item(I) '--->opciones del menu
                            NombreControl = SubMenu.Name
                            ' SubMenu.Enabled = False
                            ActivarControlPorSeguridad(SubMenu, mDtListadoControlesUSu)
                            For H = 0 To SubMenu.DropDownItems.Count - 1
                                If SubMenu.DropDownItems.Item(H).GetType().FullName = "System.Windows.Forms.ToolStripMenuItem" Then '---->Menu
                                    submenu_ = SubMenu.DropDownItems.Item(H) '--->opciones del menu
                                    NombreControl = submenu_.Name
                                    ActivarControlPorSeguridad(submenu_, mDtListadoControlesUSu)
                                End If
                            Next
                        End If
                    Next
                Next
            End If
        Catch ex As Exception
            MessageBox.Show("#ERROR AC0034, No se pudo realizar la activación de los controles por usuario: " + ex.ToString)
        End Try
    End Sub


    Public Shared Sub ActivarControlPorSeguridad(ByVal NControl As ToolStripMenuItem, ByRef mdtListadocontroles1 As DataTable)

        For i As Integer = 0 To mdtListadocontroles1.Rows.Count - 1
            If NControl.Name = mdtListadocontroles1.Rows(i).Item("NOMBRECONTROL") Then
                NControl.Visible = mdtListadocontroles1.Rows(i).Item("VISIBLE")
                NControl.Enabled = mdtListadocontroles1.Rows(i).Item("ACTIVO")
                Exit For
            End If
        Next
    End Sub
    Public Shared Sub ActivarControlPorSeguridad(ByVal NControl As ToolStripDropDownItem, ByRef mdtListadocontroles1 As DataTable)

        For i As Integer = 0 To mdtListadocontroles1.Rows.Count - 1
            If NControl.Name = mdtListadocontroles1.Rows(i).Item("NOMBRECONTROL") Then
                NControl.Visible = mdtListadocontroles1.Rows(i).Item("VISIBLE")
                NControl.Enabled = mdtListadocontroles1.Rows(i).Item("ACTIVO")
                Exit For
            End If
        Next
    End Sub


    Public Shared Sub ActivarControlPorSeguridad(ByVal NControl As ToolStripItem, ByRef mdtListadocontroles1 As DataTable)
        For i As Integer = 0 To mdtListadocontroles1.Rows.Count - 1
            If NControl.Name = mdtListadocontroles1.Rows(i).Item("NOMBRECONTROL") Then
                NControl.Visible = mdtListadocontroles1.Rows(i).Item("VISIBLE")
                NControl.Enabled = mdtListadocontroles1.Rows(i).Item("ACTIVO")
                Exit For
            End If
        Next
    End Sub

#End Region

End Class

viernes, 31 de julio de 2020

Consultar Deposito Mayorista (Expresiones de combo box, control grid)

Public Class Consultar_Deposito_Mayorista

#Region "Declaraciones"
    Private ObjReqRN As New ReqRN
    Private _dtResu As New DataTable
    Public idcliente As Integer
    Private FBD_Exportar As New System.Windows.Forms.FolderBrowserDialog
    Private mDt As New DataTable
    Private _idUbicacion As Integer
#End Region

#Region "Funciones"

#End Region

    Private Sub CargarComboClientes(ByVal unUsuario As Integer)
        Dim dtResu As New DataTable
        ObjReqRN = New ReqRN

        GLUE_Cliente.Properties.DataSource = ObjReqRN.SP_PLUS_REQUERIMIENTOS_LISTAR_CLIENTE_X_USUARIO_COMBO_STOCK '(unUsuario)
        GLUE_Cliente.Properties.PopulateViewColumns()
        GLUE_Cliente.Properties.DisplayMember = "Cliente"
        GLUE_Cliente.Properties.ValueMember = "idcliente"
        GLUE_Cliente.Properties.View.Columns("idcliente").Visible = False

    End Sub
    Private Sub CargarComboClientesLocales()
        Dim dtResu As New DataTable
        ObjReqRN = New ReqRN

        GLUE_Cliente.Properties.DataSource = ObjReqRN.SP_PLUS_REQUERIMIENTOS_CLIENTES_STOCK_LISTADO_LOCALES '(unUsuario)
        GLUE_Cliente.Properties.PopulateViewColumns()
        GLUE_Cliente.Properties.DisplayMember = "Cliente"
        GLUE_Cliente.Properties.ValueMember = "idcliente"
        GLUE_Cliente.Properties.View.Columns("idcliente").Visible = False

    End Sub

    Private Sub Consultar_Deposito_Mayorista_Load(sender As Object, e As EventArgs) Handles Me.Load
        LimpiarCampos_Datos()
        'CargarComboClientes(My.Application.IDUSUARIO)
    End Sub
    Private Sub Cargar_Gcstock()
        ObjReqRN = New ReqRN
        Dim _dtResu = New DataTable
        Try
            idcliente = GLUE_Cliente.EditValue
            If idcliente <> 0 Then
                _dtResu = ObjReqRN.SP_PLUS_REQUERIMIENTOS_CLIENTES_STOCK_LEER_DEPOSITOS(idcliente)
                If Not IsNothing(_dtResu) Then
                    GcStockMayor.DataSource = _dtResu
                    Dim _ubicacion As String = _dtResu.Rows(0).Item(7)
                    Dim _subDeposito As String = _dtResu.Rows(0).Item(8)
                    Dim _Deposito As String = _dtResu.Rows(0).Item(9)
                    Dim _sede As String = _dtResu.Rows(0).Item(10)

                    CargaDatosLb(_ubicacion, _subDeposito, _Deposito, _sede)
                Else
                    GcStockMayor.DataSource = Nothing
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("#ERROR D001" & ex.ToString, "Consultar Deposito", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
        End Try

    End Sub

    Private Sub RecuperaDatosConsulta()
        Try
            mDt = New DataTable
            idcliente = GLUE_Cliente.EditValue
            mDt = AccesoBase.SetSP("SP_PLUS_REQUERIMIENTOS_CLIENTES_STOCK_DATOS_CONSULTA").SetParam(idcliente, "RRL")
            If Not IsNothing(mDt) Then
                _idUbicacion = mDt.Rows(0).Item("UBICACION")
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Cargar_Gcstock_Locales()
        RecuperaDatosConsulta()
        ObjReqRN = New ReqRN
        Dim _dtResu = New DataTable
        Try
            idcliente = GLUE_Cliente.EditValue.ToString
            If idcliente <> 0 Then
                '_dtResu = ObjReqRN.SP_PLUS_REQUERIMIENTOS_CLIENTES_STOCK_LEER_DEPOSITOS(idcliente, _idUbicacion)

                _dtResu = AccesoBase.SetSP("SP_PLUS_REQUERIMIENTOS_CLIENTES_STOCK_LEER_DEPOSITOS_LOCALES").SetParam(idcliente, _idUbicacion)
                'If Not IsNothing(mDtListadoArbol) Then

                If Not IsNothing(_dtResu) Then
                    GcStockMayor.DataSource = _dtResu
                    Dim _ubicacion As String = _dtResu.Rows(0).Item(7)
                    Dim _subDeposito As String = _dtResu.Rows(0).Item(8)
                    Dim _Deposito As String = _dtResu.Rows(0).Item(9)
                    Dim _sede As String = _dtResu.Rows(0).Item(10)

                    CargaDatosLb(_ubicacion, _subDeposito, _Deposito, _sede)
                Else
                    GcStockMayor.DataSource = Nothing
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("#ERROR D001" & ex.ToString, "Consultar Deposito", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
        End Try

    End Sub

    Private Sub CargaDatosLb(ByVal ubicacion As String, ByVal subDeposito As String, ByVal Deposito As String, ByVal sede As String)
        LblDestinoSedeDato.Text = sede
        LblDestinoDepositoDato.Text = Deposito
        LblDestinoSubDepositoDato.Text = subDeposito
        LblDestinoUbicacionDato.Text = ubicacion
        Me.Refresh()
    End Sub


    Private Sub GLUE_Cliente_EditValueChanged(sender As Object, e As EventArgs) Handles GLUE_Cliente.EditValueChanged
        If RB_Mayor.Checked Then
            Cargar_Gcstock()
        Else
            Cargar_Gcstock_Locales()
        End If

    End Sub
    '****************** exportación *******************
    Private Sub Btn_ExportarExcel_Click(sender As Object, e As EventArgs) Handles Btn_ExportarExcel.Click
        FBD_Exportar = New System.Windows.Forms.FolderBrowserDialog
        Dim _valido As Boolean = True
        Try
            If (GLUE_Cliente.EditValue = 0 And GvDestino.RowCount = 0) Then
                MessageBox.Show("Algunos campos estan vacios, verifique de nuevo", "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                Exit Sub
            End If
            If (GvDestino.RowCount = 0) Then
                If (MessageBox.Show("La tabla esta vacia, ¿Igual deseas Exportar?", "Exportar", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)) = Windows.Forms.DialogResult.No Then
                    _valido = False
                End If
            Else
                If _valido = True Then
                    Dim Path As String = ""
                    If FBD_Exportar.ShowDialog() = Windows.Forms.DialogResult.OK Then
                        Path = FBD_Exportar.SelectedPath & "\Stock_Deposito_" & Trim(GLUE_Cliente.Text) & "_" & Date.Now.ToString("ddMMyyyy") & ".XLS"
                        GvDestino.ExportToXls(Path)
                        MessageBox.Show("Se exportó el archivo correctamente en la ruta seleccionada.", "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
                    End If
                    LimpiarCampos_Datos()
                End If
            End If
            
        Catch ex As Exception
            MessageBox.Show("#ERROR D002: al intentar exportar archivo de excel." & vbCrLf & ex.Message, "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
 
    Private Sub BTSalir_Click(sender As Object, e As EventArgs) Handles BTSalir.Click
        Me.Close()
    End Sub
    Private Sub LimpiarCampos_Datos()
        LblDestinoSedeDato.Text = ""
        LblDestinoDepositoDato.Text = ""
        LblDestinoSubDepositoDato.Text = ""
        LblDestinoUbicacionDato.Text = ""
        GcStockMayor.DataSource = Nothing
    End Sub

    Private Sub RB_Mayor_CheckedChanged(sender As Object, e As EventArgs) Handles RB_Mayor.CheckedChanged
        LimpiarCampos_Datos()
        CargarComboClientes(My.Application.IDUSUARIO)
    End Sub

    Private Sub RB_Locales_CheckedChanged(sender As Object, e As EventArgs) Handles RB_Locales.CheckedChanged
        LimpiarCampos_Datos()
        CargarComboClientesLocales()
    End Sub


End Class

jueves, 30 de julio de 2020

FUNCIONES DECLARADAS con Shared

Las funciones declaradas con Shared quieren decir que son definidas a nivel de clase no de instancia, por lo tanto la invocas directo con el nombre de la clase que la contenga, sin usar el "new"

por ejmeplo si tienes la clase

Public Class Prueba

  Public  Shared Function GetValor() As Int

      Return 10

  End Function

End Class

desde tu formulario lo usarias

TextBox1.Text = CStr(Prueba.GetValor())

o sea directamente nombre de la clase y nombre del metodo


Ejemplo de declaraciones de shared en la clase PermisosControles  del aplicativo seguridad plus.




Public Class ControlesPermisos

    Inherits DevExpress.XtraEditors.XtraForm


#Region "Declaraciones"


    Private Shared mDtListadoControles As New DataTable

    Private Shared WithEvents RibbonControl As DevExpress.XtraBars.Ribbon.RibbonControl

    Private Shared Solapas As DevExpress.XtraBars.Ribbon.RibbonPage

    Private Shared Grupo As DevExpress.XtraBars.Ribbon.RibbonPageGroup

    Private Shared Category As DevExpress.XtraBars.Ribbon.RibbonPageCategory

    Private Shared Boton As DevExpress.XtraBars.BarItemLink

    Private Shared ObjReqRN As New ReqRN


    Private Shared CotrolTab = New DevExpress.XtraTab.XtraTabControl

    Private Shared PageTab = New DevExpress.XtraTab.XtraTabPage

    'Private ColeccionTab = New DevExpress.XtraTab.XtraTabPageCollection

 

#End Region



#Region "Funciones"

    Public Shared Sub RegistrarCtrlMenues(ByRef unForm As Form)


        Dim Pagina As DevExpress.XtraBars.Ribbon.RibbonPage

        Dim Grupo As DevExpress.XtraBars.Ribbon.RibbonPageGroup

        Dim CntGrupo As Integer = 0

        Dim Boton As DevExpress.XtraBars.BarItemLink

        Dim CntBoton As Integer = 0

        Dim DT_Pagina, DT_Boton As New DataTable

        Dim idAplicacion As Integer = My.Application.IDAPLICACION



        Dim _descripcion As String

        Dim _descripcionUNO As String

        For Each Pagina In Principal.RBMenu.Pages

            ObjReqRN = New ReqRN

            'DT_Pagina =

            ObjReqRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_INGRESAR_CONTROL_POR_APLICACION(idAplicacion, Pagina.Name.ToString, Pagina.Name.ToString)

            For Each Grupo In Pagina.Groups

                _descripcionUNO = Pagina.Name + "/" + Grupo.Name

                ObjReqRN = New ReqRN

                ObjReqRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_INGRESAR_CONTROL_POR_APLICACION(idAplicacion, Grupo.Name.ToString, _descripcionUNO)

                For Each Boton In Grupo.ItemLinks

                    _descripcion = Pagina.Name + "/" + Grupo.Name + "/" + Boton.Item.Name ' REGISTRA LOS GRUPOS TAMBIEN

                    ' _descripcion = Pagina.Name + "/" + Boton.Item.Name ' AQUI NO REGISTRA LOS GRUPOPS SOLO LOS BOTONES

                    ObjReqRN = New ReqRN

                    ObjReqRN.SP_HERRAMIENTAS_SIGMA_SEGURIDAD_INGRESAR_CONTROL_POR_APLICACION(idAplicacion, Boton.Item.Name.ToString, _descripcion)

                Next 'Links

            Next 'Grupo

        Next 'Pagina


    End Sub




miércoles, 29 de julio de 2020

Ejecutar un formulario dentro de otro formulario Padre vb.net

El formulario donde haras el codigo que acontinuacion te muestro es el padre o donde va reposar el otro formulario cuando lo ejecutes, y el que estamos definiendo como instancia, es el hijo.


 If mostrar Then
            Me.fHojaDeRutaLista = New FormHojaDeRutaLista
            Me.fHojaDeRutaLista.MdiParent = Me
            Me.fHojaDeRutaLista.Show()
End If

La palabra (Me) nos dice que el formulario hijo se ejecutara aqui.

la instancia del formulario hijo:

            Me.fHojaDeRutaLista.Show()


Configurar controlgrid (grilla, filtros dentro de la grilla) vb.net









Se debe seleccionar primero la opcion  (option view show group panel option)





Una vez seleccionada la opcion que muestra el campo en la pantalla anterior te permite , seleccionar una columna, para mover al lugar del filtros para colocar dentro de la grilla un filtro o una pestaña que te clasifica los estados en este caso.


Los mail de oulook no se pueden reenviar.

 cuando en el asunto poseen un caracter especial por ejemplo @#$ los correos no salen y no te muestra ningun correo de rebote, especialmente...