Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

Iniciado por Eleкtro, 18 Diciembre 2012, 22:23 PM

0 Miembros y 2 Visitantes están viendo este tema.

Eleкtro

Si el ejemplo del MSDN y otros ejemplos ya los habré intentado mil veces Novlucker :P

El código de ejemplo funciona, pero a la hora de intentar poner cualquier ejemplo en práctica con una clave creada por Windows Y CON LOS PERMISOS DENEGADOS... no tira ni a la de tres, al intentar abrir la clave siempre salta error de acceso ...incluso aunque primero se cambie el propietario actual de la clave y se cojan los permisos actuales con "GetAccessRights" ...que ni se pueden coger porque la clave no se puede abrir (opensubkey) por que no tiene permisos de lectura, de verdad que ese ejemplo del MSDN sirve para muy poco xD (segúramente yo esté fallando en algo).

un saludo








z3nth10n

#261
Esto lleva 3 días sin recibir Snippets! :o
Mala señal...




Eliminar duplicados de un ListBox

Se necesita un listbox, algunos elementos repetidos entre sí dentro de el y un botón.

Código (vbnet) [Seleccionar]
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       MsgBox(Eliminar(ListBox1) & " elementos duplicados en el List.", MsgBoxStyle.Information)
   End Sub

   Function Eliminar(ByVal LB As ListBox) As Int32
       Dim i As Int32
       Dim j As Int32
       Dim n As Int32 ' Recorre los items ( compara empezando desde el primero , de abajo hacia arriba)
       For i = 0 To LB.Items.Count - 2

           For j = LB.Items.Count - 1 To i + 1 Step -1 ' ... si es el mismo

               If LB.Items(i).ToString = LB.Items(j).ToString Then
                   LB.Items.RemoveAt(j) ' elimina el elemento indicando el índice
                   n += 1 'lleva la cuenta de los duplicados
               End If
           Next
       Next
       Return n ' retorna los eliminados
   End Function


Resultado:



PD: Este code lo he sacado de aquí: http://www.listeningonlineingles.com/2012/10/eliminar-duplicados-de-un-listbox-en.html

Pero está super ultra mega bug y yo lo he arreglado.

Un saludo.

Interesados hablad por Discord.

Eleкtro

#262
Cita de: Ikillnukes en 24 Julio 2013, 15:16 PM
Eliminar duplicados de un ListBox

Según como lo estás haciendo por cada item va a hacer casi un TRIPLE ciclo entero del resto de items del listbox, así que si hay 100 items hará como 250 checkeos distintos recorriendo casi todos los items del listbox, no lo he medido del todo pero más del doble si que es,
yo prefiero dejarle la lógica de comparar los items a algún método nativo...

Aquí va mi versión:

Código (vbnet) [Seleccionar]
#Region " [ListBox] Remove Duplicates "

   ' [ListBox] Remove Duplicates
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' RemoveDuplicates(ListBox1)

   Private Sub RemoveDuplicates(ByVal [Listbox] As ListBox)

       Dim ItemArray() As String = [Listbox].Items.Cast(Of String).Distinct().ToArray
       [Listbox].Items.Clear()
       [Listbox].Items.AddRange(ItemArray)

   End Sub

#End Region


Saludos!








z3nth10n


Interesados hablad por Discord.

Eleкtro

#264
CitarY si quiero saber cuantos están repes? :P

Usa la lógica y saca la diferencia:

Código (vbnet) [Seleccionar]
Dim DuplicateCount As Int32 = ([Listbox].Items.XXXXX - ItemArray.XXXXX)

· Donde "XXXXX" equivale a la propiedad que contiene el número total de items.






Eliminar duplicados de un array de string:

Código (vbnet) [Seleccionar]
#Region " Remove Array Duplicates "

   ' Remove Array Duplicates
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' Dim myarray(10) As String
   ' myarray(0) = "a" : myarray(1) = "b" : myarray(2) = "b" : myarray(3) = "a"
   ' myarray = RemoveDuplicates(myarray)

   Private Function RemoveDuplicates(ByVal Myarray() As String) As String()

       Array.Resize(Myarray, Myarray.Cast(Of String).Distinct().ToArray.LongLength - 1)
       Return Myarray

   End Function

#End Region








z3nth10n

Por increíble que parezca el Items.Count ha podido conmigo, ya te he enviado info con todo lo que he hecho y he probado :-\




Para no spamear meto un Snippete de camino:

Enviar Mails (Correos) desde un Form

Código (vbnet) [Seleccionar]
Imports System.Net.Mail
Public Class Form1
   Function SendEmail(ByVal Recipients As List(Of String), _
                     ByVal FromAddress As String, _
                     ByVal Subject As String, _
                     ByVal Body As String, _
                     ByVal UserName As String, _
                     ByVal Password As String, _
                     Optional ByVal Server As String = "smtp.gmail.com", _
                     Optional ByVal Port As Integer = 587, _
                     Optional ByVal Attachments As List(Of String) = Nothing) As String
       Dim Email As New MailMessage()
       Try
           Dim SMTPServer As New SmtpClient
           For Each Attachment As String In Attachments
               Email.Attachments.Add(New Attachment(Attachment))
           Next
           Email.From = New MailAddress(FromAddress)
           For Each Recipient As String In Recipients
               Email.To.Add(Recipient)
           Next
           Email.Subject = Subject
           Email.Body = Body
           SMTPServer.Host = Server
           SMTPServer.Port = Port
           SMTPServer.Credentials = New System.Net.NetworkCredential(UserName, Password)
           SMTPServer.EnableSsl = True
           SMTPServer.Send(Email)
           Email.Dispose()
           Return "Email to " & Recipients(0) & " from " & FromAddress & " was sent."
       Catch ex As SmtpException
           Email.Dispose()
           Return "Sending Email Failed. Smtp Error."
       Catch ex As ArgumentOutOfRangeException
           Email.Dispose()
           Return "Sending Email Failed. Check Port Number."
       Catch Ex As InvalidOperationException
           Email.Dispose()
           Return "Sending Email Failed. Check Port Number."
       End Try
   End Function
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
       Dim Recipients As New List(Of String)
       Recipients.Add("SomeEmailAddress")
       Dim FromEmailAddress As String = Recipients(0)
       Dim Subject As String = "Test From VB."
       Dim Body As String = "email body text, if you are reading this from your gmail account, the program worked."
       Dim UserName As String = "GMAIL USERNAME WITHOUT  (@GMAIL>COM)"
       Dim Password As String = "Password"
       Dim Port As Integer = 587
       Dim Server As String = "smtp.gmail.com"
       Dim Attachments As New List(Of String)
       MsgBox(SendEmail(Recipients, FromEmailAddress, Subject, Body, UserName, Password, Server, Port, Attachments))
   End Sub
End Class


Ale, ponte a optimizar xD :laugh:




Si hay algo que optimizar, luego pongo alguna especie de conversor de Html Entities y en el Body ("email body text, if you are reading this from your gmail account, the program worked.") se tunea un poco. :P

Un saludo.

Interesados hablad por Discord.

Eleкtro

#266
Comprobar si un archivo es un archivo de registro válido (version 5.0)

Código (vbnet) [Seleccionar]
#Region " Is Registry File "

   ' [ Is Registry File Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' MsgBox(IsRegFile("C:\RegistryFile.reg"))

   ' IsRegistryFile
   Private Function IsRegFile(ByVal RegistryFile As String) As Boolean

       Dim Regedit_Signature As String = "windows registry editor version 5.00"
       Return IO.File.ReadAllText(RegistryFile).ToLower.Trim.StartsWith(Regedit_Signature)

   End Function

#End Region







El núcleo de mi programa REG2BAT, mejorado para soportar caracteres inválidos por Batch (para escaparlos)

Código (vbnet) [Seleccionar]
   #Region " Reg2Bat "
   
      ' [ Reg2Bat Function ]
      '
      ' // By Elektro H@cker
      '
      ' Examples :
      ' MsgBox(Reg2Bat("C:\Registry.reg"))

    Public Enum REG2BAT_Format As Int16
        BINARY = 1
        DWORD = 2
        QWORD = 3
        EXPAND_SZ = 4
        MULTI_SZ = 5
        REG_SZ = 0
    End Enum

    ' Reg2Bat
    Private Function Reg2Bat(ByVal Reg_File As String) As String

        ' Source Input
        ' Join he lines, delete the Regedit linebreaks characters: "\  ", and then split the lines.
        Dim RegFile() As String = Split( _
                                  String.Join("@@@Reg2Bat@@@", IO.File.ReadAllLines(Reg_File)) _
                                  .Replace("\@@@Reg2Bat@@@  ", "") _
                                  .Replace("@@@Reg2Bat@@@", Environment.NewLine), _
                                  Environment.NewLine)

        Dim RegLine As String = String.Empty ' Where the Regedit Line will be stored.
        Dim RegKey As String = String.Empty ' Where the Regedit Key will be stored.
        Dim RegVal As String = String.Empty ' Where the Regedit Value will be stored.
        Dim RegData As String = String.Empty ' Where the Regedit Data will be stored.

        Dim Batch_Commands As String = String.Empty ' Where the decoded Regedit strings will be stored.

        Batch_Commands &= ":: Converted with REG2BAT by Elektro H@cker"
        Batch_Commands &= Environment.NewLine & Environment.NewLine
        Batch_Commands &= "@Echo OFF"
        Batch_Commands &= Environment.NewLine & Environment.NewLine

        ' Start reading the Regedit File
        For X As Int64 = 0 To RegFile.LongLength - 1

            RegLine = RegFile(X).Trim

            Select Case True

                Case RegLine.StartsWith(";") ' Comment line

                    Batch_Commands &= Environment.NewLine
                    Batch_Commands &= String.Format("REM {0}", RegLine.Substring(1, RegLine.Length - 1).Trim)
                    Batch_Commands &= Environment.NewLine

                Case RegLine.StartsWith("[-") ' Key to delete

                    RegKey = RegLine.Substring(2, RegLine.Length - 3).Trim
                    Batch_Commands &= String.Format("REG DELETE ""{0}"" /F", RegKey)
                    Batch_Commands &= Environment.NewLine

                Case RegLine.StartsWith("[") ' Key to add

                    RegKey = RegLine.Substring(1, RegLine.Length - 2).Trim
                    Batch_Commands &= String.Format("REG ADD ""{0}"" /F", RegKey)
                    Batch_Commands &= Environment.NewLine

                Case RegLine.StartsWith("@=") ' Default Value to add

                    RegData = Split(RegLine, "@=", , CompareMethod.Text).Last
                    Batch_Commands &= String.Format("REG ADD ""{0}"" /V  """" /D {1} /F", RegKey, RegData)
                    Batch_Commands &= Environment.NewLine

                Case RegLine.StartsWith("""") _
                AndAlso RegLine.Split("=").Last = "-"  ' Value to delete

                    RegVal = RegLine.Substring(1, RegLine.Length - 4)
                    Batch_Commands &= String.Format("REG DELETE ""{0}"" /V ""{1}"" /F", RegKey, RegVal)
                    Batch_Commands &= Environment.NewLine

                Case RegLine.StartsWith("""") ' Value to add

                    ' Check data type:
                    Select Case RegLine.Split("=")(1).Split(":")(0).ToLower

                        Case "hex" ' Binary

                            RegVal = Format_Regedit_String(Get_Regedit_Value(RegLine, REG2BAT_Format.BINARY))
                            RegData = Get_Regedit_Data(RegLine, REG2BAT_Format.BINARY)
                            Batch_Commands &= String.Format("REG ADD ""{0}"" /V ""{1}"" /T ""REG_BINARY"" /D ""{2}"" /F", RegKey, RegVal, RegData)
                            Batch_Commands &= Environment.NewLine

                        Case "dword" ' DWORD (32 bit)

                            RegVal = Format_Regedit_String(Get_Regedit_Value(RegLine, REG2BAT_Format.DWORD))
                            RegData = Get_Regedit_Data(RegLine, REG2BAT_Format.DWORD)
                            Batch_Commands &= String.Format("REG ADD ""{0}"" /V ""{1}"" /T ""REG_DWORD"" /D ""{2}"" /F", RegKey, RegVal, RegData)
                            Batch_Commands &= Environment.NewLine

                        Case "hex(b)" ' QWORD (64 bIT)

                            RegVal = Format_Regedit_String(Get_Regedit_Value(RegLine, REG2BAT_Format.QWORD))
                            RegData = Get_Regedit_Data(RegLine, REG2BAT_Format.QWORD)
                            Batch_Commands &= String.Format("REG ADD ""{0}"" /V ""{1}"" /T ""REG_QWORD"" /D ""{2}"" /F", RegKey, RegVal, RegData)
                            Batch_Commands &= Environment.NewLine

                        Case "hex(2)"  ' EXPAND SZ

                            RegVal = Format_Regedit_String(Get_Regedit_Value(RegLine, REG2BAT_Format.EXPAND_SZ))
                            RegData = Format_Regedit_String(Get_Regedit_Data(RegLine, REG2BAT_Format.EXPAND_SZ))
                            Batch_Commands &= String.Format("REG ADD ""{0}"" /V ""{1}"" /T ""REG_EXPAND_SZ"" /D ""{2}"" /F", RegKey, RegVal, RegData)
                            Batch_Commands &= Environment.NewLine

                        Case "hex(7)" ' MULTI SZ

                            RegVal = Format_Regedit_String(Get_Regedit_Value(RegLine, REG2BAT_Format.MULTI_SZ))
                            RegData = Format_Regedit_String(Get_Regedit_Data(RegLine, REG2BAT_Format.MULTI_SZ))
                            Batch_Commands &= String.Format("REG ADD ""{0}"" /V ""{1}"" /T ""REG_MULTI_SZ"" /D ""{2}"" /F", RegKey, RegVal, RegData)
                            Batch_Commands &= Environment.NewLine

                        Case Else ' REG SZ

                            RegVal = Format_Regedit_String(Get_Regedit_Value(RegLine, REG2BAT_Format.REG_SZ))
                            RegData = Format_Regedit_String(Get_Regedit_Data(RegLine, REG2BAT_Format.REG_SZ))
                            Batch_Commands &= String.Format("REG ADD ""{0}"" /V ""{1}"" /T ""REG_SZ"" /D ""{2}"" /F", RegKey, RegVal, RegData)
                            Batch_Commands &= Environment.NewLine

                    End Select

            End Select

        Next

        Return Batch_Commands

    End Function

    ' Get Regedit Value
    Private Function Get_Regedit_Value(ByVal Line As String, ByVal REG2BAT_Format As REG2BAT_Format) As String

        Dim str As String = Nothing

        Select Case REG2BAT_Format

            Case REG2BAT_Format.BINARY : str = Split(Line, "=hex:", , CompareMethod.Text).First
            Case REG2BAT_Format.DWORD : str = Split(Line, "=dword:", , CompareMethod.Text).First
            Case REG2BAT_Format.QWORD : str = Split(Line, "=hex(b):", , CompareMethod.Text).First
            Case REG2BAT_Format.EXPAND_SZ : str = Split(Line, "=Hex(2):", , CompareMethod.Text).First
            Case REG2BAT_Format.MULTI_SZ : str = Split(Line, "=Hex(7):", , CompareMethod.Text).First
            Case REG2BAT_Format.REG_SZ : str = Split(Line, """=""", , CompareMethod.Text).First
            Case Else : Return Nothing

        End Select

        If str.StartsWith("""") Then str = str.Substring(1, str.Length - 1)
        If str.EndsWith("""") Then str = str.Substring(0, str.Length - 1)
        Return str

    End Function

    ' Get Regedit Data
    Private Function Get_Regedit_Data(ByVal Line As String, ByVal REG2BAT_Format As REG2BAT_Format) As String

        Dim Data As String = Nothing

        Select Case REG2BAT_Format

            Case REG2BAT_Format.BINARY
                Return Split(Line, (Split(Line, "=hex:", , CompareMethod.Text).First & "=hex:"), , CompareMethod.Text).Last.Replace(",", "")

            Case REG2BAT_Format.DWORD
                Return "0x" & Split(Line, (Split(Line, "=dword:", , CompareMethod.Text).First & "=dword:"), , CompareMethod.Text).Last.Replace(",", "")

            Case REG2BAT_Format.QWORD
                Line = StrReverse(Split(Line, (Split(Line, "=hex(b):", , CompareMethod.Text).First & "=hex(b):"), , CompareMethod.Text).Last.Replace(",", ""))
                For Each [byte] In Line.Split(",") : Data &= StrReverse([byte]) : Next
                Return Data

            Case REG2BAT_Format.EXPAND_SZ
                Line = Split(Line, (Split(Line, "=Hex(2):", , CompareMethod.Text).First & "=hex(2):"), , CompareMethod.Text).Last.Replace(",00", "").Replace("00,", "")
                For Each [byte] In Line.Split(",") : Data &= Chr(Val("&H" & [byte])) : Next
                Return Data.Replace("""", "\""")

            Case REG2BAT_Format.MULTI_SZ

                Line = Split(Line, (Split(Line, "=Hex(7):", , CompareMethod.Text)(0) & "=hex(7):"), , CompareMethod.Text).Last.Replace(",00,00,00", ",\0").Replace(",00", "").Replace("00,", "")

                For Each [byte] In Line.Split(",")

                    If [byte] = "\0" Then
                        Data &= "\0" ' Line separator for multiline.
                    Else
                        Data &= Chr(Val("&H" & [byte]))
                    End If

                Next

                Return Data.Replace("""", "\""")

            Case REG2BAT_Format.REG_SZ
                Data = Split(Line, (Split(Line, """=""", , CompareMethod.Text)(0) & """="""), , CompareMethod.Text).Last
                Data = Data.Substring(0, Data.Length - 1)
                Return Data

            Case Else
                Return Nothing

        End Select

    End Function

    ' Format Regedit String
    Private Function Format_Regedit_String(ByVal str As String) As String

        str = str.Replace("%", "%%")
        If Not str.Contains("""") Then Return str

        str = str.Replace("\""", """")

        Dim strArray() As String = str.Split("""")

        For num As Long = 1 To strArray.Length - 1 Step 2

            strArray(num) = strArray(num).Replace("^", "^^") ' This replace need to be THE FIRST.
            strArray(num) = strArray(num).Replace("<", "^<")
            strArray(num) = strArray(num).Replace(">", "^>")
            strArray(num) = strArray(num).Replace("|", "^|")
            strArray(num) = strArray(num).Replace("&", "^&")
            ' strArray(num) = strArray(num).Replace("\", "\\")

        Next

        Return String.Join("\""", strArray)

    End Function
   
   #End Region








The_Saint

EleKtro H@cker
Espectacular el curro que te has pegado con los snippets  ;-)
<< Si piensas que eres demasiado pequeño para tener impacto.
Prueba a irte a la cama con un mosquito>>

z3nth10n

#268
Seguro que cuando Elektro ha visto que un tal H_MUDA ha comentado, ha pensado, NUEVOS SNIPPETS! jajaja Yo también me he llevado una decepción. '--




Crear String random:

Código (vbnet) [Seleccionar]
Imports System.Text

Public Class Form1

Function Randomize() 'Fuck the police
       Dim s As String = "abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" 'Aquí se define los caracteres que se van a mostrar
       Dim r As New Random 'Se declara la Class Random
       Dim sb As New StringBuilder 'Se declarar la Class StingBuilder
       For i As Integer = 1 To 8 'Aquí se llama al ciclo For; el 8 representa el numero de caracteres en la cadena
           Dim idx As Integer = r.Next(0, 35) 'Esto no se muy bien que hace xD
           sb.Append(s.Substring(idx, 1)) 'Y esto lo muestra?
       Next
       Return sb.ToString 'Esto lo returna para que luego en el MsgBox salga el valor correcto
   End Function

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'Evento de un botón, por poner algún evento

       Dim Max As Integer = 10 'Aquí el numero de MsgBox a mostrar

       For i As Integer = 0 To Max 'Aquí se llama al ciclo For
           MsgBox(Randomize()) 'Aquí se muestran las MsgBox
       Next

   End Sub

End Class


Con esto voy a poder hacer muchas, pero que muchas troleadas :P

Un saludo.




Extra en PHP, para que Elektro aprenda:

Código (php) [Seleccionar]
function rand_string($length) {
       $str = ""; //Por si no quieres ningún E_NOTICE por culero. :P
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //Aquí se define los caracteres que se van a mostrar

$size = strlen($chars); //Aquí se devuelve la longitud del string dado
for($i = 0; $i < $length; $i++) { //Un ciclo For de toda la vida
$str .= $chars[rand(0, $size - 1)]; //Aquí se muestra, el equivalente en mi función de VB.NET sería Dim idx As Integer = r.Next(0, 35); pero aquí no se necesita ningún sb.Append(...) :P
}

return $str; //Aquí se returna para luego mostrarla con un Echo
}

echo rand_string(8); //Aquí se muestra con una longitud de 8 caracteres...

//Ejemplo: http://phpfiddle.org/main/code/7rx-rnp


Ejemplo: http://phpfiddle.org/main/code/7rx-rnp ;)

:laugh: :laugh: :laugh: :laugh:

PD: Espero que sepas agradecer la molestia que me he tomado.. :P

Interesados hablad por Discord.

Eleкtro

#269
Me parece indignante leer comentarios de tus codes como "esto no tengo ni p**a idea de para q sirve", etc...

En el code de VB un fallo muy grave:
Código (vbnet) [Seleccionar]
r.Next(0, 35) 'Esto no se muy bien que hace xD

Claro, que como de costumbre no te has molestado en buscar que coño significa, pus asi vas.

Significa que el número se va a generar desde el 0 hasta el 35, pero tu cadena de caracteres tiene una longitud de 62 caracteres...con lo cual no es nada aleatorio, ya que sólo escojerá entre los primeros 35 digitos...

En cambio en el code de PHP es correcto porque priméramente se obtiene la longitud de la cadena (variable $size) para usarlo como margen total del número random, cosa que no haces en VB y no sabes ni para que sirve pero en PHP si que lo haces así que debemos suponer que en PHP si que sabes para que sirve cuando ex exáctamente lo mismo?...

Código (php) [Seleccionar]
rand(0, $size - 1)

...Así que doy por supuesto que usas copy/paste para todos los lenguajes sin enterarte de nada de lo que haces, es algo que se nota a simple vista, y me parece muy mal Ikillnukes, y como he dicho, indignante, para serte aún más sincero no me extraña que algunas personas se enfaden cuando presumes de saber un lenguaje, no eres quien para llamar noobs a los que no saben PHP, porque viendo esto... tu no eres más, intenta ser un poco más humilde.

PD: A cualquiera que se haga llamar programador le molestaría darse cuenta de las cosas que me doy cuenta yo día a día contigo. Sabes o espero que sepas que no te tengo mania, pero yo estas cosas no las tolero.

Aparte de eso, no estás definiendo el tipo de valor que devuelves en la función, pero bueno, eso es una minucia comparado con lo que verdaderamente importa.

En fin, aquí tienes mi versión con dicho error corregido, ale, a copiar se ha dicho... :

Código (vbnet) [Seleccionar]
   Private Function Random_String(ByVal Length As Int32, _
                                  Optional ByVal Characters As String = _
                                  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" _
                                 ) As String

       Select Case Length

           Case Is < 1 ' Is 0 or negative
               Throw New Exception("Length must be greater than 0")

           Case Else ' Is greater than 0

               Dim str As String = String.Empty
               Dim rand As New Random, rand_length As Int32 = Characters.Length

               Do Until str.Length = Length
                   str &= Characters.Substring(rand.Next(0, rand_length), 1)
               Loop

               Return str

       End Select

   End Function


PD2: Quizás sea beneficioso crear un método parecido pero usando LINQ para procesar más rápido cadenas extremádamente largas.