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

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

0 Miembros y 1 Visitante están viendo este tema.

Eleкtro

#280
Una Class para manipular el archivo Hosts:

Código (vbnet) [Seleccionar]
#Region " Hosts Helper "

Public Class Hosts_Helper


    ' [ Hosts Helper ]
    '
    ' // By Elektro H@cker
    '
    ' Examples:
    '
    ' MsgBox(Hosts_Helper.HOSTS_Exists)
    ' Hosts_Helper.Add("www.youtube.com", "231.7.66.33")
    ' Hosts_Helper.Block("www.youtube.com")
    ' MsgBox(Hosts_Helper.IsAdded("www.youtube.com"))
    ' MsgBox(Hosts_Helper.IsBlocked("www.youtube.com"))
    ' Hosts_Helper.Remove("www.youtube.com")
    ' Hosts_Helper.Clean_Hosts_File()


    Shared ReadOnly HOSTS As String = _
    IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "Drivers\etc\hosts")


    ''' <summary>
    ''' Adds a new Block mapping into the Hosts file.
    ''' </summary>
    Public Shared Sub Block(ByVal URL As String)

        Dim Entry As String = String.Format("::1 {0}", URL)

        If HOSTS_Exists() AndAlso IsBlocked(URL) Then

            Throw New Exception(String.Format("""{0}"" is already blocked.", URL))
            Exit Sub

        ElseIf HOSTS_Exists() AndAlso IsAdded(URL) Then

            Remove(URL)

        End If

        Try
            IO.File.AppendAllText(HOSTS, (Environment.NewLine & Entry), System.Text.Encoding.Default)
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try

    End Sub


    ''' <summary>
    ''' Adds a new mapping into Hosts file.
    ''' </summary>
    Public Shared Sub Add(ByVal URL As String, ByVal IP_Address As String)

        Dim Entry As String = String.Format("{0} {1}", IP_Address, URL)

        If HOSTS_Exists() AndAlso (IsAdded(URL) OrElse IsBlocked(URL)) Then
            Throw New Exception(String.Format("""{0}"" is already mapped.", URL))
            Exit Sub

        ElseIf Not Validate_IP(IP_Address) Then
            Throw New Exception(String.Format("""{0}"" is not a valid IP adress.", IP_Address))
            Exit Sub
        End If

        Try
            IO.File.AppendAllText(HOSTS, (Environment.NewLine & Entry), System.Text.Encoding.Default)
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try

    End Sub


    ''' <summary>
    ''' Removes a blocked or an added URL from the Hosts file.
    ''' </summary>
    Public Shared Sub Remove(ByVal URL As String)

        If Not HOSTS_Exists() Then
            Throw New Exception("HOSTS File does not exists.")
            Exit Sub
        ElseIf HOSTS_Exists() And Not (IsAdded(URL) OrElse IsBlocked(URL)) Then
            Throw New Exception(String.Format("""{0}"" is not added yet.", URL))
            Exit Sub
        End If

        Try

            Dim Content As String = _
                System.Text.RegularExpressions.Regex.Replace(IO.File.ReadAllText(HOSTS).ToLower, _
                String.Format("(\d{{1,3}}\.\d{{1,3}}\.\d{{1,3}}\.\d{{1,3}}|::1)(\s+|\t+){0}", URL.ToLower), String.Empty)

            IO.File.WriteAllText(HOSTS, Content, System.Text.Encoding.Default)

        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try

    End Sub


    ''' <summary>
    ''' Checks if an URL is already added into the Hosts file.
    ''' </summary>
    Public Shared Function IsAdded(ByVal URL As String) As Boolean

        Return If(Not HOSTS_Exists(), False, _
                  System.Text.RegularExpressions.Regex.IsMatch( _
                  System.Text.RegularExpressions.Regex.Replace(IO.File.ReadAllText(HOSTS).ToLower, "\s+|\t+", ";"), _
                  String.Format(";[^\#]?\d{{1,3}}\.\d{{1,3}}\.\d{{1,3}}\.\d{{1,3}};{0}", URL.ToLower)))

    End Function


    ''' <summary>
    ''' Checks if an URL is already blocked into the Hosts file.
    ''' </summary>
    Public Shared Function IsBlocked(ByVal URL As String) As Boolean

        Return If(Not HOSTS_Exists(), False, _
                  System.Text.RegularExpressions.Regex.IsMatch( _
                  System.Text.RegularExpressions.Regex.Replace(IO.File.ReadAllText(HOSTS).ToLower, "\s+|\t+", String.Empty), _
                  String.Format("[^\#](127.0.0.1|::1){0}", URL.ToLower)))

    End Function


    ''' <summary>
    ''' Checks if the Hosts file exists.
    ''' </summary>
    Public Shared Function HOSTS_Exists() As Boolean
        Return IO.File.Exists(HOSTS)
    End Function


    ''' <summary>
    ''' Cleans all the mappings inside the Hosts file.
    ''' </summary>
    Public Shared Sub Clean_Hosts_File()
        Try
            IO.File.WriteAllText(HOSTS, String.Empty)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub


    ' Validates an IP adress.
    Private Shared Function Validate_IP(ByVal IP_Address As String) As Boolean
        Dim IP As System.Net.IPAddress = Nothing
        Return System.Net.IPAddress.TryParse(IP_Address, IP)
    End Function

End Class

#End Region








Eleкtro

#281
Obtener la diferencia (personalizada) entre dos fechas:

#Region " Date Difference "
   
      ' Date Difference
      '
      ' // By Elektro H@cker
      '
      ' Examples :
      '
      ' MsgBox(DateDifference(DateTime.Parse("01/03/2013"), DateTime.Parse("10/04/2013"))) ' Result: 1 Months, 1 Weeks, 2 Days, 0 Hours, 0 Minutes and 0 Seconds
      ' MsgBox(DateDifference(DateTime.Parse("01/01/2013 14:00:00"), DateTime.Parse("02/01/2013 15:00:30"))) ' Result: 0 Months, 0 Weeks, 1 Days, 1 Hours, 0 Minutes and 30 Seconds
   
      Private Function DateDifference(ByVal Date1 As DateTime, ByVal Date2 As DateTime) As String
   
          Dim MonthDiff As String, WeekDiff As String, _
              DayDiff As String, HourDiff As String, _
              MinuteDiff As String, SecondDiff As String
   
          MonthDiff = Convert.ToString(DateDiff("M", Date1, Date2))
          WeekDiff = Convert.ToString(DateDiff("d", Date1.AddMonths(DateDiff("M", Date1, Date2)), Date2) \ 7)
          DayDiff = Convert.ToString(DateDiff("d", Date1.AddMonths(DateDiff("M", Date1, Date2)), Date2) - (WeekDiff * 7))
          HourDiff = Convert.ToString(DateDiff("h", Date1.AddHours(DateDiff("h", Date1, Date2)), Date2) - (Date1.Hour - Date2.Hour))
          MinuteDiff = Convert.ToString(DateDiff("n", Date1.AddMinutes(DateDiff("n", Date1, Date2)), Date2) - (Date1.Minute - Date2.Minute))
          SecondDiff = Convert.ToString(DateDiff("s", Date1.AddSeconds(DateDiff("s", Date1, Date2)), Date2) - (Date1.Second - Date2.Second))
   
          Return String.Format("{0} Months, {1} Weeks, {2} Days, {3} Hours, {4} Minutes and {5} Seconds", _
                               MonthDiff, WeekDiff, DayDiff, HourDiff, MinuteDiff, SecondDiff)
   
      End Function
   
   #End Region


Corregido:
Código (vbnet) [Seleccionar]
#Region " Date Difference "

   ' Date Difference
   '
   ' Examples :
   '
   ' MsgBox(DateDifference(DateTime.Parse("01/03/2013"), DateTime.Parse("10/04/2013"))) ' Result: 1 Months, 1 Weeks, 2 Days, 0 Hours, 0 Minutes and 0 Seconds
   ' MsgBox(DateDifference(DateTime.Parse("01/01/2013 14:00:00"), DateTime.Parse("02/01/2013 15:00:30"))) ' Result: 0 Months, 0 Weeks, 1 Days, 1 Hours, 0 Minutes and 30 Seconds

   Private Function DateDifference(ByVal Date1 As DateTime, ByVal Date2 As DateTime) As String

       Dim Time As TimeSpan
       Dim MonthDiff As Integer, WeekDiff As Integer

       Do Until Date1 > Date2
           Date1 = Date1.AddMonths(1)
           MonthDiff += 1
       Loop

       MonthDiff -= 1
       Date1 = Date1.AddMonths(-1)
       Time = (Date2 - Date1)
       WeekDiff = (Time.Days \ 7)
       Time = (Time - TimeSpan.FromDays(WeekDiff * 7))

       Return String.Format("{0} Months, {1} Weeks, {2} Days, {3} Hours, {4} Minutes and {5} Seconds", _
                            MonthDiff, WeekDiff, Time.Days, Time.Hours, Time.Minutes, Time.Seconds)

   End Function

#End Region








Eleкtro

Unos tips que he codeado sobre el manejo de una lista de Tuplas, de una lista de FIleInfo, y sobre la utilización de algunas extensiones de LINQ:

PD: Es muy bueno aprender todos estos métodos para dejar en el olvido a los FOR.


List(Of Tuple)
Código (vbnet) [Seleccionar]
        ' Create the list:
        Dim TupleList As New List(Of Tuple(Of String, Boolean, Integer)) ' From {Tuple.Create("Hello world", True, 1)}

        ' Add an Item:
        TupleList.Add(Tuple.Create("Elektro", False, 0))
        TupleList.Add(Tuple.Create("H@cker", True, 1))

        ' Order the TupleList by a Tuple item:
        TupleList = TupleList.OrderBy(Function(Tuple) Tuple.Item3).ToList

        ' Sort the TupleList by a Tuple item:
        TupleList.Sort( _
        Function(Comparer_A As Tuple(Of String, Boolean, Integer), _
                 Comparer_B As Tuple(Of String, Boolean, Integer)) _
                 Comparer_A.Item3.CompareTo(Comparer_B.Item3))

        ' Filter the list by items equals as "True" in their Tuple second item:
        TupleList = TupleList.Where(Function(Tuple) Tuple.Item2 = True).ToList

        ' Display a Tuple item from a list item:
        MsgBox(TupleList.Item(0).Item2)

        ' Looping the list:
        For Each Item As Tuple(Of String, Boolean, Integer) In TupleList
            MsgBox(Item.Item1)
        Next



List(Of FileInfo)
Código (vbnet) [Seleccionar]
        ' Create the list:
        Dim Files As List(Of IO.FileInfo) = IO.Directory.GetFiles("C:\", "*") _
        .Select(Function(ToFileInfo) New IO.FileInfo(ToFileInfo)).ToList

        ' Add an Item:
        Files.Add(New IO.FileInfo("C:\Windows\Notepad.exe"))

        ' Order the list by a file property:
        Files = Files.OrderBy(Function(File) File.Extension).ToList

        ' Sort the list by a file property:
        Files.Sort( _
        Function(Comparer_A As IO.FileInfo, Comparer_B As IO.FileInfo) _
                 Comparer_A.Extension.CompareTo(Comparer_B.Extension))
                 
        ' Filter the list by files containing "note" word in their filename:
        Files = Files.Where(Function(File) File.Name.ToLower.Contains("note")).ToList

        ' Display a file property from a list item:
        MsgBox(Files.Item(0).FullName)

        ' Looping the list:
        For Each File As IO.FileInfo In Files
            MsgBox(File.FullName)
        Next








Eleкtro

Convierte una fecha a formato de fecha Unix

Código (vbnet) [Seleccionar]
#Region " DateTime To Unix "

    ' [ DateTime To Unix Function ]
    '
    ' Examples :
    '
    ' MsgBox(DateTime_To_Unix(DateTime.Parse("01/01/2013 12:00:00"))) ' Result: 1357041600

    Public Function DateTime_To_Unix(ByVal DateTime As DateTime) As Long
        Return DateDiff(DateInterval.Second, #1/1/1970#, DateTime)
    End Function

#End Region


Convierte formato de fecha Unix a Fecha normal.

Código (vbnet) [Seleccionar]
#Region " Unix To DateTime "

    ' [ Unix To DateTime Function ]
    '
    ' Examples :
    '
    ' MsgBox(Unix_To_DateTime(1357041600)) ' Result: 01/01/2013 12:00:00

    Public Function Unix_To_DateTime(ByVal UnixTime As Long) As DateTime
        Return DateAdd(DateInterval.Second, UnixTime, #1/1/1970#)
    End Function

#End Region








Eleкtro

Una función para convertir entre tasas de transferencia de telecomunicaciones y tasas de transferencia de datos, es decir, entre Bp/s y B/s.

PD: En este snippet @IkillNukes me ha ayudado con los cálculos matemáticos de las enumeraciones, que me daban ciertos problemas.

Código (vbnet) [Seleccionar]
#Region " Telecommunication Bitrate To DataStorage Bitrate "

   ' [ Base64 To String Function ]
   '
   ' // By Elektro H@cker & IKillNukes
   '
   ' Examples :
   '
   ' MsgBox(Telecommunication_Bitrate_To_DataStorage_Bitrate(365, _
   '        Telecommunications_Bitrates.Kilobips, _
   '        DataStorage_Bitrates.Kilobytes)) ' Result: 45
   '
   ' MsgBox(Telecommunication_Bitrate_To_DataStorage_Bitrate(365, _
   '        Telecommunications_Bitrates.Kilobips, _
   '        DataStorage_Bitrates.Kilobytes)) ' Result: 45,625

   Private Enum Telecommunications_Bitrates As Long
       Bips = 1 ' bit/s
       Kilobips = 1000 ' bit/s
       Megabips = 1000000 ' bit/s
       Gigabips = 1000000000 ' bit/s
       Terabips = 1000000000000 ' bit/s
   End Enum

   Private Enum DataStorage_Bitrates As Long
       Bytes = 8 ' bits
       Kilobytes = 8000 ' bits
       Megabytes = 8000000 ' bits
       Gigabytes = 8000000000 ' bits
       Terabytes = 8000000000000  ' bits
   End Enum

   Private Function Telecommunication_Bitrate_To_DataStorage_Bitrate( _
                      ByVal BitRate As Single, _
                      ByVal Telecommunications_Bitrates As Telecommunications_Bitrates, _
                      ByVal DataStorage_Bitrates As DataStorage_Bitrates, _
                      Optional ByVal Rounded As Boolean = True
                    ) As Single

       Return IIf(Rounded, _
                  (BitRate * Telecommunications_Bitrates) \ DataStorage_Bitrates, _
                  (BitRate * Telecommunications_Bitrates) / DataStorage_Bitrates)

   End Function

#End Region








Eleкtro

#285
Una función para abreviar cantidades de dinero al estilo americano.

PD: He preguntado a gente americana como son las abreviaturas para cifras más grandes de un Trillón pero al parecer no existen abreviaturas Standards, así que me las he inventado un poco basándome en el nombre de las cantidades. http://ell.stackexchange.com/questions/9123/money-abbreviations

EDITO: Corregido la ubicación del caracter del dolar, parece ser que se pone a la izquierda de la cantidad, no a la derecha.
Código (vbnet) [Seleccionar]
    #Region " Money Abbreviation "
     
       ' [ Money Abbreviation Function ]
       '
       ' // By Elektro H@cker
       '
       ' Examples :
       '
       ' MsgBox(Money_Abbreviation(1000))           ' Result: 1 K
       ' MsgBox(Money_Abbreviation(1000000))        ' Result: 1 M
       ' MsgBox(Money_Abbreviation(1500000, False)) ' Result: 1,5 M
     
       Private Function Money_Abbreviation(ByVal Quantity As Object, _
                                           Optional ByVal Rounded As Boolean = True) As String
     
           Dim Abbreviation As String = String.Empty
     
           Select Case Quantity.GetType()
     
               Case GetType(Int16), GetType(Int32), GetType(Int64)
                   Quantity = FormatNumber(Quantity, TriState.False)
     
               Case Else
                   Quantity = FormatNumber(Quantity, , TriState.False)
     
           End Select
     
           Select Case Quantity.ToString.Count(Function(character As Char) character = Convert.ToChar("."))
     
               Case 0 : Return String.Format("${0}", Quantity)
               Case 1 : Abbreviation = "k"
               Case 2 : Abbreviation = "M"
               Case 3 : Abbreviation = "B"
               Case 4 : Abbreviation = "Tr."
               Case 5 : Abbreviation = "Quad."
               Case 6 : Abbreviation = "Quint."
               Case 7 : Abbreviation = "Sext."
               Case 8 : Abbreviation = "Sept."
               Case Else
                   Return String.Format("${0}", Quantity)
     
           End Select
     
           Return IIf(Rounded, _
                  String.Format("{0} {1}", StrReverse(StrReverse(Quantity).Substring(StrReverse(Quantity).LastIndexOf(".") + 1)), Abbreviation), _
                  String.Format("{0} {1}", StrReverse(StrReverse(Quantity).Substring(StrReverse(Quantity).LastIndexOf(".") - 1)), Abbreviation))
     
       End Function
     
    #End Region







Contar la cantidad de coincidencias de un caracter dentro de un string.

Código (vbnet) [Seleccionar]
#Region " Count Character "

   ' [ Count Character Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' MsgBox(Count_Character("Elektro", "e"))       ' Result: 1
   ' MsgBox(Count_Character("Elektro", "e", True)) ' Result: 2

   Public Function Count_Character(ByVal str As String, ByVal character As Char, _
                                   Optional ByVal IgnoreCase As Boolean = False) As Integer

       Return IIf(IgnoreCase, _
                  str.ToLower.Count(Function(c As Char) c = Convert.ToChar(character.ToString.ToLower)), _
                  str.Count(Function(c As Char) c = character))

   End Function

#End Region








Eleкtro

#286
Este código devuelve la cantidad de coincidencias de un String en los valores de un Array:

Código (vbnet) [Seleccionar]
#Region " Count Array Matches "

   ' [ Count Array Matches ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
    ' MsgBox(Count_Array_Matches({"a", "b", "c", "d", "d", "d"}, "d")) ' Result: 3

    Private Function Count_Array_Matches(ByVal Collection As String(), _
                                         ByVal Match As String, ByVal _
                                         IgnoreCase As Boolean) As Integer

        Return IIf(IgnoreCase, _
                  Collection.Where(Function(str) str.ToLower = Match.ToLower).Count, _
                  Collection.Where(Function(str) str = Match).Count)

    End Function

#End Region







Este código elimina los valores únicos de un array:

Código (vbnet) [Seleccionar]
#Region " Delete Array Unique Names "

   ' [ Delete Array Unique Names ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' Dim MyArray as String() = Delete_Unique_Values_In_Array({"a", "b", "c", "d", "d", "d"}) ' Result: {"d", "d", "d"}

   Private Function Delete_Unique_Values_In_Array(ByVal Collection As String()) As String()
       Return Collection.GroupBy(Function(x) x) _
       .Where(Function(x) x.Count() > 1) _
       .SelectMany(Function(x) x) _
       .ToArray()
   End Function

#End Region


PD: No está muy optimizado pero para Arrays pequeños no se aprecia nada el performance.








Eleкtro

#287
Contar las líneas en blanco o valores vacios de un array usando LINQ:


Código (vbnet) [Seleccionar]
MsgBox(RichTextBox1.Lines.Where(Function(Line) String.IsNullOrEmpty(Line)).Count)

MsgBox({"a", "", "", "b"}.Where(Function(value) String.IsNullOrEmpty(value)).Count)



EDITO:

Unas funciones genéricas muy cortas:

Código (vbnet) [Seleccionar]
#Region " Count Blank Lines "

   ' [ Count Blank Lines ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(Count_Blank_Lines(RichTextBox1.Lines))
   ' MsgBox(Count_Blank_Lines({"A", "", "", "B"})) ' Result: 2

   Private Function Count_Blank_Lines(ByVal str As String()) As Integer
       Return str.Where(Function(X) String.IsNullOrEmpty(X)).Count
   End Function

#End Region


Código (vbnet) [Seleccionar]
#Region " Count Non Blank Lines "

   ' [ Count non blank lines ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(Count_Non_Blank_Lines(RichTextBox1.Lines))
   ' MsgBox(Count_Non_Blank_Lines({"A", "", "", "B"})) ' Result: 2

   Private Function Count_Non_Blank_Lines(ByVal str As String()) As Integer
       Return str.Where(Function(X) Not String.IsNullOrEmpty(X)).Count
   End Function

#End Region


Código (vbnet) [Seleccionar]
#Region " Get non blank lines "

   ' [ Get non blank lines ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(String.Join(Environment.NewLine, Get_Non_Blank_Lines(RichTextBox1.Lines)))
   ' MsgBox(String.Join(Environment.NewLine, Get_Non_Blank_Lines({"A", "", "", "B"}))) ' Result: {"A", "B"}

   Private Function Get_Non_Blank_Lines(ByVal str As String()) As String()
       Return str.Where(Function(X) Not String.IsNullOrEmpty(X)).ToArray
   End Function

#End Region








Eleкtro

#288
Contar todas las agrupaciones en un string:

PD: Para quien no sepa, una agrupación empieza con el caracter "(" y acaba con el ")"

Código (vbnet) [Seleccionar]
               Dim stack As New Stack(Of Char)
               'Dim input As String = ")((()))("
               Dim input As String = "(Hello) ) ( (World)?"

               Dim opened As Integer = 0
               Dim closed As Integer = 0

               For Each ch As Char In input

                   If ch = "(" Then
                       stack.Push("#")

                   ElseIf ch = ")" Then

                       If stack.Count = 0 Then
                           opened += 1
                       Else
                           closed += 1
                           stack.Pop()

                       End If

                   End If
               Next ch

               opened = opened + stack.Count

               Console.WriteLine("Opened:{0} Closed:{1}", opened, closed)
               MsgBox(String.Format("Opened:{0} Closed:{1}", opened, closed))



EDITO:

Lo he modificado un poco para usarlo a mis necesidades:

Código (vbnet) [Seleccionar]
  Private ReadOnly Property TotalAgrupations As Dictionary(Of String, Integer)
        Get
            Return Count_Agrupations_In_String(TextBox_RegEx.Text)
        End Get
    End Property

    ' MsgBox(TotalAgrupations("Opened"))
    ' MsgBox(TotalAgrupations("Closed"))

    Private Function Count_Agrupations_In_String(ByVal str As String) As Dictionary(Of String, Integer)

        Dim stack As New Stack(Of Char)

        Dim opened As Integer = 0
        Dim closed As Integer = 0

        For Each ch As Char In str

            If ch = "(" Then
                stack.Push("#")

            ElseIf ch = ")" Then

                If stack.Count = 0 Then
                    opened += 1
                Else
                    closed += 1
                    stack.Pop()

                End If

            End If

        Next ch

        Return New Dictionary(Of String, Integer) From { _
            {"Opened", opened + stack.Count}, _
            {"Closed", closed} _
        }

    End Function







Los siguientes códigos he testeado su velocidad de ejecución usando métodos distintos con LINQ, RegEx y For, ha ganado For y con mucha diferencia de ms así que aquí tienen:


Reemplaza (o elimina) todos los caracteres que indiquemos en un string

Código (vbnet) [Seleccionar]
#Region " Replace All Characters "

   ' [ Replace All Characters Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(Replace_All_Characters("Hello World!", {"e"c, "o"c}, "+")) ' Result: H+ll+ W+rld!

   Public Function Replace_All_Characters(ByVal str As String, _
                                          ByVal chars As Char(), _
                                          replaceWith As Char) As String

       For Each c As Char In chars
           str = str.Replace(c, replaceWith)
       Next

       Return str

   End Function

#End Region







Reemplazar todos los caracteres en un string, menos los caracteres que indiquemos.

Código (vbnet) [Seleccionar]
#Region " Replace All Characters Except "

   ' [ Replace All Characters Except Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(Replace_All_Characters("Hello World!", "eo", ".")) ' Result: ".e..o..o...."

   Public Function Replace_All_Characters_Except(ByVal str As String, _
                                                 ByVal chars As String, _
                                                 replaceWith As Char) As String

       Dim temp_str As String = String.Empty

       For Each c As Char In str
           If Not chars.Contains(c) Then
               temp_str &= c
           Else
               temp_str &= replaceWith
           End If
       Next c

       Return temp_str

   End Function

#End Region







Eliminar todos los caracteres en un string, menos los caracteres que indiquemos.

El snippet de arriba se puede usar para esta misma función, pero traducido a milisegundos este código es más rápido.

Código (vbnet) [Seleccionar]
#Region " Remove All Characters Except "

   ' [ Remove All Characters Except Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(Remove_All_Characters_Except("Hello World!", "eo".ToCharArray)) ' Result: "eoo"

   Public Function Remove_All_Characters_Except(ByVal str As String, _
                                             ByVal chars As Char()) As String

       Dim temp_str As String = String.Empty

       For Each c As Char In str
           For Each cc As Char In chars
               If c = cc Then temp_str &= cc
           Next cc
       Next c

       Return temp_str

   End Function

#End Region










Eleкtro

#289
Hice un código improvisado en Batch para crear un listado con colores RGB aleatorios (todo lo aleatorio que cabe usando Batch) para luego copiarlo diréctamente en la IDE.

Esto lo hice por la misma razón que suelo hacer con todo este tipo de snippets, para ahorrarme el trabajo manual repetitivo xD, aunque habría quedado más bonito en otro lenguaje.

No necesito generar esta lista en tiempo de ejecución así que perdonarme por no postear una versiónd el code traducida a VB.

Código (dos) [Seleccionar]
@Echo OFF

REM By Elektro H@cker

TITLE Random Color.FromArgb() Generator for .NET

:::::::::::::::::::::
Set /A Max_Colors=255
:::::::::::::::::::::

set /A random1 & set /A random2 & set /A random3
set /a index=0

Echo+>"Color.FromArgb.txt"

:loop1
Call set /a "random1=%%RANDOM:~0,3%%"
if not %random1% GTR 255 (Goto :loop2)
Call set /a "random1=%%RANDOM:~1,2%%" 2>NUL || Call set /a "random1=%%RANDOM:~0,1%%"

:loop2
Call set /a "random2=%%RANDOM:~0,3%%"
if not %random2% GTR 255 (Goto :loop3)
Call set /a "random2=%%RANDOM:~1,2%%" 2>NUL || Call set /a "random2=%%RANDOM:~0,1%%"

:loop3
Call set /a "random3=%%RANDOM:~0,3%%"
if not %random3% GTR 255 (Goto :Append)
Call set /a "random3=%%RANDOM:~1,2%%" 2>NUL || Call set /a "random3=%%RANDOM:~0,1%%"

:Append
Echo Color.FromArgb(%RANDOM1%, %RANDOM2%, %RANDOM3%)
Echo {%index%, Color.FromArgb(%RANDOM1%, %RANDOM2%, %RANDOM3%)}, _>>"Color.FromArgb.txt"

Set /A Index+=1
if %index% GTR %Max_Colors% (Pause&Exit)
Goto:loop1


El output es algo así:

CMD:
Color.FromArgb(248, 51, 134)
Color.FromArgb(119, 23, 233)
Color.FromArgb(120, 81, 71)
Color.FromArgb(54, 209, 179)
Color.FromArgb(115, 219, 46)
Color.FromArgb(146, 229, 130)
Color.FromArgb(254, 87, 184)
Color.FromArgb(117, 50, 23)
Color.FromArgb(47, 203, 46)
Color.FromArgb(75, 226, 13)
Color.FromArgb(192, 40, 49)
Color.FromArgb(49, 214, 63)
Color.FromArgb(149, 105, 65)
Color.FromArgb(130, 133, 166)
Color.FromArgb(45, 185, 214)
Color.FromArgb(41, 196, 20)
Color.FromArgb(230, 23, 193)
Color.FromArgb(146, 21, 5)
Color.FromArgb(40, 92, 52)
Color.FromArgb(151, 93, 22)
Color.FromArgb(124, 236, 78)
Color.FromArgb(55, 226, 50)
Color.FromArgb(30, 139, 76)
Color.FromArgb(67, 50, 69)


Archivo de texto:
{0, Color.FromArgb(44, 222, 32)}, _
{1, Color.FromArgb(23, 17, 75)}, _
{2, Color.FromArgb(6, 97, 1)}, _
{3, Color.FromArgb(39, 138, 57)}, _
{4, Color.FromArgb(67, 158, 13)}, _
{5, Color.FromArgb(76, 31, 26)}, _
{6, Color.FromArgb(142, 104, 118)}, _
{7, Color.FromArgb(29, 217, 91)}, _
{8, Color.FromArgb(229, 176, 216)}, _
{9, Color.FromArgb(133, 73, 45)}, _
{10, Color.FromArgb(151, 47, 21)}, _
{11, Color.FromArgb(32, 31, 205)}, _
{12, Color.FromArgb(126, 173, 80)}, _
{13, Color.FromArgb(240, 179, 146)}, _
{14, Color.FromArgb(11, 197, 205)}, _
{15, Color.FromArgb(37, 206, 129)}, _
{16, Color.FromArgb(253, 214, 137)}, _
{17, Color.FromArgb(89, 119, 31)}, _
{18, Color.FromArgb(2, 103, 255)}, _
{19, Color.FromArgb(91, 166, 196)}, _
{20, Color.FromArgb(79, 90, 82)}, _
{21, Color.FromArgb(154, 249, 78)}, _
{22, Color.FromArgb(93, 125, 5)}, _
{23, Color.FromArgb(192, 119, 17)}, _
{24, Color.FromArgb(60, 250, 236)}, _
{25, Color.FromArgb(196, 97, 99)}, _