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

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

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

Eleкtro

#490
RegExUtil.vb, es una class que expone funcionalidades relacionadas con las expresiones regulares, cómo validar una expresión u obtener (solamente) las posiciones de las coincidencias encontradas.

También expone algunas expresiones esándar y no tan estándar (la mayoría las tomé prestadas del aporte del compañero WHK aquí: http://foro.elhacker.net/programacion_general/hilo_oficial_solicitudes_de_expresiones_regulares-t434833.0.html )

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

#Region " Public Members Summary "

#Region " Functions "

' RegExUtil.GetMatchesPositions(Regex, String, Integer) As IEnumerable(Of RegExUtil.MatchPosition)
' RegExUtil.Validate(String, Boolean) As Boolean

#End Region

#Region " Constants "

' RegExUtil.Patterns.CreditCard As String
' RegExUtil.Patterns.EMail As String
' RegExUtil.Patterns.HtmlTag As String
' RegExUtil.Patterns.Ipv4 As String
' RegExUtil.Patterns.Ipv6 As String
' RegExUtil.Patterns.SafeText As String
' RegExUtil.Patterns.Url As String
' RegExUtil.Patterns.USphone As String
' RegExUtil.Patterns.USssn As String
' RegExUtil.Patterns.USstate As String
' RegExUtil.Patterns.USzip As String

#End Region

#Region " Types "

' RegExUtil.MatchPosition

#End Region

#Region " Child Classes "

' RegExUtil.Patterns

#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.Linq
Imports System.Text.RegularExpressions

#End Region

#Region " RegEx Util "

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains related RegEx utilities.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class RegExUtil

#Region " Types "

#Region " MatchPosition "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Encapsulates a text value captured by a RegEx, with its start/end index.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <Serializable>
   Public NotInheritable Class MatchPosition

#Region " Properties "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the text value.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The text value.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property Text As String
           Get
               Return Me.textB
           End Get
       End Property
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' ( Backing Field )
       ''' The text value.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private ReadOnly textB As String

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the start index.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The start index.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property StartIndex As Integer
           Get
               Return Me.startIndexB
           End Get
       End Property
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' ( Backing Field )
       ''' The start index.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private ReadOnly startIndexB As Integer

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the end index.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The end index.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property EndIndex As Integer
           Get
               Return Me.endIndexB
           End Get
       End Property
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' ( Backing Field )
       ''' The end index.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private ReadOnly endIndexB As Integer

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the text length.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>The text length.</value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property Length As Integer
           Get
               Return Me.valueB.Length
           End Get
       End Property

#End Region

#Region " Constructors "

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

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="MatchPosition"/> class.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="text">
       ''' The rtext value.
       ''' </param>
       '''
       ''' <param name="startIndex">
       ''' The start index.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub New(ByVal text As String,
                      ByVal startIndex As Integer)

           Me.textB = text
           Me.startIndexB = startIndex
           Me.endIndexB = (startIndex + text.Length)

       End Sub

#End Region

   End Class

#End Region

#End Region

#Region " Child Classes "

#Region " Patterns "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' A class that exposes common RegEx patterns.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   Public NotInheritable Class Patterns

#Region " Constants "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches an URL.
       '''
       ''' For Example:
       ''' http://url
       ''' ftp://url
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const Url As String =
           "^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches the content of an Html enclosed tag.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const HtmlTag As String =
           ">([^<]+?)<"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches an IPv4 address.
       '''
       ''' For Example:
       ''' 127.0.0.1
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const Ipv4 As String =
           "((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches an IPv6 address.
       '''
       ''' For Example:
       ''' FE80:0000:0000:0000:0202:B3FF:FE1E:8329
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const Ipv6 As String =
           "(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches a valid e-mail address.
       '''
       ''' For Example:
       '''
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const EMail As String =
           "^[a-zA-Z0-9+&*-]+(?:\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,7}$"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches lower and upper case letters and all digits.
       '''
       ''' For Example:
       '''
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const SafeText As String =
           "^[a-zA-Z0-9 .-]+$"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches a valid credit card number.
       '''
       ''' For Example:
       '''
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const CreditCard As String =
           "^((4\d{3})|(5[1-5]\d{2})|(6011)|(7\d{3}))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches an United States zip code with optional dash-four.
       '''
       ''' For Example:
       '''
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const USzip As String =
           "^\d{5}(-\d{4})?$"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches an United States phone number with or without dashes.
       '''
       ''' For Example:
       '''
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const USphone As String =
           "^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches a 2 letter United States state abbreviations.
       '''
       ''' For Example:
       '''
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const USstate As String =
           "^(AE|AL|AK|AP|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MP|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY)$"

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A pattern that matches a 9 digit United States social security number with dashes.
       '''
       ''' For Example:
       '''
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Const USssn As String =
           "^\d{3}-\d{2}-\d{4}$"

#End Region

   End Class

#End Region

#End Region

#Region " Public Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Validates the specified regular expression pattern.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="pattern">
   ''' The RegEx pattern.
   ''' </param>
   '''
   ''' <param name="ignoreErrors">
   ''' If set to <c>true</c>, ignore validation errors, otherwise, throws an exception if validation fails.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <c>True</c> if pattern validation success, <c>False</c> otherwise.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function Validate(ByVal pattern As String,
                                   Optional ByVal ignoreErrors As Boolean = True) As Boolean

       Try
           Dim regEx As New Regex(pattern:=pattern)
           Return True

       Catch ex As Exception
           If Not ignoreErrors Then
               Throw
           End If
           Return False

       End Try

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <example><code>
   ''' Dim regEx As New Regex("Dog", RegexOptions.IgnoreCase)
   '''
   ''' Dim text As String = "One Dog!, Two Dogs!, three Dogs!"
   ''' RichTextBox1.Text = text
   '''
   ''' Dim matchesPos As IEnumerable(Of RegExUtil.MatchPosition) = RegExUtil.GetMatchesPositions(regEx, text, groupIndex:=0)
   '''
   ''' For Each matchPos As RegExUtil.MatchPosition In matchesPos
   '''
   '''     Console.WriteLine(text.Substring(matchPos.StartIndex, matchPos.Length))
   '''
   '''     With RichTextBox1
   '''         .SelectionStart = matchPos.StartIndex
   '''         .SelectionLength = matchPos.Length
   '''         .SelectionBackColor = Color.IndianRed
   '''         .SelectionColor = Color.WhiteSmoke
   '''         .SelectionFont = New Font(RichTextBox1.Font.Name, RichTextBox1.Font.SizeInPoints, FontStyle.Bold)
   '''     End With
   '''
   ''' Next matchPos
   '''
   ''' With RichTextBox1
   '''     .SelectionStart = 0
   '''     .SelectionLength = 0
   ''' End With
   ''' </code></example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Validates the specified regular expression pattern.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="regEx">
   ''' The RegEx pattern.
   ''' </param>
   '''
   ''' <param name="text">
   ''' If set to <c>true</c>, ignore validation errors, otherwise, throws an exception if validation fails.
   ''' </param>
   '''
   ''' <param name="groupIndex">
   ''' If set to <c>true</c>, ignore validation errors, otherwise, throws an exception if validation fails.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <c>True</c> if pattern validation success, <c>False</c> otherwise.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Iterator Function GetMatchesPositions(ByVal regEx As Regex,
                                                       ByVal text As String,
                                                       Optional ByVal groupIndex As Integer = 0) As IEnumerable(Of MatchPosition)

       Dim match As Match = regEx.Match(text)

       Do While match.Success

           Yield New MatchPosition(value:=match.Groups(groupIndex).Value,
                                   startIndex:=match.Groups(groupIndex).Index)

           match = match.NextMatch

       Loop

   End Function

#End Region

End Class

#End Region








Eleкtro

#491
CodeDomUtil.vb, una class que sirve para compilar, en tiempo de ejecución, código o archivos/soluciones escritos en VB.Net o C#.

CodeDomUtil.vb sustituye por completo a la antigua versión publicada aquí:
http://foro.elhacker.net/net/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg2021481#msg2021481

Añadí dos classes hijas que separan las funcionalidades (aunque basicamente son las mismas), estas son:

  • CodeDomUtil.VisualBasicCompiler
  • CodeDomUtil.CSharpCompiler

También añadí el evento CodeDomUtil.Compiler.CompilerWorkDone para desarrollar de manera más amistosa ...al suscribirse a este evento, vaya.

También hay definidas algunas plantillas de VB.Net y C#, plantila de consola, de WinForms, y de librería, pero estas plantillas más que para ser utilizadas sirven solamente cómo ejemplo (para testear el compiler o para mostrarle una estructura de código inicial al usuario). y más cosas que me dejo por nombrar.

El código fuente, aviso, son casi 2.000 lineas de código fuente, convendría separar las classes hijas, enumeraciones, constantes y demás para organizarlas en archivos distintos:
http://pastebin.com/Z7HMx5sg

Un ejemplo del compilador de VB.Net:
Código (vbnet) [Seleccionar]
Public NotInheritable Class Form1 : Inherits Form

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' The VisualBasic.Net compiler instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Dim WithEvents vbCompiler As CodeDomUtil.Compiler =
        New CodeDomUtil.VisualBasicCompiler(CodeDomUtil.CompilerVersions.V4)

    Private Sub Form1_Shown() Handles MyBase.Shown

        With Me.vbCompiler.Compilersettings
            .GenerateDebugInformation = True
            .GenerateWarnings = True
            .GenerateXmlDocumentation = True
            .HighEntropyEnabled = True
            .IntegerOverflowChecksEnabled = False
            .OptimizationsEnabled = True
            .Platform = CodeDomUtil.Platform.AnyCpu
            .SubsystemVersion = CodeDomUtil.SubsystemVersions.WindowsXP
            .TreatWarningsAsErrors = False
            .Verbose = True
            .VerboseSyntax = False
            .WarningLevel = CodeDomUtil.WarningLevelEnum.Level3
            .LibraryPaths.Add(IO.Directory.GetCurrentDirectory)
        End With

        Dim referencedAssemblies As New List(Of String)
        referencedAssemblies.AddRange({"System.dll", "System.Windows.Forms.dll"})

        ' Compile a VB Console App from string.
        vbCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.Console,
                                     targetFile:="C:\VB Default Console App.exe",
                                     sourceCode:=CodeDomUtil.Templates.TemplateVbConsoleApp,
                                     mainMemberName:="MainNamespace.MainModule",
                                     referencedAssemblies:=referencedAssemblies,
                                     resources:=Nothing,
                                     iconFile:=Nothing)

        ' Compile a VB WinForms App from string.
        vbCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.WinExe,
                                     targetFile:="C:\VB Default WinForms App.exe",
                                     sourceCode:=CodeDomUtil.Templates.TemplateVbWinFormsApp,
                                     mainMemberName:="MainNamespace.MainClass",
                                     referencedAssemblies:=referencedAssemblies,
                                     resources:=Nothing,
                                     iconFile:=Nothing)

        ' Compile a VB library from string.
        vbCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.DynamicLinkLibrary,
                                     targetFile:="C:\VB Default Library.dll",
                                     sourceCode:=CodeDomUtil.Templates.TemplateVbLib,
                                     mainMemberName:="MainNamespace.MainClass",
                                     referencedAssemblies:=referencedAssemblies,
                                     resources:=Nothing,
                                     iconFile:=Nothing)

        ' Compile a VB local file that contains the sourcecode.
        vbCompiler.CompileFromFile(netAssembly:=CodeDomUtil.NetAssembly.WinExe,
                                   targetFile:="C:\VB Custom App.exe",
                                   sourceFile:="C:\SourceCode.vb",
                                   mainMemberName:="MainNamespace.MainClass",
                                   referencedAssemblies:=referencedAssemblies,
                                   resources:=Nothing,
                                   iconFile:=Nothing)

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Handles the <see cref="CodeDomUtil.Compiler.CompilerWorkDone"/> event of the <see cref="vbCompiler"/> instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="sender">
    ''' The source of the event.
    ''' </param>
    '''
    ''' <param name="e">
    ''' The <see cref="CodeDomUtil.Compiler.CompilerWorkDoneEventArgs"/> instance containing the event data.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    Public Sub VbCompiler_CompilerWorkDone(ByVal sender As Object, ByVal e As CodeDomUtil.Compiler.CompilerWorkDoneEventArgs) _
    Handles vbCompiler.CompilerWorkDone

        Console.WriteLine(String.Format("Compiler: {0}", e.CodeDomProvider.ToString))
        Console.WriteLine(String.Format("Parameters: {0}", e.CompilerParameters.CompilerOptions))

        For Each war As CodeDomUtil.Compiler.Warning In e.CompilerWarnings
            Console.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
        Next war

        For Each err As CodeDomUtil.Compiler.Error In e.CompileErrors
            Console.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
        Next err

        If Not e.CompileErrors.Any Then
            Console.WriteLine(String.Format("Compilation Successful: {0}", e.TargetFilePath))
        End If

        Console.WriteLine()

    End Sub

End Class


Un ejemplo del compilador de C#:
Código (vbnet) [Seleccionar]
Public NotInheritable Class Form1 : Inherits Form

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' The C# compiler instance.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   Dim WithEvents csCompiler As CodeDomUtil.Compiler =
       New CodeDomUtil.CSharpCompiler(CodeDomUtil.CompilerVersions.V4)

   Private Sub Form1_Shown() Handles MyBase.Shown

       With Me.csCompiler.Compilersettings
           .GenerateDebugInformation = True
           .GenerateWarnings = True
           .GenerateXmlDocumentation = True
           .HighEntropyEnabled = True
           .IntegerOverflowChecksEnabled = False
           .OptimizationsEnabled = True
           .OutputLanguage = New CultureInfo("en-US")
           .Platform = CodeDomUtil.Platform.AnyCpu
           .SubsystemVersion = CodeDomUtil.SubsystemVersions.WindowsXP
           .TreatWarningsAsErrors = False
           .Verbose = True
           .VerboseSyntax = False
           .WarningLevel = CodeDomUtil.WarningLevelEnum.Level3
           .LibraryPaths.Add(IO.Directory.GetCurrentDirectory)
       End With

       Dim referencedAssemblies As New List(Of String)
       referencedAssemblies.AddRange({"System.dll", "System.Windows.Forms.dll"})

       ' Compile a C# Console App from string.
       csCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.Console,
                                    targetFile:="C:\CS Default Console App.exe",
                                    sourceCode:=CodeDomUtil.Templates.TemplateCsConsoleApp,
                                    mainMemberName:="MainNamespace.MainClass",
                                    referencedAssemblies:=referencedAssemblies,
                                    resources:=Nothing,
                                    iconFile:=Nothing)

       ' Compile a C# WinForms App from string.
       csCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.WinExe,
                                    targetFile:="C:\CS Default WinForms App.exe",
                                    sourceCode:=CodeDomUtil.Templates.TemplateCsWinFormsApp,
                                    mainMemberName:="MainNamespace.MainClass",
                                    referencedAssemblies:=referencedAssemblies,
                                    resources:=Nothing,
                                    iconFile:=Nothing)

       ' Compile a C# library from string.
       csCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.DynamicLinkLibrary,
                                    targetFile:="C:\CS Default Library.dll",
                                    sourceCode:=CodeDomUtil.Templates.TemplateCsLib,
                                    mainMemberName:="MainNamespace.MainClass",
                                    referencedAssemblies:=referencedAssemblies,
                                    resources:=Nothing,
                                    iconFile:=Nothing)

       ' Compile a C# local file that contains the sourcecode.
       csCompiler.CompileFromFile(netAssembly:=CodeDomUtil.NetAssembly.WinExe,
                                  targetFile:="C:\CS Custom App.exe",
                                  sourceFile:="C:\SourceCode.cs",
                                  mainMemberName:="MainNamespace.MainClass",
                                  referencedAssemblies:=referencedAssemblies,
                                  resources:=Nothing,
                                  iconFile:=Nothing)

   End Sub

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Handles the <see cref="CodeDomUtil.Compiler.CompilerWorkDone"/> event of the csCompiler instance.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="sender">
   ''' The source of the event.
   ''' </param>
   '''
   ''' <param name="e">
   ''' The <see cref="CodeDomUtil.Compiler.CompilerWorkDoneEventArgs"/> instance containing the event data.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   Public Sub CsCompiler_CompilerWorkDone(ByVal sender As Object, ByVal e As CodeDomUtil.Compiler.CompilerWorkDoneEventArgs) _
   Handles csCompiler.CompilerWorkDone

       Console.WriteLine(String.Format("Compiler: {0}", e.CodeDomProvider.ToString))
       Console.WriteLine(String.Format("Parameters: {0}", e.CompilerParameters.CompilerOptions))

       For Each war As CodeDomUtil.Compiler.Warning In e.CompilerWarnings
           Console.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
       Next war

       For Each err As CodeDomUtil.Compiler.Error In e.CompileErrors
           Console.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
       Next err

       If Not e.CompileErrors.Any Then
           Console.WriteLine(String.Format("Compilation Successful: {0}", e.TargetFilePath))
       End If

       Console.WriteLine()

   End Sub

End Class


Por último, muestro el diagrama de class:








Espero que les haya servido de algo este aporte.

Saludos!








Eleкtro

#492
Lamentablemente por las restricciones del foro en cuanto al límite de caracteres por post creo que no voy a poder seguir publicando snippets, ya que cada vez me quedan más grandes y muchas veces no me caben los snippets y debo subirlos a otro lugar para poner un simple enlace aquí...

Así que he decidido no publicar más snippets "importantes" o "grandes" por que me agobia dicha restricción, pero seguiré compartiendo snippets "pequeños" si surge la ocasión claro está.

También quiero mencionar que estoy construyendo mi GitHub en el cual pienso subir todos los snippets que tengo (y de paso, a ver si alguien me contribuye a optimizar los códigos xD).

Pueden visitar el repositorio de snippets a través de esta url:
http://github.com/ElektroStudios/VBNetSnippets

...Todavía faltan muchas categorías y snippets por subir, ya que primero tengo que tratar de reorganizarlos y refactorizarlos (por ejemplo, en lugar de tener 20 snippets sobre manipulación de strings, los paso a un módulo de extensiones de String), y eso lleva su tiempo.

Bueno, un saludo!








Eleкtro

#493
Les traigo una nueva actualización de este útil módulo, ProfillingUtil.vb, que como su nombre indica está orientado a escenarios de Profilling y test de unidades de código, aunque todavía es un módulo muy sencillito.

Al módulo le añadí dos métodos asíncronos, uno para medir el tiempo de ejecución de una operación, y otro para evaluar si una operación fue exitosa o no. Aparte, he refactorizado los métodos sincrónicos que ya mostré en snippets anteriores... los cuales ahora exponen el resultado a través de la estructura ProfillingUtil.TestExecutionInfo para un manejo más sencillo o familiar e intuitivo.

Sin más, abajo les muestro el código fuente y ejemplos de uso.

Recuerden que aquí tienen más snippets:



Saludos




Ejemplo de uso asíncronico:

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

Public Class Form1 : Inherits Form

   Private Sub Test() Handles Me.Shown

       Dim taskTestTime As Task(Of TestExecutionInfo) =
           ProfillingUtil.TestTimeAsync(Sub()
                                            For x As Integer = 0 To 5000
                                                Console.WriteLine(x)
                                            Next x
                                        End Sub)

       taskTestTime.ContinueWith(Sub() Me.ShowTestExecutionInfo(taskTestTime.Result))

   End Sub

   Private Sub ShowTestExecutionInfo(ByVal teInfo As TestExecutionInfo)

       Dim sb As New StringBuilder
       Select Case teInfo.Success

           Case True
               With sb ' Set an information message.
                   .AppendLine(String.Format("Method Name: {0}", teInfo.Method.Name))
                   .AppendLine()
                   .AppendLine(String.Format("Elapsed Time: {0}", teInfo.Elapsed.ToString("hh\:mm\:ss\:fff")))
               End With
               MessageBox.Show(sb.ToString, "Code Execution Measurer", MessageBoxButtons.OK, MessageBoxIcon.Information)

           Case Else
               With sb ' Set an error message.
                   .AppendLine("Exception occurred during code execution measuring.")
                   .AppendLine()
                   .AppendLine(String.Format("Method Name: {0}", teInfo.Method.Name))
                   .AppendLine()
                   .AppendLine(String.Format("Exception Type: {0}", teInfo.Exception.GetType.Name))
                   .AppendLine()
                   .AppendLine("Exception Message:")
                   .AppendLine(teInfo.Exception.Message)
                   .AppendLine()
                   .AppendLine("Exception Stack Trace:")
                   .AppendLine(teInfo.Exception.StackTrace)
               End With
               MessageBox.Show(sb.ToString, "Code Execution Measurer", MessageBoxButtons.OK, MessageBoxIcon.Error)

       End Select

   End Sub

End Class


Ejemplo de uso síncronico:

Código (vbnet) [Seleccionar]
   Sub Test()

       Dim successful As Boolean =
           ProfillingUtil.TestSuccess(Sub() Convert.ToInt32("Hello World!"))

       Dim teInfo As TestExecutionInfo =
           ProfillingUtil.TestTime(Sub()
                                       For x As Integer = 0 To 2500
                                           Console.WriteLine(x)
                                       Next x
                                   End Sub)

       Dim sb As New StringBuilder
       Select Case teInfo.Success

           Case True
               With sb ' Set an information message.
                   .AppendLine(String.Format("Method Name: {0}", teInfo.Method.Name))
                   .AppendLine()
                   .AppendLine(String.Format("Elapsed Time: {0}", teInfo.Elapsed.ToString("hh\:mm\:ss\:fff")))
               End With
               MessageBox.Show(sb.ToString, "Code Execution Measurer", MessageBoxButtons.OK, MessageBoxIcon.Information)

           Case Else
               With sb ' Set an error message.
                   .AppendLine("Exception occurred during code execution measuring.")
                   .AppendLine()
                   .AppendLine(String.Format("Method Name: {0}", teInfo.Method.Name))
                   .AppendLine()
                   .AppendLine(String.Format("Exception Type: {0}", teInfo.Exception.GetType.Name))
                   .AppendLine()
                   .AppendLine("Exception Message:")
                   .AppendLine(teInfo.Exception.Message)
                   .AppendLine()
                   .AppendLine("Exception Stack Trace:")
                   .AppendLine(teInfo.Exception.StackTrace)
               End With
               MessageBox.Show(sb.ToString, "Code Execution Measurer", MessageBoxButtons.OK, MessageBoxIcon.Error)

       End Select

   End Sub





Código fuente del módulo ProfillingUtil.vb:

EDITO:

BUENO, POR LO VISTO EN EL FORO NO CABE UN MISERABLE CÓDIGO DE 700 LINEAS. ASÍ QUE NO PUEDO PUBLICARLO AQUÍ. COPIEN Y PEGUEN DESDE EL GITHUB:
https://raw.githubusercontent.com/ElektroStudios/VBNetSnippets/master/Profilling/Profilling%20Util.vb








Eleкtro

#494
Les traigo un nuevo snippet recién salido del horno, el módulo AudioUtil.

La clase hija AudioUtil.WaveRecorder permite grabar audio Wave de forma muy sencilla.
La clase hija AudioUtil.AudioPlayer permite reproducir archivos wav, mp3 o mid/midi de forma muy sencilla.

Aparte de eso, el módulo AudioUtil puede hacer algunas cosas más, como modificar el volumen de la aplicación actual, o silenciar el volumen del sistema.




Lista de miembros públicos:

- Types
  - AudioUtil.AudioPlayer : IDisposable
  - AudioUtil.StereoVolume <Serializable>
  - AudioUtil.WaveRecorder : IDisposable

- Cosntructors
  - AudioUtil.AudioPlayer.New()
  - AudioUtil.AudioPlayer.New(Form)
  - AudioUtil.StereoVolume(Integer, Integer)
  - AudioUtil.WaveRecorder.New()

- Properties
  - AudioUtil.AudioPlayer.Filepath As String
  - AudioUtil.AudioPlayer.Status As PlayerState
  - AudioUtil.AudioPlayer.PlaybackMode As AudioPlayMode
  - AudioUtil.AudioPlayer.Channels As Integer
  - AudioUtil.AudioPlayer.Length As Integer
  - AudioUtil.AudioPlayer.Position As TimeSpan
  - AudioUtil.AudioPlayer.IsFileLoaded As Boolean
  - AudioUtil.StereoVolume.LeftChannel As Integer
  - AudioUtil.StereoVolume.RightChannel As Integer
  - AudioUtil.WaveRecorder.Status As AudioUtil.WaveRecorder.RecorderStatus

- Enumerations
  - AudioUtil.ChannelMode As Integer
  - AudioUtil.AudioPlayer.PlayerState As Integer
  - AudioUtil.WaveRecorder.RecorderStatus As Integer

- Functions
  - AudioUtil.GetAppVolume() As AudioUtil.StereoVolume

- Methods
  - AudioUtil.MuteSystemVolume()
  - AudioUtil.SetAppVolume(Integer)
  - AudioUtil.SetAppVolume(Integer, Integer)
  - AudioUtil.SetAppVolume(AudioUtil.StereoVolume)
  - AudioUtil.AudioPlayer.LoadFile(String)
  - AudioUtil.AudioPlayer.UnloadFile
  - AudioUtil.AudioPlayer.Play(Opt: AudioPlayMode)
  - AudioUtil.AudioPlayer.Seek(Long)
  - AudioUtil.AudioPlayer.Seek(TimeSpan)
  - AudioUtil.AudioPlayer.Pause
  - AudioUtil.AudioPlayer.Resume
  - AudioUtil.AudioPlayer.Stop
  - AudioUtil.AudioPlayer.Dispose
  - AudioUtil.WaveRecorder.Record
  - AudioUtil.WaveRecorder.Stop
  - AudioUtil.WaveRecorder.Play
  - AudioUtil.WaveRecorder.Delete
  - AudioUtil.WaveRecorder.Save(String, Opt: Boolean)
  - AudioUtil.WaveRecorder.Dispose




Ejemplo de uso de la class WaveRecorder:

Código (vbnet) [Seleccionar]
Dim recorder As New WaveRecorder

Sub Button_Record_Click() Handles Button_Record.Click

   If Not (recorder.Status = WaveRecorder.RecorderStatus.Recording) Then
       recorder.Record()
   End If

End Sub

Sub Button_Stop_Click() Handles Button_Stop.Click

   If (recorder.Status = WaveRecorder.RecorderStatus.Recording) Then
       recorder.Stop()
   End If

End Sub

Sub Button_Play_Click() Handles Button_Play.Click

   If (recorder.Status = WaveRecorder.RecorderStatus.Stopped) Then
       recorder.Play()
   End If

End Sub

Sub Button_Delete_Click() Handles Button_Delete.Click

   If Not (recorder.Status = WaveRecorder.RecorderStatus.Empty) Then
       recorder.Delete()
   End If

End Sub

Sub Button_Save_Click() Handles Button_Save.Click

   If Not (recorder.Status = WaveRecorder.RecorderStatus.Empty) Then
       recorder.Save("C:\File.wav", overWrite:=True)
   End If

End Sub


Ejemplo de uso de la class AudioPlayer:

Código (vbnet) [Seleccionar]

Dim player As New AudioPlayer

Sub Button_LoadFile_Click() Handles Button_LoadFile.Click

   If Not player.IsFileLoaded Then
       player.LoadFile("C:\File.wav")
   End If

End Sub

Sub Button_Play_Click() Handles Button_Play.Click

   If Not (player.Status = AudioPlayer.PlayerState.Playing) Then
       player.Play(AudioPlayMode.Background)
   End If

End Sub

Sub Button_Stop_Click() Handles Button_Stop.Click

   If Not (player.Status = AudioPlayer.PlayerState.Stopped) Then
       player.Stop()
   End If

End Sub

Sub Button_PauseResume_Click() Handles Button_PauseResume.Click

   If (player.Status = AudioPlayer.PlayerState.Playing) Then
       player.Pause()

   ElseIf (player.Status = AudioPlayer.PlayerState.Paused) Then
       player.Resume()

   End If

End Sub

Private Sub Button_SeekBackward_Click(sender As Object, e As EventArgs) Handles Button_SeekBackward.Click

   Dim currentPosition As Long = CLng(player.Position.TotalMilliseconds)

   If ((currentPosition - 5000) <= 0) Then
       player.Seek(0)

   Else
       player.Seek(currentPosition - 5000)

   End If

End Sub

Private Sub Button_SeekForward_Click(sender As Object, e As EventArgs) Handles Button_SeekForward.Click

   Dim currentPosition As Long = CLng(player.Position.TotalMilliseconds)

   If Not ((currentPosition + 5000) >= player.Length) Then
       player.Seek(currentPosition + 5000)
   End If

End Sub

Sub Button_UnloadFile_Click() Handles Button_UnloadFile.Click

   If player.IsFileLoaded Then
       player.UnLoadFile()
   End If

End Sub





Código fuente:

Más snippets (o librerías según se mire xD) en:


Saludos!








Eleкtro

#495
Una simple esructura para representar un color, en un string con formato y sintaxis unica.
Se puede extender sencillamente para añadir más formatos/sintaxis.

Ejemplo de uso:
Código (vbnet) [Seleccionar]
Dim colorString As New ColorString(Color.FromArgb(255, 91, 146, 198))

Console.WriteLine(String.Format("ColorString Structure Size: {0}", Marshal.SizeOf(GetType(ColorString)).ToString))
Console.WriteLine(String.Format("Color.Tostring      : {0}", colorString.Color.ToString))
Console.WriteLine(String.Format("ColorString.Tostring: {0}", colorString.ToString))
Console.WriteLine()

Console.WriteLine(String.Format("Numeric Format (Standard)    : {0}", colorString.Numeric(ColorString.ColorStringSyntax.Standard)))
Console.WriteLine(String.Format("Numeric Format (CSharp)      : {0}", colorString.Numeric(ColorString.ColorStringSyntax.CSharp)))
Console.WriteLine(String.Format("Numeric Format (VbNet)       : {0}", colorString.Numeric(ColorString.ColorStringSyntax.VbNet)))
Console.WriteLine(String.Format("Numeric Format (VisualStudio): {0}", colorString.Numeric(ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
Console.WriteLine()

Console.WriteLine(String.Format("Hexadecimal Format (Standard)    : {0}", colorString.Hexadecimal(ColorString.ColorStringSyntax.Standard)))
Console.WriteLine(String.Format("Hexadecimal Format (CSharp)      : {0}", colorString.Hexadecimal(ColorString.ColorStringSyntax.CSharp)))
Console.WriteLine(String.Format("Hexadecimal Format (VbNet)       : {0}", colorString.Hexadecimal(ColorString.ColorStringSyntax.VbNet)))
Console.WriteLine(String.Format("Hexadecimal Format (VisualStudio): {0}", colorString.Hexadecimal(ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
Console.WriteLine()

Console.WriteLine(String.Format("Web Format (Standard)    : {0}", colorString.Web(ColorString.ColorStringSyntax.Standard)))
Console.WriteLine(String.Format("Web Format (CSharp)      : {0}", colorString.Web(ColorString.ColorStringSyntax.CSharp)))
Console.WriteLine(String.Format("Web Format (VbNet)       : {0}", colorString.Web(ColorString.ColorStringSyntax.VbNet)))
Console.WriteLine(String.Format("Web Format (VisualStudio): {0}", colorString.Web(ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))


Resultado de ejecución:
CitarColorString Structure Size: 24
Color.Tostring      : Color [A=255, R=91, G=146, B=198]
ColorString.Tostring: {A=255, R=91, G=146, B=198}

Numeric Format (Standard)    : 255, 91, 146, 198
Numeric Format (CSharp)      : Color.FromArgb(255, 91, 146, 198);
Numeric Format (VbNet)       : Color.FromArgb(255, 91, 146, 198)
Numeric Format (VisualStudio): 255; 91; 146; 198

Hexadecimal Format (Standard)    : FF5B92C6
Hexadecimal Format (CSharp)      : Color.FromArgb(0xFF, 0x5B, 0x92, 0xC6);
Hexadecimal Format (VbNet)       : Color.FromArgb(&HFF, &H5B, &H92, &HC6)
Hexadecimal Format (VisualStudio): 0xFF5B92C6

Web Format (Standard)    : #5B92C6
Web Format (CSharp)      : ColorTranslator.FromHtml("#5B92C6");
Web Format (VbNet)       : ColorTranslator.FromHtml("#5B92C6")
Web Format (VisualStudio): #5B92C6

Ejemplo de utilidad en la vida real:


Código fuente:
Código (vbnet) [Seleccionar]
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Defines a <see cref="Color"/> with an unique string-format representation in the specified string-syntax.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' Dim colorString As New ColorString(Color.FromArgb(255, 91, 146, 198))
   '''
   ''' Console.WriteLine(String.Format("ColorString Structure Size: {0}", Marshal.SizeOf(GetType(ColorString)).ToString))
   ''' Console.WriteLine(String.Format("Color.Tostring      : {0}", colorString.Color.ToString))
   ''' Console.WriteLine(String.Format("ColorString.Tostring: {0}", colorString.ToString))
   ''' Console.WriteLine()
   ''' Console.WriteLine(String.Format("Numeric Format (Standard)    : {0}", colorString.Numeric(ColorUtil.ColorString.ColorStringSyntax.Standard)))
   ''' Console.WriteLine(String.Format("Numeric Format (CSharp)      : {0}", colorString.Numeric(ColorUtil.ColorString.ColorStringSyntax.CSharp)))
   ''' Console.WriteLine(String.Format("Numeric Format (VbNet)       : {0}", colorString.Numeric(ColorUtil.ColorString.ColorStringSyntax.VbNet)))
   ''' Console.WriteLine(String.Format("Numeric Format (VisualStudio): {0}", colorString.Numeric(ColorUtil.ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
   ''' Console.WriteLine()
   ''' Console.WriteLine(String.Format("Hexadecimal Format (Standard)    : {0}", colorString.Hexadecimal(ColorUtil.ColorString.ColorStringSyntax.Standard)))
   ''' Console.WriteLine(String.Format("Hexadecimal Format (CSharp)      : {0}", colorString.Hexadecimal(ColorUtil.ColorString.ColorStringSyntax.CSharp)))
   ''' Console.WriteLine(String.Format("Hexadecimal Format (VbNet)       : {0}", colorString.Hexadecimal(ColorUtil.ColorString.ColorStringSyntax.VbNet)))
   ''' Console.WriteLine(String.Format("Hexadecimal Format (VisualStudio): {0}", colorString.Hexadecimal(ColorUtil.ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
   ''' Console.WriteLine()
   ''' Console.WriteLine(String.Format("Web Format (Standard)    : {0}", colorString.Web(ColorUtil.ColorString.ColorStringSyntax.Standard)))
   ''' Console.WriteLine(String.Format("Web Format (CSharp)      : {0}", colorString.Web(ColorUtil.ColorString.ColorStringSyntax.CSharp)))
   ''' Console.WriteLine(String.Format("Web Format (VbNet)       : {0}", colorString.Web(ColorUtil.ColorString.ColorStringSyntax.VbNet)))
   ''' Console.WriteLine(String.Format("Web Format (VisualStudio): {0}", colorString.Web(ColorUtil.ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
    <Serializable>
   <StructLayout(LayoutKind.Sequential)>
   Public Structure ColorString

#Region " Properties "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the <see cref="Color"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="Color"/>.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property Color As Color
           <DebuggerStepThrough>
           Get
               Return Me.colorB
           End Get
       End Property
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' ( Backing field )
       ''' The <see cref="Color"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private ReadOnly colorB As Color

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the numeric color-string representation for this instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The numeric color-string representation.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property Numeric(ByVal colorStringSyntax As ColorStringSyntax) As String
           <DebuggerStepThrough>
           Get
               Return Me.GetNumericString(colorStringSyntax)
           End Get
       End Property

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the Hexadecimal color-string representation for this instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The Hexadecimal color-string representation.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property Hexadecimal(ByVal colorStringSyntax As ColorStringSyntax) As String
           <DebuggerStepThrough>
           Get
               Return Me.GetHexadecimalString(colorStringSyntax)
           End Get
       End Property

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the Web color-string representation for this instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The Web color-string representation.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property Web(ByVal colorStringSyntax As ColorStringSyntax) As String
           <DebuggerStepThrough>
           Get
               Return Me.GetWebString(colorStringSyntax)
           End Get
       End Property

#End Region

#Region " Enumerations "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Specifies a string syntax to represent a color value.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Enum ColorStringSyntax As Integer

           ''' <summary>
           ''' Standard syntax.
           ''' </summary>
           Standard = 0

           ''' <summary>
           ''' C# language syntax.
           ''' </summary>
           CSharp = 1

           ''' <summary>
           ''' Visual Basic.Net language syntax.
           ''' </summary>
           VbNet = 2

           ''' <summary>
           ''' VisualStudio IDE's property grid syntax.
           ''' </summary>
           VisualStudioPropertyGrid = 3

       End Enum

#End Region

#Region " Constructors "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="ColorString"/> structure.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="color">
       ''' The source <see cref="Color"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Sub New(ByVal color As Color)

           Me.colorB = color

       End Sub

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="ColorString"/> structure.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="brush">
       ''' The source <see cref="SolidBrush"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Sub New(ByVal brush As SolidBrush)

           Me.colorB = brush.Color

       End Sub

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="ColorString"/> structure.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="pen">
       ''' The source <see cref="Pen"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Sub New(ByVal pen As Pen)

           Me.colorB = pen.Color

       End Sub

#End Region

#Region " Private Methods "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the numeric string representation of a <see cref="Color"/>, in the specified <see cref="ColorStringSyntax"/> syntax.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="syntax">
       ''' The color-string syntax.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The numeric string representation.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <exception cref="InvalidEnumArgumentException">
       ''' syntax
       ''' </exception>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Private Function GetNumericString(ByVal syntax As ColorStringSyntax) As String

           Dim byteString As String =
               String.Format("{0}, {1}, {2}, {3}",
                             Convert.ToString(Me.colorB.A),
                             Convert.ToString(Me.colorB.R),
                             Convert.ToString(Me.colorB.G),
                             Convert.ToString(Me.colorB.B))

           Select Case syntax

               Case ColorString.ColorStringSyntax.Standard
                   Return byteString

               Case ColorString.ColorStringSyntax.CSharp
                   Return String.Format("Color.FromArgb({0});", byteString)

               Case ColorString.ColorStringSyntax.VbNet
                   Return String.Format("Color.FromArgb({0})", byteString)

               Case ColorString.ColorStringSyntax.VisualStudioPropertyGrid
                   Return byteString.Replace(",", ";")

               Case Else
                   Throw New InvalidEnumArgumentException("syntax", syntax, GetType(ColorStringSyntax))

           End Select

       End Function

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the numeric string representation of a <see cref="Color"/>, in the specified <see cref="ColorStringSyntax"/> syntax.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="syntax">
       ''' The color-string syntax.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The numeric string representation.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <exception cref="InvalidEnumArgumentException">
       ''' syntax
       ''' </exception>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Private Function GetHexadecimalString(ByVal syntax As ColorStringSyntax) As String

           Dim a As String = Convert.ToString(Me.colorB.A, 16).ToUpper
           Dim r As String = Convert.ToString(Me.colorB.R, 16).ToUpper
           Dim g As String = Convert.ToString(Me.colorB.G, 16).ToUpper
           Dim b As String = Convert.ToString(Me.colorB.B, 16).ToUpper

           Select Case syntax

               Case ColorString.ColorStringSyntax.Standard
                   Return String.Format("{0}{1}{2}{3}", a, r, g, b)

               Case ColorString.ColorStringSyntax.CSharp
                   Return String.Format("Color.FromArgb(0x{0}, 0x{1}, 0x{2}, 0x{3});", a, r, g, b)

               Case ColorString.ColorStringSyntax.VbNet
                   Return String.Format("Color.FromArgb(&H{0}, &H{1}, &H{2}, &H{3})", a, r, g, b)

               Case ColorString.ColorStringSyntax.VisualStudioPropertyGrid
                   Return String.Format("0x{0}{1}{2}{3}", a, r, g, b)

               Case Else
                   Throw New InvalidEnumArgumentException("syntax", syntax, GetType(ColorStringSyntax))

           End Select

       End Function

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the Web string representation of a <see cref="Color"/>, in the specified <see cref="ColorStringSyntax"/> syntax.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="syntax">
       ''' The color-string syntax.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The Web string representation.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <exception cref="InvalidEnumArgumentException">
       ''' syntax
       ''' </exception>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Private Function GetWebString(ByVal syntax As ColorStringSyntax) As String

           Dim htmlString As String = ColorTranslator.ToHtml(Color)

           Select Case syntax

               Case ColorString.ColorStringSyntax.Standard
                   Return htmlString

               Case ColorString.ColorStringSyntax.CSharp
                   Return String.Format("ColorTranslator.FromHtml(""{0}"");", htmlString)

               Case ColorString.ColorStringSyntax.VbNet
                   Return String.Format("ColorTranslator.FromHtml(""{0}"")", htmlString)

               Case ColorString.ColorStringSyntax.VisualStudioPropertyGrid
                   Return htmlString

               Case Else
                   Throw New InvalidEnumArgumentException("syntax", syntax, GetType(ColorStringSyntax))

           End Select

       End Function

#End Region

#Region " Public Methods "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Performs an implicit conversion from <see cref="ColorString"/> to <see cref="Color"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="colorString">
       ''' The <see cref="ColorString"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The resulting <see cref="Color"/> of the conversion.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Shared Widening Operator CType(ByVal colorString As ColorString) As Color

           Return Drawing.Color.FromArgb(colorString.Color.R, colorString.Color.G, colorString.Color.B)

       End Operator

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Performs an implicit conversion from <see cref="Color"/> to <see cref="ColorString"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="color">
       ''' The <see cref="Color"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The resulting <see cref="ColorString"/> of the conversion.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Shared Narrowing Operator CType(ByVal color As Color) As ColorString

           Return New ColorString(color)

       End Operator

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Implements the operator =.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="colorString1">
       ''' The first <see cref="ColorString"/> to evaluate.
       ''' </param>
       '''
       ''' <param name="colorString2">
       ''' The second <see cref="ColorString"/> to evaluate.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The result of the operator.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Shared Operator =(ByVal colorString1 As ColorString,
                                ByVal colorString2 As ColorString) As Boolean

           Return colorString1.Equals(colorString2)

       End Operator

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Implements the operator &lt;&gt;.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="colorString1">
       ''' The first <see cref="ColorString"/> to evaluate.
       ''' </param>
       '''
       ''' <param name="colorString2">
       ''' The second <see cref="ColorString"/> to evaluate.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The result of the operator.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Shared Operator <>(ByVal colorString1 As ColorString,
                                 ByVal colorString2 As ColorString) As Boolean

           Return Not colorString1.Equals(colorString2)

       End Operator

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether the specified <see cref="System.Object"/> is equal to this instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="obj">
       ''' Another object to compare to.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' <see langword="True"/> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <see langword="False"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overrides Function Equals(ByVal obj As Object) As Boolean

           If (TypeOf obj Is ColorString) Then
               Return Me.Equals(DirectCast(obj, ColorString))

           ElseIf (TypeOf obj Is Color) Then
               Return Me.Equals(New ColorString(DirectCast(obj, Color)))

           Else
               Return False

           End If

       End Function

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether the specified <see cref="ColorString"/> is equal to this instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="colorString">
       ''' Another <see cref="ColorString"/> to compare to.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' <see langword="True"/> if the specified <see cref="ColorString"/> is equal to this instance; otherwise, <see langword="False"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overloads Function Equals(ByVal colorString As ColorString) As Boolean

           Return (colorString.Color.ToArgb = Me.colorB.ToArgb)

       End Function

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Returns a hash code for this instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overrides Function GetHashCode() As Integer

           Return Me.colorB.GetHashCode()

       End Function

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Returns a <see cref="System.String"/> that represents this instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="System.String"/> that represents this instance.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overrides Function ToString() As String

           Return String.Format(CultureInfo.CurrentCulture, "{{A={0}, R={1}, G={2}, B={3}}}",
                                Me.colorB.A, Me.colorB.R, Me.colorB.G, Me.colorB.B)

       End Function

#End Region

   End Structure








Eleкtro

#496
He ideado esta sencilla y genérica manera de reunir en una misma función la posibilidad de utilizar varios algoritmos para computar el hash de un archivo o de un string.

Ejemplo de uso:

Código (vbnet) [Seleccionar]
Dim md5 As String = CryptoUtil.ComputeHashOfString(Of MD5CryptoServiceProvider)("Hello World!")
Dim sha1 As String = CryptoUtil.ComputeHashOfString(Of SHA1CryptoServiceProvider)("Hello World!")
Dim sha256 As String = CryptoUtil.ComputeHashOfString(Of SHA256CryptoServiceProvider)("Hello World!")
Dim sha384 As String = CryptoUtil.ComputeHashOfString(Of SHA384CryptoServiceProvider)("Hello World!")
Dim sha512 As String = CryptoUtil.ComputeHashOfString(Of SHA512CryptoServiceProvider)("Hello World!")


Código (vbnet) [Seleccionar]
Dim md5 As String = CryptoUtil.ComputeHashOfFile(Of MD5CryptoServiceProvider)("C:\File.ext")
Dim sha1 As String = CryptoUtil.ComputeHashOfFile(Of SHA1CryptoServiceProvider)("C:\File.ext")
Dim sha256 As String = CryptoUtil.ComputeHashOfFile(Of SHA256CryptoServiceProvider)("C:\File.ext")
Dim sha384 As String = CryptoUtil.ComputeHashOfFile(Of SHA384CryptoServiceProvider)("C:\File.ext")
Dim sha512 As String = CryptoUtil.ComputeHashOfFile(Of SHA512CryptoServiceProvider)("C:\File.ext")


Código fuente:
Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Computes the hash, using the given hash algorithm, for the specified string.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Dim md5 As String = CryptoUtil.ComputeHashOfString(Of MD5CryptoServiceProvider)("Hello World!")
''' Dim sha1 As String = CryptoUtil.ComputeHashOfString(Of SHA1CryptoServiceProvider)("Hello World!")
''' Dim sha256 As String = CryptoUtil.ComputeHashOfString(Of SHA256CryptoServiceProvider)("Hello World!")
''' Dim sha384 As String = CryptoUtil.ComputeHashOfString(Of SHA384CryptoServiceProvider)("Hello World!")
''' Dim sha512 As String = CryptoUtil.ComputeHashOfString(Of SHA512CryptoServiceProvider)("Hello World!")
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <typeparam name="T">
''' The <see cref="HashAlgorithm"/> provider.
''' </typeparam>
'''
''' <param name="str">
''' The string.
''' </param>
'''
''' <param name="enc">
''' The text <see cref="Encoding"/>.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' An Hexadecimal representation of the resulting hash value.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Function ComputeHashOfString(Of T As HashAlgorithm)(ByVal str As String,
                                                          Optional ByVal enc As Encoding = Nothing) As String

   If (enc Is Nothing) Then
       enc = Encoding.Default
   End If

   Using algorithm As HashAlgorithm = DirectCast(Activator.CreateInstance(GetType(T)), HashAlgorithm)

       Dim data As Byte() = enc.GetBytes(str)
       Dim hash As Byte() = algorithm.ComputeHash(data)
       Dim sb As New StringBuilder(capacity:=hash.Length * 2)

       For Each b As Byte In hash
           sb.Append(b.ToString("X2"))
       Next

       Return sb.ToString

   End Using

End Function

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Computes the hash, using the given hash algorithm, for the specified file.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Dim md5 As String = CryptoUtil.ComputeHashOfFile(Of MD5CryptoServiceProvider)("C:\File.ext")
''' Dim sha1 As String = CryptoUtil.ComputeHashOfFile(Of SHA1CryptoServiceProvider)("C:\File.ext")
''' Dim sha256 As String = CryptoUtil.ComputeHashOfFile(Of SHA256CryptoServiceProvider)("C:\File.ext")
''' Dim sha384 As String = CryptoUtil.ComputeHashOfFile(Of SHA384CryptoServiceProvider)("C:\File.ext")
''' Dim sha512 As String = CryptoUtil.ComputeHashOfFile(Of SHA512CryptoServiceProvider)("C:\File.ext")
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <typeparam name="T">
''' The <see cref="HashAlgorithm"/> provider.
''' </typeparam>
'''
''' <param name="filepath">
''' The filepath.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' An Hexadecimal representation of the resulting hash value.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Function ComputeHashOfFile(Of T As HashAlgorithm)(ByVal filepath As String) As String

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

       Using algorithm As HashAlgorithm = DirectCast(Activator.CreateInstance(GetType(T)), HashAlgorithm)

           Dim hash As Byte() = algorithm.ComputeHash(fs)
           Dim sb As New StringBuilder(capacity:=hash.Length * 2)

           For Each b As Byte In hash
               sb.Append(b.ToString("X2"))
           Next b

           Return sb.ToString

       End Using

   End Using

End Function








Eleкtro

Un snippet para monitorizar la inserción y extracción de dispositivos de almacenamiento (USB, discos duros, etc).

Ejemplo de uso:
Código (vbnet) [Seleccionar]
    Friend WithEvents DriveMon As New DriveWatcher

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Handles the <see cref="DriveWatcher.DriveStatusChanged"/> event of the <see cref="DriveMon"/> instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="sender">
    ''' The source of the event.
    ''' </param>
    '''
    ''' <param name="e">
    ''' The <see cref="DriveWatcher.DriveStatusChangedEventArgs"/> instance containing the event data.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    Private Sub DriveMon_DriveStatusChanged(ByVal sender As Object, ByVal e As DriveWatcher.DriveStatusChangedEventArgs) _
    Handles DriveMon.DriveStatusChanged

        Select Case e.DeviceEvent

            Case DriveWatcher.DeviceEvents.Arrival
                Dim sb As New StringBuilder
                sb.AppendLine("New drive connected...'")
                sb.AppendLine(String.Format("Type......: {0}", e.DriveInfo.DriveType.ToString))
                sb.AppendLine(String.Format("Label.....: {0}", e.DriveInfo.VolumeLabel))
                sb.AppendLine(String.Format("Name......: {0}", e.DriveInfo.Name))
                sb.AppendLine(String.Format("Root......: {0}", e.DriveInfo.RootDirectory))
                sb.AppendLine(String.Format("FileSystem: {0}", e.DriveInfo.DriveFormat))
                sb.AppendLine(String.Format("Size......: {0} GB", (e.DriveInfo.TotalSize / (1024 ^ 3)).ToString("n1")))
                sb.AppendLine(String.Format("Free space: {0} GB", (e.DriveInfo.AvailableFreeSpace / (1024 ^ 3)).ToString("n1")))
                Console.WriteLine(sb.ToString)

            Case DriveWatcher.DeviceEvents.RemoveComplete
                Dim sb As New StringBuilder
                sb.AppendLine("Drive disconnected...'")
                sb.AppendLine(String.Format("Name: {0}", e.DriveInfo.Name))
                sb.AppendLine(String.Format("Root: {0}", e.DriveInfo.RootDirectory))
                Console.WriteLine(sb.ToString)

        End Select

    End Sub

    Private Sub StartMon_Click(ByVal sender As Object, ByVal e As EventArgs) _
    Handles Button_StartMon.Click

        Me.DriveMon.Start()

    End Sub

    Private Sub StopMon_Click(ByVal sender As Object, ByVal e As EventArgs) _
    Handles Button_StopMon.Click

        Me.DriveMon.Stop()

    End Sub


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

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' A device insertion and removal monitor.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable

#Region " Properties "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the connected drives on this computer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public ReadOnly Property Drives As IEnumerable(Of DriveInfo)
        <DebuggerStepThrough>
        Get
            Return DriveInfo.GetDrives
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets a value that determines whether the monitor is running.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public ReadOnly Property IsRunning As Boolean
        <DebuggerStepThrough>
        Get
            Return Me.isRunningB
        End Get
    End Property
    Private isRunningB As Boolean

#End Region

#Region " Events "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' A list of event delegates.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Private ReadOnly events As EventHandlerList

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Occurs when a drive is inserted, removed, or changed.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Custom Event DriveStatusChanged As EventHandler(Of DriveStatusChangedEventArgs)

        <DebuggerNonUserCode>
        <DebuggerStepThrough>
        AddHandler(ByVal value As EventHandler(Of DriveStatusChangedEventArgs))
            Me.events.AddHandler("DriveStatusChangedEvent", value)
        End AddHandler

        <DebuggerNonUserCode>
        <DebuggerStepThrough>
        RemoveHandler(ByVal value As EventHandler(Of DriveStatusChangedEventArgs))
            Me.events.RemoveHandler("DriveStatusChangedEvent", value)
        End RemoveHandler

        <DebuggerNonUserCode>
        <DebuggerStepThrough>
        RaiseEvent(ByVal sender As Object, ByVal e As DriveStatusChangedEventArgs)
            Dim handler As EventHandler(Of DriveStatusChangedEventArgs) =
                DirectCast(Me.events("DriveStatusChangedEvent"), EventHandler(Of DriveStatusChangedEventArgs))

            If (handler IsNot Nothing) Then
                handler.Invoke(sender, e)
            End If
        End RaiseEvent

    End Event

#End Region

#Region " Events Data "

#Region " DriveStatusChangedEventArgs "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Contains the event-data of a <see cref="DriveStatusChanged"/> event.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public NotInheritable Class DriveStatusChangedEventArgs : Inherits EventArgs

#Region " Properties "

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Gets the device event that occurred.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <value>
        ''' The drive info.
        ''' </value>
        ''' ----------------------------------------------------------------------------------------------------
        Public ReadOnly Property DeviceEvent As DeviceEvents
            <DebuggerStepThrough>
            Get
                Return Me.deviceEventsB
            End Get
        End Property
        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' ( Backing field )
        ''' The device event that occurred.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Private ReadOnly deviceEventsB As DeviceEvents

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Gets the drive info.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <value>
        ''' The drive info.
        ''' </value>
        ''' ----------------------------------------------------------------------------------------------------
        Public ReadOnly Property DriveInfo As DriveInfo
            <DebuggerStepThrough>
            Get
                Return Me.driveInfoB
            End Get
        End Property
        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' ( Backing field )
        ''' The drive info.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Private ReadOnly driveInfoB As DriveInfo

#End Region

#Region " Constructors "

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

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Initializes a new instance of the <see cref="DriveStatusChangedEventArgs"/> class.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <param name="driveInfo">
        ''' The drive info.
        ''' </param>
        ''' ----------------------------------------------------------------------------------------------------
        <DebuggerStepThrough>
        Public Sub New(ByVal deviceEvent As DeviceEvents, ByVal driveInfo As DriveInfo)

            Me.deviceEventsB = deviceEvent
            Me.driveInfoB = driveInfo

        End Sub

#End Region

    End Class

#End Region

#End Region

#Region " Event Invocators "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Raises <see cref="DriveStatusChanged"/> event.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="e">
    ''' The <see cref="DriveStatusChangedEventArgs"/> instance containing the event data.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Protected Overridable Sub OnDriveStatusChanged(ByVal e As DriveStatusChangedEventArgs)

        RaiseEvent DriveStatusChanged(Me, e)

    End Sub

#End Region

#Region " Enumerations "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Specifies a change to the hardware configuration of a device.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <remarks>
    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx"/>
    ''' <para></para>
    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx"/>
    ''' </remarks>
    ''' ----------------------------------------------------------------------------------------------------
    Public Enum DeviceEvents As Integer

        ' *****************************************************************************
        '                            WARNING!, NEED TO KNOW...
        '
        '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS PROJECT
        ' *****************************************************************************

        ''' <summary>
        ''' The current configuration has changed, due to a dock or undock.
        ''' </summary>
        Change = &H219

        ''' <summary>
        ''' A device or piece of media has been inserted and becomes available.
        ''' </summary>
        Arrival = &H8000

        ''' <summary>
        ''' Request permission to remove a device or piece of media.
        ''' <para></para>
        ''' This message is the last chance for applications and drivers to prepare for this removal.
        ''' However, any application can deny this request and cancel the operation.
        ''' </summary>
        QueryRemove = &H8001

        ''' <summary>
        ''' A request to remove a device or piece of media has been canceled.
        ''' </summary>
        QueryRemoveFailed = &H8002

        ''' <summary>
        ''' A device or piece of media is being removed and is no longer available for use.
        ''' </summary>
        RemovePending = &H8003

        ''' <summary>
        ''' A device or piece of media has been removed.
        ''' </summary>
        RemoveComplete = &H8004

    End Enum

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Specifies a computer device type.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <remarks>
    ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363246%28v=vs.85%29.aspx"/>
    ''' </remarks>
    ''' ----------------------------------------------------------------------------------------------------
    Private Enum DeviceType As Integer

        ' *****************************************************************************
        '                            WARNING!, NEED TO KNOW...
        '
        '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS PROJECT
        ' *****************************************************************************

        ''' <summary>
        ''' Logical volume.
        ''' </summary>
        Logical = &H2

    End Enum

#End Region

#Region " Types "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Contains information about a logical volume.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <remarks>
    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx"/>
    ''' </remarks>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    <StructLayout(LayoutKind.Sequential)>
    Private Structure DevBroadcastVolume

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' The size of this structure, in bytes.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Size As UInteger

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Set to DBT_DEVTYP_VOLUME (2).
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Type As UInteger

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Reserved parameter; do not use this.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Reserved As UInteger

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' The logical unit mask identifying one or more logical units.
        ''' Each bit in the mask corresponds to one logical drive.
        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Mask As UInteger

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' This parameter can be one of the following values:
        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
        ''' '0x0002': Indicated logical volume is a network volume.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Flags As UShort

    End Structure

#End Region

#Region " Constructor "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Initializes a new instance of <see cref="DriveWatcher"/> class.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub New()

        Me.events = New EventHandlerList

    End Sub

#End Region

#Region " Public Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Starts monitoring.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="Exception">
    ''' Monitor is already running.
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Overridable Sub Start()

        If (Me.Handle = IntPtr.Zero) Then
            MyBase.CreateHandle(New CreateParams)
            Me.isRunningB = True

        Else
            Throw New Exception(message:="Monitor is already running.")

        End If

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Stops monitoring.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="Exception">
    ''' Monitor is already stopped.
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Overridable Sub [Stop]()

        If (Me.Handle <> IntPtr.Zero) Then
            MyBase.DestroyHandle()
            Me.isRunningB = False

        Else
            Throw New Exception(message:="Monitor is already stopped.")

        End If

    End Sub

#End Region

#Region " Private Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the drive letter stored in a <see cref="DevBroadcastVolume"/> structure.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="Device">
    ''' The <see cref="DevBroadcastVolume"/> structure containing the device mask.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' The drive letter.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Private Function GetDriveLetter(ByVal device As DevBroadcastVolume) As Char

        Dim driveLetters As Char() = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray

        Dim deviceID As New BitArray(BitConverter.GetBytes(device.Mask))

        For i As Integer = 0 To deviceID.Length

            If deviceID(i) Then
                Return driveLetters(i)
            End If

        Next i

        Return Nothing

    End Function

#End Region

#Region " Window Procedure (WndProc) "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Invokes the default window procedure associated with this window to process messages for this Window.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="m">
    ''' A <see cref="T:System.Windows.Forms.Message"/> that is associated with the current Windows message.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Protected Overrides Sub WndProc(ByRef m As Message)

        Select Case m.Msg

            Case DeviceEvents.Change ' The hardware has changed.

                If (m.LParam = IntPtr.Zero) Then
                    Exit Select
                End If

                ' If it's an storage device then...
                If Marshal.ReadInt32(m.LParam, 4) = DeviceType.Logical Then

                    ' Transform the LParam pointer into the data structure.
                    Dim currentWDrive As DevBroadcastVolume =
                        DirectCast(Marshal.PtrToStructure(m.LParam, GetType(DevBroadcastVolume)), DevBroadcastVolume)

                    Dim driveLetter As Char = Me.GetDriveLetter(currentWDrive)
                    Dim deviceEvent As DeviceEvents = DirectCast(m.WParam.ToInt32, DeviceEvents)
                    Dim driveInfo As New DriveInfo(driveLetter)

                    Me.OnDriveStatusChanged(New DriveStatusChangedEventArgs(deviceEvent, driveInfo))

                End If

        End Select

        ' Return Message to base message handler.
        MyBase.WndProc(m)

    End Sub

#End Region

#Region " Hidden methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Serves as a hash function for a particular type.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function GetHashCode() As Integer
        Return MyBase.GetHashCode
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the <see cref="System.Type"/> of the current instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' The exact runtime type of the current instance.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function [GetType]() As Type
        Return MyBase.GetType
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Determines whether the specified <see cref="System.Object"/> instances are considered equal.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function Equals(ByVal obj As Object) As Boolean
        Return MyBase.Equals(obj)
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Returns a String that represents the current object.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function ToString() As String
        Return MyBase.ToString
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Assigns a handle to this window.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub AssignHandle(ByVal handle As IntPtr)
        MyBase.AssignHandle(handle)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Creates a window and its handle with the specified creation parameters.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub CreateHandle(ByVal cp As CreateParams)
        MyBase.CreateHandle(cp)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Destroys the window and its handle.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub DestroyHandle()
        MyBase.DestroyHandle()
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Releases the handle associated with this window.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub ReleaseHandle()
        MyBase.ReleaseHandle()
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function GetLifeTimeService() As Object
        Return MyBase.GetLifetimeService
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function InitializeLifeTimeService() As Object
        Return MyBase.InitializeLifetimeService
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Creates an object that contains all the relevant information to generate a proxy used to communicate with a remote object.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function CreateObjRef(ByVal requestedType As Type) As System.Runtime.Remoting.ObjRef
        Return MyBase.CreateObjRef(requestedType)
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Invokes the default window procedure associated with this window.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub DefWndProc(ByRef m As Message)
        MyBase.DefWndProc(m)
    End Sub

#End Region

#Region " IDisposable Implementation "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' To detect redundant calls when disposing.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Private isDisposed As Boolean

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Releases all the resources used by this instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Dispose() Implements IDisposable.Dispose

        Me.Dispose(isDisposing:=True)
        GC.SuppressFinalize(obj:=Me)

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' Releases unmanaged and - optionally - managed resources.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="isDisposing">
    ''' <see langword="True"/>  to release both managed and unmanaged resources;
    ''' <see langword="False"/> to release only unmanaged resources.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)

        If (Not Me.isDisposed) AndAlso (isDisposing) Then

            Me.events.Dispose()
            Me.Stop()

        End If

        Me.isDisposed = True

    End Sub

#End Region

End Class








Borito30

Hola los snippets que pusistes en mediafire estan actualizados para la version de visual studio 2015 o que versión me recomiendas para usarlos? Increible aporte gracias! ;-)
Estoy en contra del foro libre y la Sección de juegos y consolas (distraen al personal)

z3nth10n

Cita de: Ragaza en  3 Marzo 2017, 23:09 PM
Hola los snippets que pusistes en mediafire estan actualizados para la version de visual studio 2015 o que versión me recomiendas para usarlos? Increible aporte gracias! ;-)

En teoría, la versión de Visual Studio (aunque es recomendado usar como minimo la versión 2010, y de ahí la 2013, y por excelencia la 2015, la 2017 no la recomiendo todavía, tiene algún que otro bug y si eres de utilizar muchos plugins te verás limitado, como yo por ejemplo con los Tools de Unity)

Lo que si importa es la versión del framework de .NET que como mínimo necesitarías para algunos la versión 4.5, quizás la 4, o incluso en algunos casos con tener la 3.5 es suficiente, eso ya lo vás seleccionando desde tu proyecto. Pero ya te digo tu te instalas la 4.6.2 y te van todos fijo.

No importa la versión de Visual Studio, a ojo diría que las versiones correspondientes son:

Visual Studio 2017 -> 4.6, 4.6.1, 4.6.2
Visual Studio 2015 -> 4.5, 4.5.1, 4.5.2
Visual Studio 2013 -> 4
Visual Studio 2010 -> 3.5
Visual Studio 2008 -> 1.1 y 2.0?

En fin, pero con instalar los paquetes de .NET ya el VS te los detecta para usarlo en tu proyecto.

Un saludo.

Interesados hablad por Discord.