Imports System.Data.SqlClient
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Security.Cryptography
Imports System.Text
Imports System.Text.RegularExpressions

Module Module1
    Public Function CheckForm(_form As Form) As Boolean
        For Each f As Form In Application.OpenForms
            If f.Name = _form.Name Then
                Return True
            End If
        Next
        Return False
    End Function
    Sub IsValidEmail(ByVal Email As TextBox)
        Static emailExpression As New Regex("^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$")

        If Not emailExpression.IsMatch(Email.Text) Then
            MsgBox("Atención! El correo electrónico ingresado no es válido.", MsgBoxStyle.Information, "Mensaje del Sistema")
            Email.Text = ""
            Email.Focus()
        End If
    End Sub
    Sub ContarCaracteres(ByVal TextBox As TextBox, ByVal Caracteres As Integer, ByVal Campo As String)
        If TextBox.Text.Length <> Caracteres Then
            MsgBox("Atención! el Campo " & Campo & " No cumple con los caracteres necesarios (" & Caracteres & ")")
            TextBox.Focus()
            Exit Sub
        End If
    End Sub
    Sub ContarCaracteres2(ByVal TextBox As TextBox, ByVal Caracteres As Integer)
        If TextBox.Text.Length <> Caracteres Then
            MsgBox("Atención! el Campo " & TextBox.Tag & " No cumple con los caracteres necesarios (" & Caracteres & ")")
            TextBox.Focus()
            Exit Sub
        End If
    End Sub
    Public Sub DelGuion(ByVal CajaTexto As Windows.Forms.TextBox, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If e.KeyChar = "-" Then
            e.Handled = True
        End If
    End Sub
    Sub DescargarArchivo(Archivo As TextBox)
        If Archivo.Text Is Nothing Or IsDBNull(Archivo.Text) Or Archivo.Text = "" Then
            Exit Sub
        End If
        Try
            Dim Filename As String = Archivo.Text

            Dim request As FtpWebRequest = WebRequest.Create("ftp://neuroexpress.mx/" & Filename)
            request.Credentials = New NetworkCredential("sftneuroexp@neuroexpress.mx", "sneAcc#7524")
            request.Method = WebRequestMethods.Ftp.DownloadFile

            Using ftpStream As Stream = request.GetResponse().GetResponseStream(),
                fileStream As Stream = File.Create(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "\Downloads\" & Filename)
                ftpStream.CopyTo(fileStream)
            End Using
            MsgBox("Archivo descargado con éxito en Downloads\" & Filename, MsgBoxStyle.Information, "Mensaje del Sistema")

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
    Sub LimpiarCampos(ByVal c1 As Control)
        'Limpia todos los controles dentro del control principal (c1)
        'aunque esten dentro de otros controles
        For Each c As Control In c1.Controls
            If TypeOf c Is TextBox Then
                c.Text = "" ' eliminar el texto 
            Else
                LimpiarCampos(c)
            End If
            If TypeOf c Is ComboBox Then
                c.Text = "" ' eliminar el texto 
            Else
                LimpiarCampos(c)
            End If
            If TypeOf c Is DateTimePicker Then
                c.Text = Date.Today ' Pone la fecha actual 
            Else
                LimpiarCampos(c)
            End If
            If (TypeOf (c) Is CheckBox) Then
                CType(c, CheckBox).Checked = False 'Quita el check
            Else
                LimpiarCampos(c)
            End If
            If (TypeOf (c) Is RadioButton) Then
                CType(c, RadioButton).Checked = False 'Quita el check
            Else
                LimpiarCampos(c)
            End If
        Next
    End Sub
    Public Sub LlenarCombo(ByVal Combo As ComboBox, ByVal Tabla As String, ByVal Idcampo As String, ByVal Campo As String)

        Try
            ' Verificamos que los valores de los parámetros sean correctos.

            If (Combo Is Nothing) Then
                Throw New ArgumentNullException("No se ha especificado el nombre del ComboBox")
            End If
            If (String.IsNullOrEmpty(Tabla)) Then
                Throw New ArgumentException("No se ha especificado el nombre de la Tabla.")
            End If
            If (String.IsNullOrEmpty(Campo)) Then
                Throw New ArgumentException("No se ha especificado el nombre del Campo.")
            End If

            ' Configuramos una conexión con la cadena de conexión existente
            ' a nivel del proyecto.
            Using cn As New SqlConnection(GlobalVariables.cstring)
                Dim com As SqlCommand = cn.CreateCommand()
                'otra forma, hay que agregar sqlCriterio al publicsub e incluirlo en la llamada
                'com.CommandText = String.Format("SELECT * FROM " & tabla * "  " & sqlCriterio)
                com.CommandText = String.Format("SELECT distinct " & Campo & " FROM " & Tabla & " order by " & Campo)
                Dim adap As New SqlDataAdapter(com)
                Dim dt As New DataTable()

                adap.Fill(dt)

                Combo.DataSource = dt
                Combo.ValueMember = Idcampo
                Combo.DisplayMember = Campo
            End Using

        Catch ex As Exception
            ' Se ha producido un error.
            '
            MessageBox.Show(ex.Message)

        End Try

    End Sub

    Public Sub LlenarComboCriterio(ByVal Combo As ComboBox, ByVal Tabla As String, ByVal Idcampo As String, Criterio As String, ByVal Campo As String)
        Try
            ' Verificamos que los valores de los parámetros sean correctos.

            If (Combo Is Nothing) Then
                Throw New ArgumentNullException("No se ha especificado el nombre del ComboBox")
            End If
            If (String.IsNullOrEmpty(Tabla)) Then
                Throw New ArgumentException("No se ha especificado el nombre de la Tabla.")
            End If
            If (String.IsNullOrEmpty(Campo)) Then
                Throw New ArgumentException("No se ha especificado el nombre del Campo.")
            End If
            Using cn As New SqlConnection(GlobalVariables.cstring)
                Dim com As SqlCommand = cn.CreateCommand()
                'otra forma, hay que agregar sqlCriterio al publicsub e incluirlo en la llamada
                'com.CommandText = String.Format("SELECT * FROM " & tabla * "  " & sqlCriterio)
                com.CommandText = String.Format("SELECT distinct " & Campo & " FROM " & Tabla & " where " & Criterio & " order by " & Campo)
                Dim adap As New SqlDataAdapter(com)
                Dim dt As New DataTable()

                adap.Fill(dt)

                Combo.DataSource = dt
                Combo.ValueMember = Idcampo
                Combo.DisplayMember = Campo
            End Using

        Catch ex As Exception
            ' Se ha producido un error.
            '
            MessageBox.Show(ex.Message)

        End Try
    End Sub

    Function DMax(Campo As String, Tabla As String) As Double

        Dim valor As Double
        valor = 0
        Dim sConnection As String = GlobalVariables.cstring

        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select Max(" & Campo & ") From " & Tabla
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0).ToString
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function

    Function DMaxCriterio(Campo As String, Tabla As String, strCriterio As String) As Double

        Dim valor As Double
        valor = 0
        Dim sConnection As String = GlobalVariables.cstring

        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select Max(" & Campo & ") From " & Tabla & " where " & strCriterio
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0).ToString
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function

    Function DMin(Campo As String, Tabla As String) As Double

        Dim valor As Double
        valor = 0
        Dim sConnection As String = GlobalVariables.cstring

        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select Min(" & Campo & ") From " & Tabla
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0).ToString
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function

    Function DMinCriterio(Campo As String, Tabla As String, strCriterio As String) As Double

        Dim valor As Double
        valor = 0
        Dim sConnection As String = GlobalVariables.cstring

        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select Min(" & Campo & ") From " & Tabla & " where " & strCriterio
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0).ToString
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function

    Function DLookup(Campo As String, tabla As String, strCriterio As String) As String

        Dim valor As String
        valor = ""
        Dim sConnection As String = GlobalVariables.cstring
        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select " & Campo & " From " & tabla & " where " & strCriterio
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0).ToString
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function

    Function DLookupNum(Campo As String, tabla As String, strCriterio As String) As String

        Dim valor As Double
        valor = 0
        Dim sConnection As String = GlobalVariables.cstring
        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select " & Campo & " From " & tabla & " where " & strCriterio
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0).ToString
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function
    Function BuscaImagen(Campo As String, tabla As String, strCriterio As String) As Byte()
        Dim valor() As Byte

        Dim sConnection As String = GlobalVariables.cstring
        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select " & Campo & " From " & tabla & " where " & strCriterio
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0)
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function

    Function DSum(Campo As String, Tabla As String, strCriterio As String) As Double

        Dim valor As Double
        valor = 0
        Dim sConnection As String = GlobalVariables.cstring
        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select sum(" & Campo & ") From " & Tabla & " where " & strCriterio
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0).ToString
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function

    Function DCount(Campo As String, Tabla As String, strCriterio As String) As Double

        Dim valor As Double
        valor = 0
        Dim sConnection As String = GlobalVariables.cstring
        Using Con As New SqlConnection(sConnection)
            Con.Open()
            Dim SQL As String
            SQL = "Select Count(" & Campo & ") From " & Tabla & " where " & strCriterio
            Using Com As New SqlCommand(SQL, Con)
                Using RDR = Com.ExecuteReader()
                    If RDR.HasRows Then
                        Do While RDR.Read
                            If (RDR.IsDBNull(0)) = False Then
                                valor = RDR.Item(0).ToString
                                GoTo SEGUIR
                                'Null: Do not call GetDateTime
                            End If
                        Loop
                    End If
                End Using
            End Using
SEGUIR:
            Con.Close()
        End Using

        Return valor
    End Function

    Public Function ObtenerClave(Opcion As String, Psw As String)
        Dim cn As New SqlConnection(GlobalVariables.cstring)
        Dim ClaveEncontrada As Boolean = False
        Dim sql As String = "select * from Claves where clave='" & Psw & "' COLLATE SQL_Latin1_General_CP1_CS_AS and  opcion='" & Opcion & "' COLLATE SQL_Latin1_General_CP1_CS_AS"

        Try
            Dim cmd As New SqlCommand(sql, cn)
            cn.Open()
            Dim objDataReader As SqlDataReader = cmd.ExecuteReader()

            If objDataReader.HasRows Then
                objDataReader.Read()
                ClaveEncontrada = True
            Else
                ClaveEncontrada = False
            End If

            objDataReader.Close()
            cmd.Dispose()
            cn.Close()

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical)
        End Try
        Return ClaveEncontrada
    End Function

    Public Function ObtenerAcceso(Opcion As String, Psw As String)
        Dim cn As New SqlConnection(GlobalVariables.cstring)
        Dim ClaveEncontrada As Boolean = False
        Dim sql As String = "select * from Usuarios where Password='" & Psw & "' COLLATE SQL_Latin1_General_CP1_CS_AS and Nivel='" & Opcion & "' COLLATE SQL_Latin1_General_CP1_CS_AS"

        Try
            Dim cmd As New SqlCommand(sql, cn)
            cn.Open()
            Dim objDataReader As SqlDataReader = cmd.ExecuteReader()

            If objDataReader.HasRows Then
                objDataReader.Read()
                ClaveEncontrada = True
            Else
                ClaveEncontrada = False
            End If

            objDataReader.Close()
            cmd.Dispose()
            cn.Close()

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical)
        End Try
        Return ClaveEncontrada
    End Function

    Public Function Encriptar(ByVal Input As String) As String

        Dim IV() As Byte = ASCIIEncoding.ASCII.GetBytes("GarmCode") 'La clave debe ser de 8 caracteres
        Dim EncryptionKey() As Byte = Convert.FromBase64String("gmrSPvIvVLlrcodePU9/c67Gkj7yL1S5") 'No se puede alterar la cantidad de caracteres pero si la clave, 32 caracteres
        Dim buffer() As Byte = Encoding.UTF8.GetBytes(Input)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
        des.Key = EncryptionKey
        des.IV = IV

        Return Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length()))

    End Function

    Public Function Desencriptar(ByVal Input As String) As String

        Dim IV() As Byte = ASCIIEncoding.ASCII.GetBytes("GarmCode") 'La clave debe ser de 8 caracteres
        Dim EncryptionKey() As Byte = Convert.FromBase64String("gmrSPvIvVLlrcodePU9/c67Gkj7yL1S5") 'No se puede alterar la cantidad de caracteres pero si la clave, 32 caracteres
        Dim buffer() As Byte = Convert.FromBase64String(Input)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
        des.Key = EncryptionKey
        des.IV = IV
        Return Encoding.UTF8.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length()))

    End Function


    'METODO ABRIR FORMULARIOS DENTRO DEL PANEL

    'Metodo / evento al cerrar Forms
    Public Sub CerrarFormulario()

        If (Application.OpenForms("frmClientes") Is Nothing) Then
            FrmMain.BtnClientes.BackColor = Color.FromArgb(1, 0, 102)
        End If

        If (Application.OpenForms("FrmCobranza") Is Nothing) Then
            FrmMain.BtnCobranza.BackColor = Color.FromArgb(1, 0, 102)
        End If
        If (Application.OpenForms("FrmInvoicesHisto") Is Nothing) Then
            FrmMain.BtnInvoicesHisto.BackColor = Color.FromArgb(1, 0, 102)
        End If
        If (Application.OpenForms("FrmInvoices") Is Nothing) Then
            FrmMain.BtnInvoices.BackColor = Color.FromArgb(1, 0, 102)
        End If


        ' PANEL SISTEMA
        If (Application.OpenForms("frmConfig") Is Nothing) Then
            FrmMain.BtnITConfig.BackColor = Color.FromArgb(13, 149, 225)
        End If
        If (Application.OpenForms("frmUsuarios") Is Nothing) Then
            FrmMain.BtnITUsuarios.BackColor = Color.FromArgb(13, 149, 225)
        End If
        If (Application.OpenForms("frmControlACC") Is Nothing) Then
            FrmMain.BtnITControlAcc.BackColor = Color.FromArgb(13, 149, 225)
        End If
    End Sub
    Public Function QryConsulta(ByVal sql) As DataSet
        Dim ds As New DataSet
        Try
            Dim cn As New SqlConnection(GlobalVariables.cstring)
            Dim com As New SqlCommand(sql, cn)
            Dim ad As New SqlDataAdapter(com)
            cn.Open()
            ad.Fill(ds)
            ad.Dispose()
            cn.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Return ds
    End Function

    Public Sub QryInsUpDel(ByVal query As String)
        Try
            Dim cn As New SqlConnection(GlobalVariables.cstring)
            Dim com As New SqlCommand(query, cn)
            cn.Open()
            com.ExecuteNonQuery()
            cn.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Public Function GetMyNumberToWords(ByVal value As String) As String
        Dim str As String = String.Empty

        Select Case Convert.ToDouble(value)
            Case 0 : str = "CERO"
            Case 1 : str = "UN"
            Case 2 : str = "DOS"
            Case 3 : str = "TRES"
            Case 4 : str = "CUATRO"
            Case 5 : str = "CINCO"
            Case 6 : str = "SEIS"
            Case 7 : str = "SIETE"
            Case 8 : str = "OCHO"
            Case 9 : str = "NUEVE"
            Case 10 : str = "DIEZ"
            Case 11 : str = "ONCE"
            Case 12 : str = "DOCE"
            Case 13 : str = "TRECE"
            Case 14 : str = "CATORCE"
            Case 15 : str = "QUINCE"
            Case Is < 20 : str = "DIECI" & GetMyNumberToWords(value - 10)
            Case 20 : str = "VEINTE"
            Case Is < 30 : str = "VEINTI" & GetMyNumberToWords(value - 20)
            Case 30 : str = "TREINTA"
            Case 40 : str = "CUARENTA"
            Case 50 : str = "CINCUENTA"
            Case 60 : str = "SESENTA"
            Case 70 : str = "SETENTA"
            Case 80 : str = "OCHENTA"
            Case 90 : str = "NOVENTA"
            Case Is < 100 : str = GetMyNumberToWords(Int(value \ 10) * 10) & " Y " & GetMyNumberToWords(value Mod 10)
            Case 100 : str = "CIEN"
            Case Is < 200 : str = “CIENTO ” & GetMyNumberToWords(value - 100)
            Case 200, 300, 400, 600, 800 : str = GetMyNumberToWords(Int(value \ 100)) & "CIENTOS"
            Case 500 : str = "QUINIENTOS"
            Case 700 : str = "SETECIENTOS"
            Case 900 : str = "NOVECIENTOS"
            Case Is < 1000 : str = GetMyNumberToWords(Int(value \ 100) * 100) & " " & GetMyNumberToWords(value Mod 100)
            Case 1000 : str = "MIL"
            Case Is < 2000 : str = "MIL " & GetMyNumberToWords(value Mod 1000)
            Case Is < 1000000 : str = GetMyNumberToWords(Int(value \ 1000)) & " MIL"
                If value Mod 1000 Then str = str & ” ” & GetMyNumberToWords(value Mod 1000)
            Case 1000000 : str = "UN MILLON"
            Case Is < 2000000 : str = "UN MILLON " & GetMyNumberToWords(value Mod 1000000)
            Case Is < 1000000000000.0# : str = GetMyNumberToWords(Int(value / 1000000)) & " MILLONES "
                If (value - Int(value / 1000000) * 1000000) Then str = str & ” ” & GetMyNumberToWords(value - Int(value / 1000000) * 1000000)
            Case 1000000000000.0# : str = "UN BILLON"
            Case Is < 2000000000000.0# : str = "UN BILLON " & GetMyNumberToWords(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
            Case Else : str = str(Int(value / 1000000000000.0#)) & " BILLONES"
                If (value - Int(value / 1000000000000.0#) * 1000000000000.0#) Then str = str & " " & GetMyNumberToWords(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
        End Select

        Return str
    End Function


    Public Function Num2TextD(value As Double) As String
        Dim HayDecimales As Integer = InStr(1, value.ToString, ".")
        Dim a() As String
        a = Split(value.ToString, ".")
        Dim enteros As Integer = a(0)

        Dim decimales As Integer
        If HayDecimales = 0 Then
            decimales = "00"
        Else
            decimales = a(1)
            If Len(decimales.ToString) = 1 Then
                decimales = CInt(a(1) & "0")
            End If
        End If

        Dim txtEnteros As String = Num2Text(enteros)
        Dim txtDecimales As String = decimales
        Dim txtNumeroCompleto As String = txtEnteros & " PESOS " & txtDecimales & "/100 MN"

        Return txtNumeroCompleto
    End Function

    Public Function Num2TextDolarEsp(value As Double) As String
        Dim HayDecimales As Integer = InStr(1, value.ToString, ".")
        Dim a() As String
        a = Split(value.ToString, ".")
        Dim enteros As Integer = a(0)

        Dim decimales As Integer
        If HayDecimales = 0 Then
            decimales = "00"
        Else
            decimales = a(1)
            If Len(decimales.ToString) = 1 Then
                decimales = CInt(a(1) & "0")
            End If
        End If

        Dim txtEnteros As String = Num2Text(enteros)
        Dim txtDecimales As String = decimales
        Dim txtNumeroCompleto As String = txtEnteros & " DOLARES " & txtDecimales & "/100 MA"

        Return txtNumeroCompleto
    End Function

    Public Function Num2Text(ByVal value As Double) As String
        Select Case value
            Case 0 : Num2Text = "CERO"
            Case 1 : Num2Text = "UN"
            Case 2 : Num2Text = "DOS"
            Case 3 : Num2Text = "TRES"
            Case 4 : Num2Text = "CUATRO"
            Case 5 : Num2Text = "CINCO"
            Case 6 : Num2Text = "SEIS"
            Case 7 : Num2Text = "SIETE"
            Case 8 : Num2Text = "OCHO"
            Case 9 : Num2Text = "NUEVE"
            Case 10 : Num2Text = "DIEZ"
            Case 11 : Num2Text = "ONCE"
            Case 12 : Num2Text = "DOCE"
            Case 13 : Num2Text = "TRECE"
            Case 14 : Num2Text = "CATORCE"
            Case 15 : Num2Text = "QUINCE"
            Case Is < 20 : Num2Text = "DIECI" & Num2Text(value - 10)
            Case 20 : Num2Text = "VEINTE"
            Case Is < 30 : Num2Text = "VEINTI" & Num2Text(value - 20)
            Case 30 : Num2Text = "TREINTA"
            Case 40 : Num2Text = "CUARENTA"
            Case 50 : Num2Text = "CINCUENTA"
            Case 60 : Num2Text = "SESENTA"
            Case 70 : Num2Text = "SETENTA"
            Case 80 : Num2Text = "OCHENTA"
            Case 90 : Num2Text = "NOVENTA"
            Case Is < 100 : Num2Text = Num2Text(Int(value \ 10) * 10) & " Y " & Num2Text(value Mod 10)
            Case 100 : Num2Text = "CIEN"
            Case Is < 200 : Num2Text = "CIENTO " & Num2Text(value - 100)
            Case 200, 300, 400, 600, 800 : Num2Text = Num2Text(Int(value \ 100)) & "CIENTOS"
            Case 500 : Num2Text = "QUINIENTOS"
            Case 700 : Num2Text = "SETECIENTOS"
            Case 900 : Num2Text = "NOVECIENTOS"
            Case Is < 1000 : Num2Text = Num2Text(Int(value \ 100) * 100) & " " & Num2Text(value Mod 100)
            Case 1000 : Num2Text = "MIL"
            Case Is < 2000 : Num2Text = "MIL " & Num2Text(value Mod 1000)
            Case Is < 1000000 : Num2Text = Num2Text(Int(value \ 1000)) & " MIL"
                If value Mod 1000 Then Num2Text = Num2Text & " " & Num2Text(value Mod 1000)
            Case 1000000 : Num2Text = "UN MILLON"
            Case Is < 2000000 : Num2Text = "UN MILLON " & Num2Text(value Mod 1000000)
            Case Is < 1000000000000.0# : Num2Text = Num2Text(Int(value / 1000000)) & " MILLONES"
                If (value - Int(value / 1000000) * 1000000) Then Num2Text = Num2Text & " " & Num2Text(value - Int(value / 1000000) * 1000000)
            Case 1000000000000.0# : Num2Text = "UN BILLON"
            Case Is < 2000000000000.0# : Num2Text = "UN BILLON " & Num2Text(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
            Case Else : Num2Text = Num2Text(Int(value / 1000000000000.0#)) & " BILLONES"
                If (value - Int(value / 1000000000000.0#) * 1000000000000.0#) Then Num2Text = Num2Text & " " & Num2Text(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
        End Select

        Return Num2Text
    End Function

    Public Sub CreaBitacora(User As String, Screen As String, Action As String, Data As String)
        Dim sql As String = ""
        sql = "INSERT INTO BitacoraRegs (Fecha, Hora, Usuario, Pantalla, Accion, Datos) VALUES(@Fecha, @Hora, @Usuario, @Pantalla, @Accion, @Datos)"

        Try
            Dim cn As New SqlConnection(GlobalVariables.cstring)
            Dim cmd As New SqlCommand(sql, cn)
            cn.Open()
            cmd.Parameters.AddWithValue("@Fecha", DateTime.Today)
            cmd.Parameters.AddWithValue("@Hora", UCase(DateTime.Now.ToLongTimeString()))
            cmd.Parameters.AddWithValue("@Usuario", User)
            cmd.Parameters.AddWithValue("@Pantalla", Screen)
            cmd.Parameters.AddWithValue("@Accion", Action)
            cmd.Parameters.AddWithValue("@Datos", Data)
            cmd.ExecuteNonQuery()
            cn.Close()
            cmd = Nothing

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Public Function EnviarMail(mailSubject As String, mailBody As String)
        Dim smtp As New System.Net.Mail.SmtpClient
        smtp.Host = "host"
        smtp.Port = 25
        smtp.EnableSsl = False
        Dim mMail As New System.Net.Mail.MailMessage()
        mMail.[To].Add("nameTo@mail.com")
        mMail.From = New System.Net.Mail.MailAddress("nameFrom@mail.com", "", System.Text.Encoding.UTF8)
        mMail.Subject = mailSubject
        mMail.Body = mailBody
        Dim fileTXT As String = "c:\file1234.txt"
        Dim data As Net.Mail.Attachment = New Net.Mail.Attachment(fileTXT)
        data.Name = "file.txt"
        mMail.Attachments.Add(data)
        Try
            smtp.Send(mMail)
            data.Dispose()
            Return True
        Catch ex As System.Net.Mail.SmtpException
            Return False
        End Try
    End Function

    Public Sub EnviarCorreo(ByVal varTo As String, ByVal varMenssage As String, ByVal varPath As String, ByVal varSubject As String, ByVal Correo As String, ByVal Pass As String)
        Try
            Dim Smtp_Server As New SmtpClient
            Dim e_mail As New MailMessage()
            Smtp_Server.UseDefaultCredentials = False
            Smtp_Server.Credentials = New Net.NetworkCredential(Correo, Pass)
            Smtp_Server.Port = 587
            Smtp_Server.EnableSsl = True
            Smtp_Server.Host = "mail.godamexpress.com"

            e_mail = New MailMessage()
            e_mail.From = New MailAddress(Correo)
            e_mail.To.Add(varTo)
            e_mail.Subject = varSubject
            e_mail.IsBodyHtml = False
            e_mail.Body = varMenssage
            If varPath <> "" Then
                Dim archivo As Net.Mail.Attachment = New Net.Mail.Attachment(varPath)
                e_mail.Attachments.Add(archivo)
            End If

            Smtp_Server.Send(e_mail)
            MsgBox("Atención, El correo fue enviado correctamente. ", MsgBoxStyle.Information, "Mensaje del Sistema.")
            QryInsUpDel("UPDATE Invoices SET Estatus='POR PAGAR-ENV. MAIL' WHERE Id=" & FrmInvoices.Id.Text & "")
            FrmInvoices.Estatus.Text = "POR PAGAR-ENV. MAIL"

        Catch error_t As Exception
            MsgBox(error_t.ToString)
        End Try
    End Sub


    Public Sub EnviarCorreoDOSAdj(ByVal varTo As String, ByVal varMenssage As String, ByVal varPath As String, ByVal varPath2 As String, ByVal varSubject As String, ByVal Correo As String, ByVal Pass As String)

        Try
            Dim Smtp_Server As New SmtpClient
            Dim e_mail As New MailMessage()
            Smtp_Server.UseDefaultCredentials = False
            Smtp_Server.Credentials = New Net.NetworkCredential(Correo, Pass)
            Smtp_Server.Port = 587
            Smtp_Server.EnableSsl = True
            Smtp_Server.Host = "mail.godamexpress.com"

            e_mail = New MailMessage()
            e_mail.From = New MailAddress(Correo)
            e_mail.To.Add(varTo)
            e_mail.Subject = varSubject
            e_mail.IsBodyHtml = False
            e_mail.Body = varMenssage
            If varPath <> "" Then
                Dim archivo As Net.Mail.Attachment = New Net.Mail.Attachment(varPath)
                e_mail.Attachments.Add(archivo)
            End If
            If varPath2 <> "" Then
                Dim archivo2 As Net.Mail.Attachment = New Net.Mail.Attachment(varPath2)
                e_mail.Attachments.Add(archivo2)

            End If

            Smtp_Server.Send(e_mail)
            MsgBox("El mensaje fue enviado correctamente. ", MsgBoxStyle.Information, "Mensaje del Sistema.")

        Catch error_t As Exception
            MsgBox(error_t.ToString)
        End Try
    End Sub

    Sub BloquearControles(ByVal c1 As Control)

        'Limpia todos los controles dentro del control principal (c1)
        'aunque esten dentro de otros controles
        For Each c As Control In c1.Controls
            c.Enabled = False
        Next
    End Sub
    Sub DesBloquearControles(ByVal c1 As Control)

        'Limpia todos los controles dentro del control principal (c1)
        'aunque esten dentro de otros controles
        For Each c As Control In c1.Controls
            c.Enabled = True
        Next
    End Sub
    Sub UnlockCampos(ByVal c1 As Control)
        'Limpia todos los controles dentro del control principal (c1)
        'aunque esten dentro de otros controles
        For Each c As Control In c1.Controls
            If (TypeOf (c) Is TextBox) Then
                CType(c, TextBox).ReadOnly = False
            End If
            If TypeOf c Is ComboBox Then
                c.Enabled = True
            End If
            If TypeOf c Is DateTimePicker Then
                c.Enabled = True
            End If
            If (TypeOf (c) Is CheckBox) Then
                CType(c, CheckBox).Enabled = True
            End If
            If (TypeOf (c) Is RadioButton) Then
                CType(c, RadioButton).Enabled = True
            End If
        Next
    End Sub

    Sub LockCampos(ByVal c1 As Control)
        'Limpia todos los controles dentro del control principal (c1)
        'aunque esten dentro de otros controles
        For Each c As Control In c1.Controls
            If (TypeOf (c) Is TextBox) Then
                CType(c, TextBox).ReadOnly = True
            End If
            If TypeOf c Is ComboBox Then
                c.Enabled = False
            End If
            If TypeOf c Is DateTimePicker Then
                c.Enabled = False
            End If
            If (TypeOf (c) Is CheckBox) Then
                CType(c, CheckBox).Enabled = False
            End If
            If (TypeOf (c) Is RadioButton) Then
                CType(c, RadioButton).Enabled = False
            End If
        Next
    End Sub
    Public Sub NumConFrac(ByVal CajaTexto As Windows.Forms.TextBox, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If Char.IsDigit(e.KeyChar) Then
            e.Handled = False
        ElseIf Char.IsControl(e.KeyChar) Then
            e.Handled = False
        ElseIf e.KeyChar = "." And Not CajaTexto.Text.IndexOf(".") Then
            e.Handled = True
        ElseIf e.KeyChar = "." Then
            e.Handled = False
        Else
            e.Handled = True
        End If
    End Sub
    Public Sub NumOnly(ByVal CajaTexto As Windows.Forms.TextBox, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If Char.IsDigit(e.KeyChar) Then
            e.Handled = False
        ElseIf Char.IsControl(e.KeyChar) Then
            e.Handled = False
        ElseIf e.KeyChar = "." And Not CajaTexto.Text.IndexOf(".") Then
            e.Handled = True
        ElseIf e.KeyChar = "." Then
            e.Handled = True
        Else
            e.Handled = True
        End If
    End Sub

    Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String)
        Dim _FileInfo As New System.IO.FileInfo(_FileName)
        ' Create FtpWebRequest object from the Uri provided
        Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)

        ' Provide the WebPermission Credintials
        _FtpWebRequest.Credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)

        ' By default KeepAlive is true, where the control connection is not closed
        ' after a command is executed.
        _FtpWebRequest.KeepAlive = False

        ' set timeout for 20 seconds
        _FtpWebRequest.Timeout = 20000

        ' Specify the command to be executed.
        _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

        ' Specify the data transfer type.
        _FtpWebRequest.UseBinary = True

        ' Notify the server about the size of the uploaded file
        _FtpWebRequest.ContentLength = _FileInfo.Length

        ' The buffer size is set to 2kb
        Dim buffLength As Integer = 2048
        Dim buff(buffLength - 1) As Byte

        ' Opens a file stream (System.IO.FileStream) to read the file to be uploaded
        Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()

        Try
            ' Stream to which the file to be upload is written
            Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()

            ' Read from the file stream 2kb at a time
            Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)

            ' Till Stream content ends
            Do While contentLen <> 0
                ' Write Content from the file stream to the FTP Upload Stream
                _Stream.Write(buff, 0, contentLen)
                contentLen = _FileStream.Read(buff, 0, buffLength)
            Loop

            ' Close the file stream and the Request Stream
            _Stream.Close()
            _Stream.Dispose()
            _FileStream.Close()
            _FileStream.Dispose()
            MsgBox("Atención! archivo subido con exito.")
            GlobalVariables.VarUpload = True
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            GlobalVariables.VarUpload = False
        End Try

    End Sub
    Public Function ConvertNum(ByVal Input As Long) As String 'Call this function passing the number you desire to be changed
        Dim output As String = Nothing
        If Input < 1000 Then
            output = FindNumber(Input) 'if its less than 1000 then just look it up
        Else
            Dim nparts() As String 'used to break the number up into 3 digit parts
            Dim n As String = Input 'string version of the number
            Dim i As Long = Input.ToString.Length 'length of the string to help break it up

            Do Until i - 3 <= 0
                n = n.Insert(i - 3, ",") 'insert commas to use as splitters
                i = i - 3 'this insures that we get the correct number of parts
            Loop
            nparts = n.Split(",") 'split the string into the array

            i = Input.ToString.Length 'return i to initial value for reuse
            Dim p As Integer = 0 'p for parts, used for finding correct suffix
            For Each s As String In nparts
                Dim x As Long = CLng(s) 'x is used to compare the part value to other values
                p = p + 1
                If p = nparts.Length Then 'if p = number of elements in the array then we need to do something different
                    If x <> 0 Then
                        If CLng(s) < 100 Then
                            output = output & " AND " & FindNumber(CLng(s)) ' look up the number, no suffix 
                        Else                                                ' required as this is the last part
                            output = output & " " & FindNumber(CLng(s))
                        End If
                    End If
                Else 'if its not the last element in the array
                    If x <> 0 Then
                        If output = Nothing Then 'we have to check this so we don't add a leading space
                            output = output & FindNumber(CLng(s)) & " " & FindSuffix(i, CLng(s)) 'look up the number and suffix
                        Else 'spaces must go in the right place
                            output = output & " " & FindNumber(CLng(s)) & " " & FindSuffix(i, CLng(s)) 'look up the snumber and suffix
                        End If
                    End If
                End If
                i = i - 3 'reduce the suffix counter by 3 to step down to the next suffix
            Next
        End If
        Return output
    End Function

    Public Function FindNumber(ByVal Number As Long) As String
        Dim Words As String = Nothing
        Dim Digits() As String = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN",
      "EIGHT", "NINE", "TEN"}
        Dim Teens() As String = {"", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN",
       "EIGHTEEN", "NINETEEN"}

        If Number < 11 Then
            Words = Digits(Number)

        ElseIf Number < 20 Then
            Words = Teens(Number - 10)

        ElseIf Number = 20 Then
            Words = "TWENTY"

        ElseIf Number < 30 Then
            Words = "TWENTY " & Digits(Number - 20)

        ElseIf Number = 30 Then
            Words = "THIRTY"

        ElseIf Number < 40 Then
            Words = "THIRTY " & Digits(Number - 30)

        ElseIf Number = 40 Then
            Words = "FOURTY"

        ElseIf Number < 50 Then
            Words = "FOURTY " & Digits(Number - 40)

        ElseIf Number = 50 Then
            Words = "FIFTY"

        ElseIf Number < 60 Then
            Words = "FIFTY " & Digits(Number - 50)

        ElseIf Number = 60 Then
            Words = "SIXTY"

        ElseIf Number < 70 Then
            Words = "SIXTY " & Digits(Number - 60)

        ElseIf Number = 70 Then
            Words = "SEVENTY"

        ElseIf Number < 80 Then
            Words = "SEVENTY " & Digits(Number - 70)

        ElseIf Number = 80 Then
            Words = "EIGHTY"

        ElseIf Number < 90 Then
            Words = "EIGHTY " & Digits(Number - 80)

        ElseIf Number = 90 Then
            Words = "NINETY"

        ElseIf Number < 100 Then
            Words = "NINETY " & Digits(Number - 90)

        ElseIf Number < 1000 Then
            Words = Number.ToString
            Words = Words.Insert(1, ",")
            Dim wparts As String() = Words.Split(",")
            Words = FindNumber(wparts(0)) & " " & "HUNDRED"
            Dim n As String = FindNumber(wparts(1))
            If CLng(wparts(1)) <> 0 Then
                Words = Words & " AND " & n
            End If
        End If

        Return Words
    End Function

    Public Function FindSuffix(ByVal Length As Long, ByVal l As Long) As String
        Dim word As String

        If l <> 0 Then
            If Length > 12 Then
                word = "TRILLION"
            ElseIf Length > 9 Then
                word = "BILLION"
            ElseIf Length > 6 Then
                word = "MILLION"
            ElseIf Length > 3 Then
                word = "THOUSAND"
            ElseIf Length > 2 Then
                word = "HUNDRED"
            Else
                word = ""
            End If
        Else
            word = ""
        End If

        Return word
    End Function


End Module


