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.

josnan

Me gustaria probar esos snippets pero el enlace no funciona.


Eleкtro

@josnan

Se me olvidó responder a la petición que hiciste, la leí el otro día pero se me pasó contestarte, lo siento.

actualmente los snippets los estoy "reconstruyendo", refactorizando, reordenando, actualizándolos, etc, prefiero no publicarlos todavía, pero te los pasaré en breve por privado.

Gracias por tu interés, y perdona el pequeño olvido.

Saludos








josnan


Eleкtro

Despues de un tiempo sin actualizar, volvemos a la carga con un par de snippets.




Ejemplo de uso de la librería CodeScales:
http://www.codescales.com/

Es un simple, muy simple cliente http que encapsula el código/miembros necesarios de la librería de classes de .Net para realizar peticiones Post con MultiPart, y otras, de forma muy sencilla:

Código (vbnet) [Seleccionar]


       ' *********************
       ' Get Method
       ' http://www.google.com
       ' *********************
       '
       ' Dim client As New HttpClient
       ' Dim getMethod As New HttpGet(New Uri("http://www.google.com/search"))
       '
       ' With getMethod
       '     .Parameters.Add("q", "Hello")
       '     .Parameters.Add("lr", "lang_en")
       ' End With
       '
       ' Dim response As HttpResponse = client.Execute(getMethod)
       ' Dim text As String = EntityUtils.ToString(response.Entity)



       ' **************************
       ' Post Method with MultiPart
       ' http://9kw.eu/
       ' **************************
       '
       ' Dim apiKey As String = "XXXXXXXXXXXX"
       ' Dim filepath As String = "C:\File.png"
       '
       ' Dim client As New HttpClient
       ' Dim postMethod As New HttpPost(New Uri("http://www.9kw.eu/index.cgi"))
       '
       ' Dim multipartEntity As New MultipartEntity
       ' postMethod.Entity = multipartEntity
       '
       ' With multipartEntity
       '     .AddBody(New StringBody(Encoding.UTF8, "apikey", apiKey))
       '     .AddBody(New StringBody(Encoding.UTF8, "action", "usercaptchaupload"))
       '     .AddBody(New StringBody(Encoding.UTF8, "source", "vbapi"))
       ' End With
       '
       ' Dim fileBody As New FileBody("file-upload-01", filepath, New IO.FileInfo(filepath))
       ' multipartEntity.AddBody(fileBody)
       '
       ' Dim response As HttpResponse = client.Execute(postMethod)
       ' Dim text As String = EntityUtils.ToString(response.Entity)





9KW Captcha Helper
http://9kw.eu/
(veanse otros ejemplos de uso en el apartado de la API en la página oficial)

Es una class para utilizar el servicio de solución de captchas de 9KW. Este servicio es de pago, se necesita una API key para podr utilizarlo.

Por el momento cumple las dos labores más esenciales, la función GetCredits devuelve los créditos actuales del usuario, y el método SolveCaptcha soluciona el captcha especificado.

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 18-September-2015
' ***********************************************************************
' <copyright file="KWCaptchaHelper.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Public Members Summary "

#Region " Properties "

' KWCaptchaHelper.ApiKey As String

#End Region

#Region " Functions "

' KWCaptchaHelper.GetCredits As String

#End Region

#Region " Methods "

' KWCaptchaHelper.SolveCaptcha(String)

#End Region

#End Region

#Region " Usage Examples "

' Dim captchaSolver As New KWCaptchaHelper(apiKey:="XXXXXXXXXXXXXXXXXXX")
' Dim imagePath As String = "C:\captcha.png"
' Dim result As String = String.Empty

' Console.WriteLine(String.Format("User Credits: {0}", captchaSolver.GetCredits()))
' Console.WriteLine(String.Format("Captcha Img.: {0}", imagePath))

' Console.WriteLine("Solving Captcha, please wait...")
' result = captchaSolver.SolveCaptcha(imagePath)
' Console.WriteLine(String.Format("Result: {0}", result))

'Console.ReadKey()

#End Region

#Region " Imports "

Imports CodeScales.Http
Imports CodeScales.Http.Entity
Imports CodeScales.Http.Methods
Imports CodeScales.Http.Entity.Mime

Imports System
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading

#End Region

#Region " KWCaptchaHelper "

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' 9KW Captcha service. Helper Class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>
''' Visit <see href="http://9kw.eu/"/> for further info.
''' </remarks>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class KWCaptchaHelper

#Region " Properties "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets the 9KW's API user key.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <value>
   ''' The 9KW's API user key.
   ''' </value>
   ''' ----------------------------------------------------------------------------------------------------
   Public ReadOnly Property ApiKey As String
       Get
           Return Me.apiKeyB
       End Get
   End Property
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' ( Backing field )
   ''' The 9KW's API user key.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   Private ReadOnly apiKeyB As String

#End Region

#Region " Constructors "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Initializes a new instance of the <see cref="KWCaptchaHelper"/> class.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="apiKey">
   ''' The 9KW's API user key.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   Public Sub New(ByVal apiKey As String)

       Me.apiKeyB = apiKey

   End Sub

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Prevents a default instance of the <see cref="KWCaptchaHelper"/> class from being created.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   Private Sub New()
   End Sub

#End Region

#Region " Private Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="data">
   ''' The data.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' System.String.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   Private Function Get9kwApi(ByVal data As String) As String

       Return Me.Get9kwHttp(String.Format("http://www.9kw.eu/index.cgi?source=vbapi&debug=0&apikey={0}&action=" & data, Me.apiKeyB))

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="url">
   ''' The URL.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' System.String.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   Private Function Get9kwHttp(ByVal url As String) As String

       Dim httpClient As New HttpClient
       Dim httpGet As New HttpGet(New Uri(url))
       Dim httpResponse As HttpResponse = httpClient.Execute(httpGet)

       Return EntityUtils.ToString(httpResponse.Entity)

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="data">
   ''' The data.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' System.String.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   Private Function Get9kwApiUpload(ByVal data As String) As String

       Dim client As New HttpClient
       Dim postMethod As New HttpPost(New Uri("http://www.9kw.eu/index.cgi"))

       Dim multipartEntity As New MultipartEntity
       postMethod.Entity = multipartEntity

       Dim stringBody As New StringBody(Encoding.UTF8, "apikey", Me.apiKeyB)
       multipartEntity.AddBody(stringBody)

       Dim stringBody3 As New StringBody(Encoding.UTF8, "source", "vbapi")
       multipartEntity.AddBody(stringBody3)

       Dim stringBody2 As New StringBody(Encoding.UTF8, "action", "usercaptchaupload")
       multipartEntity.AddBody(stringBody2)

       Dim fileInfo As New FileInfo(data)
       Dim fileBody As New FileBody("file-upload-01", data, fileInfo)
       multipartEntity.AddBody(fileBody)

       Dim response As HttpResponse = client.Execute(postMethod)
       Return EntityUtils.ToString(response.Entity)

   End Function

#End Region

#Region " Public Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets the current remaining credits.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' The current remaining credits.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   Public Function GetCredits() As String

       Return Me.Get9kwApi("usercaptchaguthaben")

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Solves the specified captcha image.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="imagePath">
   ''' The image path.
   ''' </param>
   '''
   ''' <param name="checkInterval">
   ''' The interval to check whether the captcha is solved.
   ''' </param>
   '''
   ''' <param name="totalTries">
   ''' The total intents. ( <paramref name="totalTries"/> * <paramref name="checkInterval"/> ).
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' The solved text.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   Public Function SolveCaptcha(ByVal imagePath As String,
                                Optional ByVal checkInterval As Integer = 2000,
                                Optional ByVal totalTries As Integer = 100) As String

       Dim newCaptchaID As String = Me.Get9kwApiUpload(imagePath)
       Dim checkdata As String = String.Empty
       Dim counter As Integer = 0

       Do Until Not String.IsNullOrEmpty(checkdata)

           If Interlocked.Increment(counter) = totalTries Then
               Exit Do
           Else
               Thread.Sleep(checkInterval)
           End If

           checkdata = Me.Get9kwApi("usercaptchacorrectdata&id=" & newCaptchaID)

       Loop

       Return checkdata

   End Function

#End Region

End Class

#End Region








Eleкtro

AppConfigUtil, es una class que expone un simple parser de uso genérico para comprovar el valor de una propiedad declarada en la configuración de aplicación (appconfig), el cual no he optimizado para los tipos de estructura del árbol de nodos del appconfig ...podría ser ineficiente en ciertos escenarios, pero es un comienzo.

Por ejemplo, para saber si los contadores de rendimientos están activados en el appconfig de una aplicación .Net, lo podriamos utilizar de la siguiente manera:

Código (vbnet) [Seleccionar]
Dim isPerfCountersEnabled As boolean = GetAppConfigSetting(Of Boolean)("system.net", "settings", "performanceCounters", "enabled")

O utilizar el método IsPerformanceCountersEnabled definido expresamente para esa labor.

Source:
Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 18-September-2015
' ***********************************************************************
' <copyright file="AppConfigUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Public Members Summary "

#Region " Functions "

' GetAppConfigSetting(Of T)(String, String, String, String, Optional:String) As T
' GetAppConfigSetting(Of T)(String, String, String, String) As T
' IsPerformanceCountersEnabled(Optional:String) As Boolean

#End Region

#End Region

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Imports "

Imports System
Imports System.Configuration
Imports System.Linq
Imports System.Net.Configuration

#End Region

#Region " AppConfig Util "

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains related AppConfig utilities.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class AppConfigUtil

#Region " Public Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the value of a setting declared in the application configuration file (app.config)
    ''' of the specified application.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <example> This is a code example.
    ''' <code>
    ''' Dim isPerfCountersEnabled As boolean = GetAppConfigSetting(Of Boolean)("system.net", "settings", "performanceCounters", "enabled")
    ''' </code>
    ''' </example>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    '''
    ''' <param name="sectionGroupName">
    ''' The name of the section group.
    ''' </param>
    '''
    ''' <param name="sectionName">
    ''' The name of the section.
    ''' </param>
    '''
    ''' <param name="elementName">
    ''' The name of the element.
    ''' </param>
    '''
    ''' <param name="propertyName">
    ''' The name of the property.
    ''' </param>
    '''
    ''' <param name="exePath">
    ''' The executable path of the current or an external .Net application.
    ''' If any path is specified, it assumes the current application.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' If the SectionGroup, the Section, the Element, or the Property doesn't exist, the return value is <see langword="Nothing"/>,
    ''' otherwise, the value.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    <DebuggerHidden>
    Public Shared Function GetAppConfigSetting(Of T)(ByVal sectionGroupName As String,
                                                     ByVal sectionName As String,
                                                     ByVal elementName As String,
                                                     ByVal propertyName As String,
                                                     Optional ByVal exePath As String = "") As T

        Dim appConfig As Configuration
        Dim group As ConfigurationSectionGroup
        Dim section As ConfigurationSection
        Dim sectionPropInfo As PropertyInformation
        Dim element As ConfigurationElement
        Dim elementPropInfo As PropertyInformation

        If Not String.IsNullOrEmpty(exePath) Then
            appConfig = ConfigurationManager.OpenExeConfiguration(exePath)
        Else
            appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        End If

        group = appConfig.GetSectionGroup(sectionGroupName)
        If group Is Nothing Then
            Return Nothing
        End If

        section = group.Sections(sectionName)
        If section Is Nothing Then
            Return Nothing
        End If

        sectionPropInfo = section.ElementInformation.Properties(elementName)
        If sectionPropInfo Is Nothing Then
            Return Nothing
        End If

        element = DirectCast(sectionPropInfo.Value, ConfigurationElement)
        If element Is Nothing Then
            Return Nothing
        End If

        elementPropInfo = element.ElementInformation.Properties(propertyName)
        If elementPropInfo Is Nothing Then
            Return Nothing
        End If

        Return DirectCast(elementPropInfo.Value, T)

    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the value of a setting declared in the application configuration file (app.config)
    ''' of the specified application.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    '''
    ''' <param name="sectionName">
    ''' The name of the section.
    ''' </param>
    '''
    ''' <param name="elementName">
    ''' The name of the element.
    ''' </param>
    '''
    ''' <param name="propertyName">
    ''' The name of the property.
    ''' </param>
    '''
    ''' <param name="exePath">
    ''' The executable path of the current or an external .Net application.
    ''' If any path is specified, it assumes the current application.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' If the Section, the Element, or the Property doesn't exist, the return value is <see langword="Nothing"/>,
    ''' otherwise, the value.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    <DebuggerHidden>
    Public Shared Function GetAppConfigSetting(Of T)(ByVal sectionName As String,
                                                     ByVal elementName As String,
                                                     ByVal propertyName As String,
                                                     Optional ByVal exePath As String = "") As T

        Dim appConfig As Configuration
        Dim section As ConfigurationSection
        Dim sectionPropInfo As PropertyInformation
        Dim element As ConfigurationElement
        Dim elementPropInfo As PropertyInformation

        If Not String.IsNullOrEmpty(exePath) Then
            appConfig = ConfigurationManager.OpenExeConfiguration(exePath)
        Else
            appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        End If

        section = appConfig.GetSection(sectionName)
        If section Is Nothing Then
            Return Nothing
        End If

        sectionPropInfo = section.ElementInformation.Properties(elementName)
        If sectionPropInfo Is Nothing Then
            Return Nothing
        End If

        element = DirectCast(sectionPropInfo.Value, ConfigurationElement)
        If element Is Nothing Then
            Return Nothing
        End If

        elementPropInfo = element.ElementInformation.Properties(propertyName)
        If elementPropInfo Is Nothing Then
            Return Nothing
        End If

        Return DirectCast(elementPropInfo.Value, T)

    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Determines whether the performance counters feature is enabled in the application configuration file (app.config)
    ''' of the specified application.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="exePath">
    ''' The executable path of the current or an external .Net application.
    ''' If any path is specified, it assumes the current application.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' Returns <see langword="False"/> if the performance counters feature is disabled or if the "system.net" section is not defined;
    ''' otherwise, <see langword="True"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    <DebuggerHidden>
    Public Shared Function IsPerformanceCountersEnabled(Optional ByVal exePath As String = "") As Boolean

        Dim appConfig As Configuration
        Dim group As NetSectionGroup

        If Not String.IsNullOrEmpty(exePath) Then
            appConfig = ConfigurationManager.OpenExeConfiguration(exePath)
        Else
            appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        End If

        group = DirectCast(appConfig.GetSectionGroup("system.net"), NetSectionGroup)

        Return (group IsNot Nothing AndAlso group.Settings.PerformanceCounters.Enabled)

    End Function

#End Region

End Class

#End Region








Eleкtro

#486
NetworkUtil.vb, esta class expone varias funcionalidades relacionadas con los adaptadores de red, desde un evento compartido, NetworkUtil.NetworkStatusChanged, el cual se puede utilizar para monitorizar el estado de la conexión, hasta las classes NetworkUtil.NetworkTrafficMonitor, y NetworkUtil.ProcessTrafficMonitor
que, con sus respectivos eventos a los que uno se puede suscribir, sirven para monitorizar el consumo de tráfico de una red, o el de un proces en particular. Realmente tiene poco más que lo que acabo de mencionar xD.

Source:
http://pastebin.com/byCZSqGc

Ejemplo para monitorizar el estado de la red:
Código (vbnet) [Seleccionar]
Public Class Form1

   Private Sub Form1_Shown() Handles MyBase.Load

       AddHandler NetworkUtil.NetworkStatusChanged, AddressOf DoNetworkStatusChanged

   End Sub

   Private Sub DoNetworkStatusChanged(ByVal sender As Object, e As NetworkUtil.NetworkStatusChangedArgs)

       If e.IsAvailable Then
           Console.WriteLine("Network is available.")

       Else
           Console.WriteLine("Network is not available.")

       End If

   End Sub

End Class


Ejemplo para monitorizar el tráfico de red:
Código (vbnet) [Seleccionar]
Public NotInheritable Class Form1 : Inherits Form

    Dim WithEvents netMon As NetworkUtil.NetworkTrafficMonitor

    Private Sub Form1_Load() Handles MyBase.Load

        Me.netMon = New NetworkUtil.NetworkTrafficMonitor(NetworkUtil.NetworkTrafficMonitor.GetAvaliableInterfaceNames.First)
        Me.netMon.UpdateBehavior = NetworkUtil.NetworkTrafficMonitor.UpdateBehaviorEnum.FireAlwaysAfterTick
        Me.netMon.UpdateInterval = 1000 ' 1 sec
        Me.netMon.Start()

    End Sub

    '''  ----------------------------------------------------------------------------------------------------
    '''  <summary>
    '''  Handles the <see cref="NetworkUtil.NetworkTrafficMonitor.TrafficChanged"/> event of the netMon instance.
    '''  </summary>
    '''  ----------------------------------------------------------------------------------------------------
    '''  <param name="sender">T
    '''  The source of the event.
    '''  </param>
    '''  
    '''  <param name="e">
    '''  The <see cref="NetworkUtil.NetworkTrafficMonitor.TrafficChangedEventArgs"/> instance containing the event data.
    '''  </param>
    '''  ----------------------------------------------------------------------------------------------------
    Private Sub NetMon_TrafficChanged(ByVal sender As Object, ByVal e As NetworkUtil.NetworkTrafficMonitor.TrafficChangedEventArgs) _
    Handles netMon.TrafficChanged

        Me.LabelBytesReceived.Text = String.Format("Bytes received: {0} kb", (e.BytesReceived / 1024).ToString("n2"))
        Me.LabelDlSpeed.Text = String.Format("DL Speed: {0} kb/sec", (e.DiffBytesReceived / 1024).ToString("n2"))

        Me.LabelBytesSent.Text = String.Format("Bytes sent: {0} kb", (e.BytesSent / 1024).ToString("n2"))
        Me.LabelUlSpeed.Text = String.Format("UL Speed: {0} kb/sec", (e.DiffBytesSent / 1024).ToString("n2"))

    End Sub

    Private Sub BtDownloadUrl_Click() Handles BtDownloadUrl.Click

        Dim url As String = "http://download.thinkbroadband.com/10MB.zip"
        Dim client As New WebClient()
        client.DownloadFileAsync(New Uri(url), Path.GetTempFileName())

    End Sub

    Private Sub BtPauseMon_Click() Handles BtPauseMon.Click

        If Me.netMon.IsActive Then
            Me.netMon.Stop()
        Else
            Me.netMon.Start()
        End If

    End Sub

End Class


Ejemplo para monitorizar el tráfico de una aplicación .Net (que tenga los contadores de rendimiento habilitados):
Código (vbnet) [Seleccionar]
Public NotInheritable Class Form1 : Inherits Form

   Dim WithEvents procNetMon As NetworkUtil.ProcessTrafficMonitor

   Private Sub Form1_Load() Handles MyBase.Load

       Me.procNetMon = New NetworkUtil.ProcessTrafficMonitor(Process.GetCurrentProcess.Id)
       Me.procNetMon.UpdateBehavior = NetworkUtil.ProcessTrafficMonitor.UpdateBehaviorEnum.FireAlwaysAfterTick
       Me.procNetMon.UpdateInterval = 1000 ' 1 sec
       Me.procNetMon.Start()

   End Sub

  ''' ----------------------------------------------------------------------------------------------------
  ''' <summary>
  ''' Handles the <see cref="NetworkUtil.ProcessTrafficMonitor.TrafficChanged"/> event of the procNetMon instance.
  ''' </summary>
  ''' ----------------------------------------------------------------------------------------------------
  ''' <param name="sender">T
  ''' The source of the event.
  ''' </param>
  '''
  ''' <param name="e">
  ''' The <see cref="NetworkUtil.ProcessTrafficMonitor.TrafficChangedEventArgs"/> instance containing the event data.
  ''' </param>
  ''' -----------------------------------------------------------------------------------------------------
   Private Sub ProcNetMon_TrafficChanged(ByVal sender As Object, ByVal e As NetworkUtil.ProcessTrafficMonitor.TrafficChangedEventArgs) _
   Handles procNetMon.TrafficChanged

       Me.LabelBytesReceived.Text = String.Format("Bytes received: {0} kb", (e.BytesReceived / 1024).ToString("n2"))
       Me.LabelDlSpeed.Text = String.Format("DL Speed: {0} kb/sec", (e.DiffBytesReceived / 1024).ToString("n2"))

       Me.LabelBytesSent.Text = String.Format("Bytes sent: {0} kb", (e.BytesSent / 1024).ToString("n2"))
       Me.LabelUlSpeed.Text = String.Format("UL Speed: {0} kb/sec", (e.DiffBytesSent / 1024).ToString("n2"))

   End Sub

   Private Sub BtDownloadUrl_Click() Handles BtDownloadUrl.Click

       Dim url As String = "http://download.thinkbroadband.com/10MB.zip"
       Dim client As New WebClient()
       client.DownloadFileAsync(New Uri(url), Path.GetTempFileName())

   End Sub

   Private Sub BtPauseMon_Click() Handles BtPauseMon.Click

       If Me.procNetMon.IsActive Then
           Me.procNetMon.Stop()
       Else
           Me.procNetMon.Start()
       End If

   End Sub

End Class








Eleкtro

#487
IEnumerable(Of T) Extensions, cómo su propio nombre indica, expone varias extensiones de método para utilizarlas con una colección genérica.

Las extensiones son las siguiente, si alguna no es lo suficientemente aclaratoria entonces pueden usar IntelliSense o el ObjectInspector para conocer el propósito de cada una:
Código (VBNET) [Seleccionar]
IEnumerable(Of T)().ConcatMultiple(IEnumerable(Of T)()) As IEnumerable(Of T)
IEnumerable(Of T)().StringJoin As IEnumerable(Of T)
IEnumerable(Of T).CountEmptyItems As Integer
IEnumerable(Of T).CountNonEmptyItems As Integer
IEnumerable(Of T).Duplicates As IEnumerable(Of T)
IEnumerable(Of T).Randomize As IEnumerable(Of T)
IEnumerable(Of T).RemoveDuplicates As IEnumerable(Of T)
IEnumerable(Of T).SplitIntoNumberOfElements(Integer) As IEnumerable(Of T)
IEnumerable(Of T).SplitIntoNumberOfElements(Integer, Boolean, T) As IEnumerable(Of T)
IEnumerable(Of T).SplitIntoParts(Integer) As IEnumerable(Of T)
IEnumerable(Of T).UniqueDuplicates As IEnumerable(Of T)
IEnumerable(Of T).Uniques As IEnumerable(Of T)


Puse ejemplos de uso para cada extensión en la documentación XML del código fuente.

Source:
Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 10-September-2015
' ***********************************************************************
' <copyright file="IEnumerableExtensions.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Public Members Summary "

#Region " Functions "

' IEnumerable(Of T)().ConcatMultiple(IEnumerable(Of T)()) As IEnumerable(Of T)
' IEnumerable(Of T)().StringJoin As IEnumerable(Of T)
' IEnumerable(Of T).CountEmptyItems As Integer
' IEnumerable(Of T).CountNonEmptyItems As Integer
' IEnumerable(Of T).Duplicates As IEnumerable(Of T)
' IEnumerable(Of T).Randomize As IEnumerable(Of T)
' IEnumerable(Of T).RemoveDuplicates As IEnumerable(Of T)
' IEnumerable(Of T).SplitIntoNumberOfElements(Integer) As IEnumerable(Of T)
' IEnumerable(Of T).SplitIntoNumberOfElements(Integer, Boolean, T) As IEnumerable(Of T)
' IEnumerable(Of T).SplitIntoParts(Integer) As IEnumerable(Of T)
' IEnumerable(Of T).UniqueDuplicates As IEnumerable(Of T)
' IEnumerable(Of T).Uniques As IEnumerable(Of T)

#End Region

#End Region

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Imports "

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports System.Runtime.CompilerServices

#End Region

#Region " IEnumerableUtil "

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains custom extension methods to use with an <see cref="IEnumerable(Of T)"/>.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Module IEnumerableExtensions

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Get All Duplicates.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0}
   ''' Debug.WriteLine(String.Join(", ", col.Duplicates))
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets all the duplicated values of the source <see cref="IEnumerable(Of T)"/>.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collection.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of T)"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function Duplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)

       Return sender.GroupBy(Function(value As T) value).
                     Where(Function(group As IGrouping(Of T, T)) group.Count > 1).
                     SelectMany(Function(group As IGrouping(Of T, T)) group)

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Get Unique Duplicates.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0}
   ''' Debug.WriteLine(String.Join(", ", col.UniqueDuplicates))
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets the unique duplicated values of the source <see cref="IEnumerable(Of T)"/>.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collection.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of T)"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function UniqueDuplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)

       Return sender.GroupBy(Function(value As T) value).
                     Where(Function(group As IGrouping(Of T, T)) group.Count > 1).
                     Select(Function(group As IGrouping(Of T, T)) group.Key)

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Get Unique Values.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0}
   ''' Debug.WriteLine(String.Join(", ", col.Uniques))
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets the unique values of the source <see cref="IEnumerable(Of T)"/>.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collection.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of T)"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function Uniques(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)

       Return sender.Except(IEnumerableExtensions.UniqueDuplicates(sender))

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Remove Duplicates.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0}
   ''' Debug.WriteLine(String.Join(", ", col.RemoveDuplicates))
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Removes duplicated values in the source <see cref="IEnumerable(Of T)"/>.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collection.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of T)"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function RemoveDuplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)

       Return sender.Distinct

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Split Collection Into Number Of Parts.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   '''  Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
   '''  Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoParts(amount:=2)
   '''  splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
   '''                                  Debug.WriteLine(String.Join(", ", col))
   '''                              End Sub)
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Splits the source <see cref="IEnumerable(Of T)"/> into the specified amount of secuences.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collection.
   ''' </param>
   '''
   ''' <param name="amount">
   ''' The target amount of secuences.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function SplitIntoParts(Of T)(ByVal sender As IEnumerable(Of T),
                                        ByVal amount As Integer) As IEnumerable(Of IEnumerable(Of T))

       If (amount = 0) OrElse (amount > sender.Count) OrElse (sender.Count Mod amount <> 0) Then
           Throw New ArgumentOutOfRangeException(paramName:="amount",
                                                 message:="value should be greater than '0', smallest than 'col.Count', and multiplier of 'col.Count'.")
       End If

       Dim chunkSize As Integer = CInt(Math.Ceiling(sender.Count() / amount))

       Return From index As Integer In Enumerable.Range(0, amount)
              Select sender.Skip(chunkSize * index).Take(chunkSize)

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Split Collection Into Number Of Elements.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   '''  Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
   '''  Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoNumberOfElements(amount:=4)
   '''  splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
   '''                                  Debug.WriteLine(String.Join(", ", col))
   '''                              End Sub)
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Splits the source <see cref="IEnumerable(Of T)"/> into secuences with the specified amount of elements.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collection.
   ''' </param>
   '''
   ''' <param name="amount">
   ''' The target amount of elements.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function SplitIntoNumberOfElements(Of T)(ByVal sender As IEnumerable(Of T),
                                                   ByVal amount As Integer) As IEnumerable(Of IEnumerable(Of T))

       Return From index As Integer In Enumerable.Range(0, CInt(Math.Ceiling(sender.Count() / amount)))
              Select sender.Skip(index * amount).Take(amount)

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Split Collection Into Number Of Elements.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   '''  Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
   '''  Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoNumberOfElements(amount:=4, fillEmpty:=True, valueToFill:=0)
   '''  splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
   '''                                  Debug.WriteLine(String.Join(", ", col))
   '''                              End Sub)
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Splits the source <see cref="IEnumerable(Of T)"/> into secuences with the specified amount of elements.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collection.
   ''' </param>
   '''
   ''' <param name="amount">
   ''' The target amount of elements.
   ''' </param>
   '''
   ''' <param name="fillEmpty">
   ''' If set to <c>true</c>, generates empty elements to fill the last secuence's part amount.
   ''' </param>
   '''
   ''' <param name="valueToFill">
   ''' An optional value used to fill the last secuence's part amount.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function SplitIntoNumberOfElements(Of T)(ByVal sender As IEnumerable(Of T),
                                                   ByVal amount As Integer,
                                                   ByVal fillEmpty As Boolean,
                                                   Optional valueToFill As T = Nothing) As IEnumerable(Of IEnumerable(Of T))

       Return (From count As Integer In Enumerable.Range(0, CInt(Math.Ceiling(sender.Count() / amount)))).
               Select(Function(count)

                          Select Case fillEmpty

                              Case True
                                  If (sender.Count - (count * amount)) >= amount Then
                                      Return sender.Skip(count * amount).Take(amount)

                                  Else
                                      Return sender.Skip(count * amount).Take(amount).
                                                 Concat(Enumerable.Repeat(Of T)(
                                                        valueToFill,
                                                        amount - (sender.Count() - (count * amount))))
                                  End If

                              Case Else
                                  Return sender.Skip(count * amount).Take(amount)

                          End Select

                      End Function)

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Randomize Collection.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' Dim col As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
   ''' Debug.WriteLine(String.Join(", ", col.Randomize))
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Randomizes the elements of the source <see cref="IEnumerable(Of T)"/>.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collection.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of T)"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function Randomize(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)

       Dim rand As New Random

       Return From item As T In sender
              Order By rand.Next

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Concatenate Multiple Collections.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' Dim col1 As IEnumerable(Of Integer) = {1, 2, 3}
   ''' Dim col2 As IEnumerable(Of Integer) = {4, 5, 6}
   ''' Dim col3 As IEnumerable(Of Integer) = {7, 8, 9}
   ''' Debug.WriteLine(String.Join(", ", {col1, col2, col3}.ConcatMultiple))
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Concatenates multiple <see cref="IEnumerable(Of T)"/> at once into a single <see cref="IEnumerable(Of T)"/>.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="sender">
   ''' The source collections.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of T)"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function ConcatMultiple(Of T)(ByVal sender As IEnumerable(Of T)()) As IEnumerable(Of T)

       Return sender.SelectMany(Function(col As IEnumerable(Of T)) col)

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Join Multiple Collections Into Single String.
   ''' Author: Elektro
   ''' Date  : 08-March-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' Dim col1 As IEnumerable(Of Integer) = {1, 2, 3}
   ''' Dim col2 As IEnumerable(Of Integer) = {4, 5, 6}
   ''' Dim col3 As IEnumerable(Of Integer) = {7, 8, 9}
   ''' Debug.WriteLine({col1, col2, col3}.StringJoin(", ")))
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Joins multiple <see cref="IEnumerable(Of T)"/> at once into a single string.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''    
   ''' <param name="separator">
   ''' The string to use as a separator.
   ''' </param>
   '''
   ''' <param name="sender">
   ''' The source collections.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="String"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function StringJoin(Of T)(ByVal sender As IEnumerable(Of T)(),
                                    ByVal separator As String) As String

       Dim sb As New System.Text.StringBuilder

       For Each col As IEnumerable(Of T) In sender
           sb.Append(String.Join(separator, col) & separator)
       Next col

       Return sb.Remove(sb.Length - separator.Length, separator.Length).ToString

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Count empty items of collection.
   ''' Author: Elektro
   ''' Date  : 16-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim emptyItemCount As Integer = {"Hello", "   ", "World!"}.CountEmptyItems
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Counts the empty items of the source <see cref="IEnumerable(Of T)"/>.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="sender">
   ''' The source <see cref="IEnumerable(Of T)"/>.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' The total amount of empty items.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function CountEmptyItems(Of T)(ByVal sender As IEnumerable(Of T)) As Integer

       Return (From item As T In sender
               Where (item.Equals(Nothing))).Count

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Count non-empty items of collection.
   ''' Author: Elektro
   ''' Date  : 16-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim nonEmptyItemCount As Integer = {"Hello", "   ", "World!"}.CountNonEmptyItems
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Counts the non-empty items of the source <see cref="IEnumerable(Of T)"/>.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="sender">
   ''' The source <see cref="IEnumerable(Of T)"/>.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' The total amount of non-empty items.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   <Extension>
   Public Function CountNonEmptyItems(Of T)(ByVal sender As IEnumerable(Of T)) As Integer

       Return (sender.Count - IEnumerableExtensions.CountEmptyItems(sender))

   End Function

End Module

#End Region













IEnumerable(Of String) Extensions, cómo su propio nombre indica, expone varias extensiones de método para utilizarlas con una colección de strings.

Las extensiones son las siguiente, si alguna no es lo suficientemente aclaratoria entonces pueden usar IntelliSense o el ObjectInspector para conocer el propósito de cada una:
Código (vbnet) [Seleccionar]
IEnumerable(Of String).BubbleSort As IEnumerable(Of String)
IEnumerable(Of String).CountEmptyItems As Integer
IEnumerable(Of String).CountNonEmptyItems As Integer
IEnumerable(Of String).FindByContains(String, Boolean) As IEnumerable(Of String)
IEnumerable(Of String).FindByLike(String, Boolean) As IEnumerable(Of String)
IEnumerable(Of String).FindExact(String, StringComparison) As IEnumerable(Of String)
IEnumerable(Of String).RemoveByContains(String, Boolean) As IEnumerable(Of String)
IEnumerable(Of String).RemoveByLike(String, Boolean) As IEnumerable(Of String)
IEnumerable(Of String).RemoveExact(String, StringComparison) As IEnumerable(Of String)



Puse ejemplos de uso para cada extensión en la documentación XML del código fuente.

Source:
http://pastebin.com/6XfLcMj8











Array Extensions, cómo su propio nombre indica, expone extensiones de método para utilizarlas con Arays.

Aunque realmente, por el momento solo puse una extensión, pero de igual modo comparto el código para que puedan extender su funcionalidad o tomar la idea como base.

La extensión es la siguiente, sirve para redimensionar el tamaño del array de forma automatizada y más veloz que la habitual.
Código (vbnet) [Seleccionar]
T().Resize As T()

Source:
Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 10-September-2015
' ***********************************************************************
' <copyright file="Array Extensions.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Public Members Summary "

#Region " Functions "

' T().Resize As T()

#End Region

#End Region

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Imports "

Imports System
Imports System.Diagnostics
Imports System.Runtime.CompilerServices

#End Region

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains custom extension methods to use with an <see cref="Array"/>.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Module ArrayExtensions

#Region " Public Extension Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <remarks>
    ''' Title : Resize Array.
    ''' Author: Elektro
    ''' Date  : 10-September-2015
    ''' </remarks>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <example> This is a code example.
    ''' <code>
    ''' Dim myArray(50) As Integer
    ''' Console.WriteLine(String.Format("{0,-12}: {1}", "Initial Size", myArray.Length))
    '''
    ''' myArray = myArray.Resize(myArray.Length - 51)
    ''' Console.WriteLine(String.Format("{0,-12}: {1}", "New Size", myArray.Length))
    ''' </code>
    ''' </example>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Resizes the number of elements of the source <see cref="Array"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    '''
    ''' <param name="sender">
    ''' The source <see cref="Array"/>.
    ''' </param>
    '''
    ''' <param name="newSize">
    ''' The new size.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' The resized <see cref="Array"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="System.ArgumentOutOfRangeException">
    ''' newSize;Non-negative number required
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    <DebuggerHidden>
    <Extension>
    Public Function Resize(Of T)(ByVal sender As T(),
                                 ByVal newSize As Integer) As T()

        If (newSize <= 0) Then
            Throw New System.ArgumentOutOfRangeException(paramName:="newSize", message:="Value greater than 0 is required.")
        End If

        Dim preserveLength As Integer = Math.Min(sender.Length, newSize)

        If (preserveLength > 0) Then
            Dim newArray As Array = Array.CreateInstance(sender.GetType.GetElementType, newSize)
            Array.Copy(sender, newArray, preserveLength)
            Return DirectCast(newArray, T())

        Else
            Return sender

        End If

    End Function

#End Region

End Module








Eleкtro

CursorUtil.vb, es una class que por el momento sirve cómo un simple wrapper de la función LoadCursorFromFile de la WinAPI, la cual nos permite evadir las limitaciones de un WindowsForms para poder cargar y utilizar un cursor que no sea blanco y negro.

Source:
Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 08-September-2015
' ***********************************************************************
' <copyright file="CursorUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Imports "

Imports System
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
Imports System.Runtime.InteropServices
Imports System.Windows.Forms

#End Region

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains related cursor utilities.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class CursorUtil

#Region " P/Invoking "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Platform Invocation methods (P/Invoke), access unmanaged code.
   ''' This class does not suppress stack walks for unmanaged code permission.
   ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/> must not be applied to this class.
   ''' This class is for methods that can be used anywhere because a stack walk will be performed.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' MSDN Documentation: <see href="http://msdn.microsoft.com/en-us/library/ms182161.aspx"/>
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   Private NotInheritable Class NativeMethods

#Region " Functions "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Creates a cursor based on data contained in a file.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="filepath">
       ''' The source of the file data to be used to create the cursor.
       ''' The data in the file must be in either .CUR or .ANI format.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' If the function is successful, the return value is an <see cref="IntPtr"/> to the new cursor.
       ''' If the function fails, the return value is <see cref="IntPtr.Zero"/>.
       ''' To get extended error information, call <see cref="Marshal.GetLastWin32Error"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------    
       ''' <remarks>
       ''' MSDN Documentation: <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms648392%28v=vs.85%29.aspx"/>
       ''' </remarks>
       ''' ----------------------------------------------------------------------------------------------------
       <DllImport("User32.dll", CharSet:=CharSet.Ansi, BestFitMapping:=False, ThrowOnUnmappableChar:=True, SetLastError:=True)>
       Friend Shared Function LoadCursorFromFile(
              ByVal filepath As String
       ) As IntPtr
       End Function

#End Region

   End Class

#End Region

#Region " Constructors "

   ''' <summary>
   ''' Prevents a default instance of the <see cref="CursorUtil"/> class from being created.
   ''' </summary>
   Private Sub New()
   End Sub

#End Region

#Region " Public Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Creates a cursor based on data contained in a managed .Net resource.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="resource">
   ''' The raw resource data.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="System.Windows.Forms.Cursor"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <exception cref="Exception">
   ''' </exception>
   '''
   ''' <exception cref="Win32Exception">
   ''' </exception>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   Public Shared Function LoadCursorFromResource(ByVal resource As Byte(),
                                                 Optional cleanTempFile As Boolean = False) As Cursor

       Dim tmpFilepath As String = Path.GetTempFileName

       Try
           Using fs As New FileStream(tmpFilepath, FileMode.Create, FileAccess.Write, FileShare.Read)
               fs.Write(resource, 0, resource.Length)
           End Using

           Dim result As IntPtr = NativeMethods.LoadCursorFromFile(tmpFilepath)
           Dim win32Err As Integer = Marshal.GetLastWin32Error

           If (result = IntPtr.Zero) Then
               Throw New Win32Exception([error]:=win32Err)
           Else
               Return New Cursor(result)
           End If

       Catch ex As Exception
           Throw

       Finally
           If (cleanTempFile) AndAlso (File.Exists(tmpFilepath)) Then
               File.Delete(tmpFilepath)
           End If

       End Try

   End Function

#End Region

End Class











SerializationUtil.vb, es una class para serializar y deserializar datos en binario o Xml de forma (más)sencilla y haciendo uso de Generics.

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 05-September-2015
' ***********************************************************************
' <copyright file="SerializationUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Imports "

Imports System
Imports System.Data
Imports System.IO
Imports System.Linq
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Xml.Serialization

#End Region

''' <summary>
''' Contains related serialization utilities.
''' </summary>
Public NotInheritable Class SerializationUtil

#Region " Constructors "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Prevents a default instance of the <see cref="SerializationUtil"/> class from being created.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   Private Sub New()
   End Sub

#End Region

#Region " Private Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets the proper data serializer.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="format">
   ''' The serialization format.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <exception cref="System.ArgumentException">
   ''' Wrong Serialization Format.
   ''' </exception>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   Private Shared Function GetSerializer(Of T)(ByVal format As SerializationFormat) As Object

       Select Case format

           Case SerializationFormat.Binary
               Return New BinaryFormatter

           Case SerializationFormat.Xml
               Return New XmlSerializer(type:=GetType(T))

           Case Else
               Throw New ArgumentException(message:="Wrong Serialization Format.", paramName:="serializationFormat")

       End Select

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets the proper data serializer.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="obj">
   ''' The object to check.
   ''' </param>
   '''
   ''' <param name="format">
   ''' The serialization format.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   Private Shared Function GetSerializer(Of T)(ByVal obj As T,
                                               ByVal format As SerializationFormat) As Object

       Select format

           Case SerializationFormat.Binary
               Return New BinaryFormatter()

           Case SerializationFormat.Xml
               Return New XmlSerializer(obj.GetType)

           Case Else
               Throw New ArgumentException(message:="Wrong Serialization Format.", paramName:="serializationFormat")

       End Select

   End Function

#End Region

#Region " Public Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Serializes the data of an Object to the specified file, using the specified serialization format.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="obj">
   ''' The object to be serialized.
   ''' </param>
   '''
   ''' <param name="filepath">
   ''' The filepath where to save the serialized data.
   ''' </param>
   '''
   ''' <param name="format">
   ''' The serialization format.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   Public Shared Sub Serialize(Of T)(ByVal obj As T,
                                     ByVal filepath As String,
                                     ByVal format As SerializationFormat)

       Dim serializer As Object = SerializationUtil.GetSerializer(obj, format)

       Using fs As New FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)

           Select Case serializer.GetType

               Case GetType(BinaryFormatter)
                   DirectCast(serializer, BinaryFormatter).Serialize(fs, obj)

               Case GetType(XmlSerializer)
                   DirectCast(serializer, XmlSerializer).Serialize(fs, obj)

           End Select

       End Using

   End Sub

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Deserializes the data of an Object from the specified file, using the specified deserialization format.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="filepath">
   ''' The filepath where from deserialize the serialized data.
   ''' </param>
   '''
   ''' <param name="format">
   ''' The serialization format.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   Public Shared Function Deserialize(Of T)(ByVal filepath As String,
                                            ByVal format As SerializationFormat) As T

       Dim serializer As Object = SerializationUtil.GetSerializer(Of T)(format)

       Using fs As New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)

           Select Case serializer.GetType

               Case GetType(BinaryFormatter)
                   Return DirectCast(DirectCast(serializer, BinaryFormatter).Deserialize(fs), T)

               Case GetType(XmlSerializer)
                   Return DirectCast(DirectCast(serializer, XmlSerializer).Deserialize(fs), T)

           End Select

       End Using

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Deserializes the data of an Object from the specified file, using the specified deserialization format.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="filepath">
   ''' The filepath where from deserialize the serialized data.
   ''' </param>
   '''
   ''' <param name="format">
   ''' The serialization format.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   <DebuggerHidden>
   Public Shared Sub Deserialize(Of T)(ByRef refObj As T,
                                       ByVal filepath As String,
                                       ByVal format As SerializationFormat)

       refObj = SerializationUtil.Deserialize(Of T)(filepath, format)

   End Sub

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Determines whether the specified <see cref="Type"/> can be serialized.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' The <see cref="Type"/> to check.
   ''' </typeparam>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <c>True</c> if the specified <see cref="Type"/> can be serialized; otherwise, <c>False</c>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   Public Shared Function IsTypeSerializable(Of T)() As Boolean

       Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Determines whether the specified <see cref="Type"/> can be serialized.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="type">
   ''' The <see cref="Type"/> to check.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <c>True</c> if the specified <see cref="Type"/> can be serialized; otherwise, <c>False</c>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   Public Shared Function IsTypeSerializable(Of T)(ByVal type As T) As Boolean

       Return SerializationUtil.IsTypeSerializable(Of T)()

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Determines whether the specified object can be serialized.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   '''
   ''' <param name="obj">
   ''' The object to check.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <c>True</c> if the specified object can be serialized; otherwise, <c>False</c>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   Public Shared Function IsObjectSerializable(Of T)(ByVal obj As T,
                                                     ByVal format As SerializationFormat) As Boolean

       Dim serializer As Object = SerializationUtil.GetSerializer(obj, format)

       Using fs As New MemoryStream

           Try
               Select Case serializer.GetType

                   Case GetType(BinaryFormatter)
                       DirectCast(serializer, BinaryFormatter).Serialize(fs, obj)

                   Case GetType(XmlSerializer)
                       DirectCast(serializer, XmlSerializer).Serialize(fs, obj)

               End Select

               Return True

           Catch ex As InvalidOperationException
               Return False

           Catch ex As Exception
               Throw

           End Try

       End Using

   End Function

#End Region

End Class








Eleкtro

ResourceUtil.vb, es el comienzo de una class para administrar los recursos de la aplicación actual, aunque por el momento solo tiene un método genérico GetResources(Of T) que cómo su nombre nidica, obtiene los recursos del tipo especificado.

Para un código mucho más completo y extenso que sirve para administrar un archivo de recurso de .Net (resource.ResX) vease este otro aporte:
ResXManager.vb

Source:
Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 16-June-2015
' ***********************************************************************
' <copyright file="ResourceUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Public Members Summary "

#Region " Functions "

' ResourceUtil.GetResources(OF T)

#End Region

#End Region

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Imports "

Imports System
Imports System.Globalization

#End Region

''' <summary>
''' Contains related application's managed resource utilities.
''' </summary>
Public NotInheritable Class ResourceUtil

#Region " Constructors "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Prevents a default instance of the <see cref="ResourceUtil"/> class from being created.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Private Sub New()
   End Sub

#End Region

#Region " Public Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Get Application Resources Of Type...
   ''' Author: Elektro
   ''' Date  : 16-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> Get all String resources.
   ''' <code>
   ''' Dim resources As IEnumerable(Of DictionaryEntry) = GetResources(Of Bitmap)()
   '''
   ''' For Each resource As DictionaryEntry In resources
   '''
   '''     MsgBox(resource.Key)            '  Resource Name
   '''     MsgBox(resource.Value.ToString) '  Resource Data
   '''
   ''' Next resource
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets the application resources of the specified type.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' The type of the resource to find.
   ''' </typeparam>
   '''
   ''' <param name="culture">
   ''' The resource culture
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <see cref="IEnumerable(Of DictionaryEntry)"/>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function GetResources(Of T)(Optional ByVal culture As CultureInfo = Nothing) As IEnumerable(Of DictionaryEntry)

       Return From resource As DictionaryEntry
              In My.Resources.ResourceManager.
                              GetResourceSet(If(culture Is Nothing,
                                                CultureInfo.CurrentCulture,
                                                culture), createIfNotExists:=True, tryParents:=True).Cast(Of DictionaryEntry)()
              Where TypeOf resource.Value Is T

   End Function

#End Region

End Class












Un simple ejemplo de uso de la librería AndroidLib para .Net
https://github.com/regaw-leinad/AndroidLib

Otros ejemplos oficiales:
https://github.com/regaw-leinad/AndroidLib-Samples-VB

Source:
Código (vbnet) [Seleccionar]
Imports RegawMOD.Android

Public Class Form1

   Dim android As AndroidController
   Dim device As Device
   Dim serial As String

   Private Sub Test() Handles MyBase.Shown

       ' Usually, you want to load this at startup, may take up to 5 seconds to initialize/set up resources/start server.
       Me.android = AndroidController.Instance

       Using Me.android

           ' Always call UpdateDeviceList() before using AndroidController on devices, to get the most updated list.
           Me.android.UpdateDeviceList()

           If Me.android.HasConnectedDevices Then

               Me.serial = android.ConnectedDevices(0)
               Me.device = android.GetConnectedDevice(serial)

               device.BuildProp.Keys.
                   ForEach(Sub(propertyName As String)

                               Console.WriteLine(String.Format("{0}: {1}",
                                                               propertyName,
                                                               device.BuildProp.GetProp(propertyName)))

                           End Sub)

           End If

       End Using

   End Sub

End Class