elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 ... 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 [50] 51 52 53 54 55 56 57 58 59 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 485,485 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #490 en: 19 Septiembre 2015, 10:07 am »

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
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 07-July-2015
  4. ' ***********************************************************************
  5. ' <copyright file="RegExUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Public Members Summary "
  11.  
  12. #Region " Functions "
  13.  
  14. ' RegExUtil.GetMatchesPositions(Regex, String, Integer) As IEnumerable(Of RegExUtil.MatchPosition)
  15. ' RegExUtil.Validate(String, Boolean) As Boolean
  16.  
  17. #End Region
  18.  
  19. #Region " Constants "
  20.  
  21. ' RegExUtil.Patterns.CreditCard As String
  22. ' RegExUtil.Patterns.EMail As String
  23. ' RegExUtil.Patterns.HtmlTag As String
  24. ' RegExUtil.Patterns.Ipv4 As String
  25. ' RegExUtil.Patterns.Ipv6 As String
  26. ' RegExUtil.Patterns.SafeText As String
  27. ' RegExUtil.Patterns.Url As String
  28. ' RegExUtil.Patterns.USphone As String
  29. ' RegExUtil.Patterns.USssn As String
  30. ' RegExUtil.Patterns.USstate As String
  31. ' RegExUtil.Patterns.USzip As String
  32.  
  33. #End Region
  34.  
  35. #Region " Types "
  36.  
  37. ' RegExUtil.MatchPosition
  38.  
  39. #End Region
  40.  
  41. #Region " Child Classes "
  42.  
  43. ' RegExUtil.Patterns
  44.  
  45. #End Region
  46.  
  47. #End Region
  48.  
  49. #Region " Option Statements "
  50.  
  51. Option Strict On
  52. Option Explicit On
  53. Option Infer Off
  54.  
  55. #End Region
  56.  
  57. #Region " Imports "
  58.  
  59. Imports System
  60. Imports System.Collections.Generic
  61. Imports System.Linq
  62. Imports System.Text.RegularExpressions
  63.  
  64. #End Region
  65.  
  66. #Region " RegEx Util "
  67.  
  68. ''' ----------------------------------------------------------------------------------------------------
  69. ''' <summary>
  70. ''' Contains related RegEx utilities.
  71. ''' </summary>
  72. ''' ----------------------------------------------------------------------------------------------------
  73. Public NotInheritable Class RegExUtil
  74.  
  75. #Region " Types "
  76.  
  77. #Region " MatchPosition "
  78.  
  79.    ''' ----------------------------------------------------------------------------------------------------
  80.    ''' <summary>
  81.    ''' Encapsulates a text value captured by a RegEx, with its start/end index.
  82.    ''' </summary>
  83.    ''' ----------------------------------------------------------------------------------------------------
  84.    <Serializable>
  85.    Public NotInheritable Class MatchPosition
  86.  
  87. #Region " Properties "
  88.  
  89.        ''' ----------------------------------------------------------------------------------------------------
  90.        ''' <summary>
  91.        ''' Gets the text value.
  92.        ''' </summary>
  93.        ''' ----------------------------------------------------------------------------------------------------
  94.        ''' <value>
  95.        ''' The text value.
  96.        ''' </value>
  97.        ''' ----------------------------------------------------------------------------------------------------
  98.        Public ReadOnly Property Text As String
  99.            Get
  100.                Return Me.textB
  101.            End Get
  102.        End Property
  103.        ''' ----------------------------------------------------------------------------------------------------
  104.        ''' <summary>
  105.        ''' ( Backing Field )
  106.        ''' The text value.
  107.        ''' </summary>
  108.        ''' ----------------------------------------------------------------------------------------------------
  109.        Private ReadOnly textB As String
  110.  
  111.        ''' ----------------------------------------------------------------------------------------------------
  112.        ''' <summary>
  113.        ''' Gets the start index.
  114.        ''' </summary>
  115.        ''' ----------------------------------------------------------------------------------------------------
  116.        ''' <value>
  117.        ''' The start index.
  118.        ''' </value>
  119.        ''' ----------------------------------------------------------------------------------------------------
  120.        Public ReadOnly Property StartIndex As Integer
  121.            Get
  122.                Return Me.startIndexB
  123.            End Get
  124.        End Property
  125.        ''' ----------------------------------------------------------------------------------------------------
  126.        ''' <summary>
  127.        ''' ( Backing Field )
  128.        ''' The start index.
  129.        ''' </summary>
  130.        ''' ----------------------------------------------------------------------------------------------------
  131.        Private ReadOnly startIndexB As Integer
  132.  
  133.        ''' ----------------------------------------------------------------------------------------------------
  134.        ''' <summary>
  135.        ''' Gets the end index.
  136.        ''' </summary>
  137.        ''' ----------------------------------------------------------------------------------------------------
  138.        ''' <value>
  139.        ''' The end index.
  140.        ''' </value>
  141.        ''' ----------------------------------------------------------------------------------------------------
  142.        Public ReadOnly Property EndIndex As Integer
  143.            Get
  144.                Return Me.endIndexB
  145.            End Get
  146.        End Property
  147.        ''' ----------------------------------------------------------------------------------------------------
  148.        ''' <summary>
  149.        ''' ( Backing Field )
  150.        ''' The end index.
  151.        ''' </summary>
  152.        ''' ----------------------------------------------------------------------------------------------------
  153.        Private ReadOnly endIndexB As Integer
  154.  
  155.        ''' ----------------------------------------------------------------------------------------------------
  156.        ''' <summary>
  157.        ''' Gets the text length.
  158.        ''' </summary>
  159.        ''' ----------------------------------------------------------------------------------------------------
  160.        ''' <value>The text length.</value>
  161.        ''' ----------------------------------------------------------------------------------------------------
  162.        Public ReadOnly Property Length As Integer
  163.            Get
  164.                Return Me.valueB.Length
  165.            End Get
  166.        End Property
  167.  
  168. #End Region
  169.  
  170. #Region " Constructors "
  171.  
  172.        ''' ----------------------------------------------------------------------------------------------------
  173.        ''' <summary>
  174.        ''' Prevents a default instance of the <see cref="MatchPosition"/> class from being created.
  175.        ''' </summary>
  176.        ''' ----------------------------------------------------------------------------------------------------
  177.        Private Sub New()
  178.        End Sub
  179.  
  180.        ''' ----------------------------------------------------------------------------------------------------
  181.        ''' <summary>
  182.        ''' Initializes a new instance of the <see cref="MatchPosition"/> class.
  183.        ''' </summary>
  184.        ''' ----------------------------------------------------------------------------------------------------
  185.        ''' <param name="text">
  186.        ''' The rtext value.
  187.        ''' </param>
  188.        '''
  189.        ''' <param name="startIndex">
  190.        ''' The start index.
  191.        ''' </param>
  192.        ''' ----------------------------------------------------------------------------------------------------
  193.        Public Sub New(ByVal text As String,
  194.                       ByVal startIndex As Integer)
  195.  
  196.            Me.textB = text
  197.            Me.startIndexB = startIndex
  198.            Me.endIndexB = (startIndex + text.Length)
  199.  
  200.        End Sub
  201.  
  202. #End Region
  203.  
  204.    End Class
  205.  
  206. #End Region
  207.  
  208. #End Region
  209.  
  210. #Region " Child Classes "
  211.  
  212. #Region " Patterns "
  213.  
  214.    ''' ----------------------------------------------------------------------------------------------------
  215.    ''' <summary>
  216.    ''' A class that exposes common RegEx patterns.
  217.    ''' </summary>
  218.    ''' ----------------------------------------------------------------------------------------------------
  219.    Public NotInheritable Class Patterns
  220.  
  221. #Region " Constants "
  222.  
  223.        ''' ----------------------------------------------------------------------------------------------------
  224.        ''' <summary>
  225.        ''' A pattern that matches an URL.
  226.        '''
  227.        ''' For Example:
  228.        ''' http://url
  229.        ''' ftp://url
  230.        ''' </summary>
  231.        ''' ----------------------------------------------------------------------------------------------------
  232.        Public Const Url As String =
  233.            "^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$"
  234.  
  235.        ''' ----------------------------------------------------------------------------------------------------
  236.        ''' <summary>
  237.        ''' A pattern that matches the content of an Html enclosed tag.
  238.        ''' </summary>
  239.        ''' ----------------------------------------------------------------------------------------------------
  240.        Public Const HtmlTag As String =
  241.            ">([^<]+?)<"
  242.  
  243.        ''' ----------------------------------------------------------------------------------------------------
  244.        ''' <summary>
  245.        ''' A pattern that matches an IPv4 address.
  246.        '''
  247.        ''' For Example:
  248.        ''' 127.0.0.1
  249.        ''' </summary>
  250.        ''' ----------------------------------------------------------------------------------------------------
  251.        Public Const Ipv4 As String =
  252.            "((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])"
  253.  
  254.        ''' ----------------------------------------------------------------------------------------------------
  255.        ''' <summary>
  256.        ''' A pattern that matches an IPv6 address.
  257.        '''
  258.        ''' For Example:
  259.        ''' FE80:0000:0000:0000:0202:B3FF:FE1E:8329
  260.        ''' </summary>
  261.        ''' ----------------------------------------------------------------------------------------------------
  262.        Public Const Ipv6 As String =
  263.            "(([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]))"
  264.  
  265.        ''' ----------------------------------------------------------------------------------------------------
  266.        ''' <summary>
  267.        ''' A pattern that matches a valid e-mail address.
  268.        '''
  269.        ''' For Example:
  270.        '''
  271.        ''' </summary>
  272.        ''' ----------------------------------------------------------------------------------------------------
  273.        Public Const EMail As String =
  274.            "^[a-zA-Z0-9+&*-]+(?:\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,7}$"
  275.  
  276.        ''' ----------------------------------------------------------------------------------------------------
  277.        ''' <summary>
  278.        ''' A pattern that matches lower and upper case letters and all digits.
  279.        '''
  280.        ''' For Example:
  281.        '''
  282.        ''' </summary>
  283.        ''' ----------------------------------------------------------------------------------------------------
  284.        Public Const SafeText As String =
  285.            "^[a-zA-Z0-9 .-]+$"
  286.  
  287.        ''' ----------------------------------------------------------------------------------------------------
  288.        ''' <summary>
  289.        ''' A pattern that matches a valid credit card number.
  290.        '''
  291.        ''' For Example:
  292.        '''
  293.        ''' </summary>
  294.        ''' ----------------------------------------------------------------------------------------------------
  295.        Public Const CreditCard As String =
  296.            "^((4\d{3})|(5[1-5]\d{2})|(6011)|(7\d{3}))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$"
  297.  
  298.        ''' ----------------------------------------------------------------------------------------------------
  299.        ''' <summary>
  300.        ''' A pattern that matches an United States zip code with optional dash-four.
  301.        '''
  302.        ''' For Example:
  303.        '''
  304.        ''' </summary>
  305.        ''' ----------------------------------------------------------------------------------------------------
  306.        Public Const USzip As String =
  307.            "^\d{5}(-\d{4})?$"
  308.  
  309.        ''' ----------------------------------------------------------------------------------------------------
  310.        ''' <summary>
  311.        ''' A pattern that matches an United States phone number with or without dashes.
  312.        '''
  313.        ''' For Example:
  314.        '''
  315.        ''' </summary>
  316.        ''' ----------------------------------------------------------------------------------------------------
  317.        Public Const USphone As String =
  318.            "^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$"
  319.  
  320.        ''' ----------------------------------------------------------------------------------------------------
  321.        ''' <summary>
  322.        ''' A pattern that matches a 2 letter United States state abbreviations.
  323.        '''
  324.        ''' For Example:
  325.        '''
  326.        ''' </summary>
  327.        ''' ----------------------------------------------------------------------------------------------------
  328.        Public Const USstate As String =
  329.            "^(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)$"
  330.  
  331.        ''' ----------------------------------------------------------------------------------------------------
  332.        ''' <summary>
  333.        ''' A pattern that matches a 9 digit United States social security number with dashes.
  334.        '''
  335.        ''' For Example:
  336.        '''
  337.        ''' </summary>
  338.        ''' ----------------------------------------------------------------------------------------------------
  339.        Public Const USssn As String =
  340.            "^\d{3}-\d{2}-\d{4}$"
  341.  
  342. #End Region
  343.  
  344.    End Class
  345.  
  346. #End Region
  347.  
  348. #End Region
  349.  
  350. #Region " Public Methods "
  351.  
  352.    ''' ----------------------------------------------------------------------------------------------------
  353.    ''' <summary>
  354.    ''' Validates the specified regular expression pattern.
  355.    ''' </summary>
  356.    ''' ----------------------------------------------------------------------------------------------------
  357.    ''' <param name="pattern">
  358.    ''' The RegEx pattern.
  359.    ''' </param>
  360.    '''
  361.    ''' <param name="ignoreErrors">
  362.    ''' If set to <c>true</c>, ignore validation errors, otherwise, throws an exception if validation fails.
  363.    ''' </param>
  364.    ''' ----------------------------------------------------------------------------------------------------
  365.    ''' <returns>
  366.    ''' <c>True</c> if pattern validation success, <c>False</c> otherwise.
  367.    ''' </returns>
  368.    ''' ----------------------------------------------------------------------------------------------------
  369.    <DebuggerStepThrough>
  370.    Public Shared Function Validate(ByVal pattern As String,
  371.                                    Optional ByVal ignoreErrors As Boolean = True) As Boolean
  372.  
  373.        Try
  374.            Dim regEx As New Regex(pattern:=pattern)
  375.            Return True
  376.  
  377.        Catch ex As Exception
  378.            If Not ignoreErrors Then
  379.                Throw
  380.            End If
  381.            Return False
  382.  
  383.        End Try
  384.  
  385.    End Function
  386.  
  387.    ''' ----------------------------------------------------------------------------------------------------
  388.    ''' <example><code>
  389.    ''' Dim regEx As New Regex("Dog", RegexOptions.IgnoreCase)
  390.    '''
  391.    ''' Dim text As String = "One Dog!, Two Dogs!, three Dogs!"
  392.    ''' RichTextBox1.Text = text
  393.    '''
  394.    ''' Dim matchesPos As IEnumerable(Of RegExUtil.MatchPosition) = RegExUtil.GetMatchesPositions(regEx, text, groupIndex:=0)
  395.    '''
  396.    ''' For Each matchPos As RegExUtil.MatchPosition In matchesPos
  397.    '''
  398.    '''     Console.WriteLine(text.Substring(matchPos.StartIndex, matchPos.Length))
  399.    '''
  400.    '''     With RichTextBox1
  401.    '''         .SelectionStart = matchPos.StartIndex
  402.    '''         .SelectionLength = matchPos.Length
  403.    '''         .SelectionBackColor = Color.IndianRed
  404.    '''         .SelectionColor = Color.WhiteSmoke
  405.    '''         .SelectionFont = New Font(RichTextBox1.Font.Name, RichTextBox1.Font.SizeInPoints, FontStyle.Bold)
  406.    '''     End With
  407.    '''
  408.    ''' Next matchPos
  409.    '''
  410.    ''' With RichTextBox1
  411.    '''     .SelectionStart = 0
  412.    '''     .SelectionLength = 0
  413.    ''' End With
  414.    ''' </code></example>
  415.    ''' ----------------------------------------------------------------------------------------------------
  416.    ''' <summary>
  417.    ''' Validates the specified regular expression pattern.
  418.    ''' </summary>
  419.    ''' ----------------------------------------------------------------------------------------------------
  420.    ''' <param name="regEx">
  421.    ''' The RegEx pattern.
  422.    ''' </param>
  423.    '''
  424.    ''' <param name="text">
  425.    ''' If set to <c>true</c>, ignore validation errors, otherwise, throws an exception if validation fails.
  426.    ''' </param>
  427.    '''
  428.    ''' <param name="groupIndex">
  429.    ''' If set to <c>true</c>, ignore validation errors, otherwise, throws an exception if validation fails.
  430.    ''' </param>
  431.    ''' ----------------------------------------------------------------------------------------------------
  432.    ''' <returns>
  433.    ''' <c>True</c> if pattern validation success, <c>False</c> otherwise.
  434.    ''' </returns>
  435.    ''' ----------------------------------------------------------------------------------------------------
  436.    <DebuggerStepThrough>
  437.    Public Shared Iterator Function GetMatchesPositions(ByVal regEx As Regex,
  438.                                                        ByVal text As String,
  439.                                                        Optional ByVal groupIndex As Integer = 0) As IEnumerable(Of MatchPosition)
  440.  
  441.        Dim match As Match = regEx.Match(text)
  442.  
  443.        Do While match.Success
  444.  
  445.            Yield New MatchPosition(value:=match.Groups(groupIndex).Value,
  446.                                    startIndex:=match.Groups(groupIndex).Index)
  447.  
  448.            match = match.NextMatch
  449.  
  450.        Loop
  451.  
  452.    End Function
  453.  
  454. #End Region
  455.  
  456. End Class
  457.  
  458. #End Region


« Última modificación: 19 Septiembre 2015, 10:10 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #491 en: 19 Septiembre 2015, 18:22 pm »

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
  1. Public NotInheritable Class Form1 : Inherits Form
  2.  
  3.    ''' ----------------------------------------------------------------------------------------------------
  4.    ''' <summary>
  5.    ''' The VisualBasic.Net compiler instance.
  6.    ''' </summary>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    Dim WithEvents vbCompiler As CodeDomUtil.Compiler =
  9.        New CodeDomUtil.VisualBasicCompiler(CodeDomUtil.CompilerVersions.V4)
  10.  
  11.    Private Sub Form1_Shown() Handles MyBase.Shown
  12.  
  13.        With Me.vbCompiler.Compilersettings
  14.            .GenerateDebugInformation = True
  15.            .GenerateWarnings = True
  16.            .GenerateXmlDocumentation = True
  17.            .HighEntropyEnabled = True
  18.            .IntegerOverflowChecksEnabled = False
  19.            .OptimizationsEnabled = True
  20.            .Platform = CodeDomUtil.Platform.AnyCpu
  21.            .SubsystemVersion = CodeDomUtil.SubsystemVersions.WindowsXP
  22.            .TreatWarningsAsErrors = False
  23.            .Verbose = True
  24.            .VerboseSyntax = False
  25.            .WarningLevel = CodeDomUtil.WarningLevelEnum.Level3
  26.            .LibraryPaths.Add(IO.Directory.GetCurrentDirectory)
  27.        End With
  28.  
  29.        Dim referencedAssemblies As New List(Of String)
  30.        referencedAssemblies.AddRange({"System.dll", "System.Windows.Forms.dll"})
  31.  
  32.        ' Compile a VB Console App from string.
  33.        vbCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.Console,
  34.                                     targetFile:="C:\VB Default Console App.exe",
  35.                                     sourceCode:=CodeDomUtil.Templates.TemplateVbConsoleApp,
  36.                                     mainMemberName:="MainNamespace.MainModule",
  37.                                     referencedAssemblies:=referencedAssemblies,
  38.                                     resources:=Nothing,
  39.                                     iconFile:=Nothing)
  40.  
  41.        ' Compile a VB WinForms App from string.
  42.        vbCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.WinExe,
  43.                                     targetFile:="C:\VB Default WinForms App.exe",
  44.                                     sourceCode:=CodeDomUtil.Templates.TemplateVbWinFormsApp,
  45.                                     mainMemberName:="MainNamespace.MainClass",
  46.                                     referencedAssemblies:=referencedAssemblies,
  47.                                     resources:=Nothing,
  48.                                     iconFile:=Nothing)
  49.  
  50.        ' Compile a VB library from string.
  51.        vbCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.DynamicLinkLibrary,
  52.                                     targetFile:="C:\VB Default Library.dll",
  53.                                     sourceCode:=CodeDomUtil.Templates.TemplateVbLib,
  54.                                     mainMemberName:="MainNamespace.MainClass",
  55.                                     referencedAssemblies:=referencedAssemblies,
  56.                                     resources:=Nothing,
  57.                                     iconFile:=Nothing)
  58.  
  59.        ' Compile a VB local file that contains the sourcecode.
  60.        vbCompiler.CompileFromFile(netAssembly:=CodeDomUtil.NetAssembly.WinExe,
  61.                                   targetFile:="C:\VB Custom App.exe",
  62.                                   sourceFile:="C:\SourceCode.vb",
  63.                                   mainMemberName:="MainNamespace.MainClass",
  64.                                   referencedAssemblies:=referencedAssemblies,
  65.                                   resources:=Nothing,
  66.                                   iconFile:=Nothing)
  67.  
  68.    End Sub
  69.  
  70.    ''' ----------------------------------------------------------------------------------------------------
  71.    ''' <summary>
  72.    ''' Handles the <see cref="CodeDomUtil.Compiler.CompilerWorkDone"/> event of the <see cref="vbCompiler"/> instance.
  73.    ''' </summary>
  74.    ''' ----------------------------------------------------------------------------------------------------
  75.    ''' <param name="sender">
  76.    ''' The source of the event.
  77.    ''' </param>
  78.    '''
  79.    ''' <param name="e">
  80.    ''' The <see cref="CodeDomUtil.Compiler.CompilerWorkDoneEventArgs"/> instance containing the event data.
  81.    ''' </param>
  82.    ''' ----------------------------------------------------------------------------------------------------
  83.    Public Sub VbCompiler_CompilerWorkDone(ByVal sender As Object, ByVal e As CodeDomUtil.Compiler.CompilerWorkDoneEventArgs) _
  84.    Handles vbCompiler.CompilerWorkDone
  85.  
  86.        Console.WriteLine(String.Format("Compiler: {0}", e.CodeDomProvider.ToString))
  87.        Console.WriteLine(String.Format("Parameters: {0}", e.CompilerParameters.CompilerOptions))
  88.  
  89.        For Each war As CodeDomUtil.Compiler.Warning In e.CompilerWarnings
  90.            Console.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  91.        Next war
  92.  
  93.        For Each err As CodeDomUtil.Compiler.Error In e.CompileErrors
  94.            Console.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  95.        Next err
  96.  
  97.        If Not e.CompileErrors.Any Then
  98.            Console.WriteLine(String.Format("Compilation Successful: {0}", e.TargetFilePath))
  99.        End If
  100.  
  101.        Console.WriteLine()
  102.  
  103.    End Sub
  104.  
  105. End Class

Un ejemplo del compilador de C#:
Código
  1. Public NotInheritable Class Form1 : Inherits Form
  2.  
  3.    ''' ----------------------------------------------------------------------------------------------------
  4.    ''' <summary>
  5.    ''' The C# compiler instance.
  6.    ''' </summary>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    Dim WithEvents csCompiler As CodeDomUtil.Compiler =
  9.        New CodeDomUtil.CSharpCompiler(CodeDomUtil.CompilerVersions.V4)
  10.  
  11.    Private Sub Form1_Shown() Handles MyBase.Shown
  12.  
  13.        With Me.csCompiler.Compilersettings
  14.            .GenerateDebugInformation = True
  15.            .GenerateWarnings = True
  16.            .GenerateXmlDocumentation = True
  17.            .HighEntropyEnabled = True
  18.            .IntegerOverflowChecksEnabled = False
  19.            .OptimizationsEnabled = True
  20.            .OutputLanguage = New CultureInfo("en-US")
  21.            .Platform = CodeDomUtil.Platform.AnyCpu
  22.            .SubsystemVersion = CodeDomUtil.SubsystemVersions.WindowsXP
  23.            .TreatWarningsAsErrors = False
  24.            .Verbose = True
  25.            .VerboseSyntax = False
  26.            .WarningLevel = CodeDomUtil.WarningLevelEnum.Level3
  27.            .LibraryPaths.Add(IO.Directory.GetCurrentDirectory)
  28.        End With
  29.  
  30.        Dim referencedAssemblies As New List(Of String)
  31.        referencedAssemblies.AddRange({"System.dll", "System.Windows.Forms.dll"})
  32.  
  33.        ' Compile a C# Console App from string.
  34.        csCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.Console,
  35.                                     targetFile:="C:\CS Default Console App.exe",
  36.                                     sourceCode:=CodeDomUtil.Templates.TemplateCsConsoleApp,
  37.                                     mainMemberName:="MainNamespace.MainClass",
  38.                                     referencedAssemblies:=referencedAssemblies,
  39.                                     resources:=Nothing,
  40.                                     iconFile:=Nothing)
  41.  
  42.        ' Compile a C# WinForms App from string.
  43.        csCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.WinExe,
  44.                                     targetFile:="C:\CS Default WinForms App.exe",
  45.                                     sourceCode:=CodeDomUtil.Templates.TemplateCsWinFormsApp,
  46.                                     mainMemberName:="MainNamespace.MainClass",
  47.                                     referencedAssemblies:=referencedAssemblies,
  48.                                     resources:=Nothing,
  49.                                     iconFile:=Nothing)
  50.  
  51.        ' Compile a C# library from string.
  52.        csCompiler.CompileFromString(netAssembly:=CodeDomUtil.NetAssembly.DynamicLinkLibrary,
  53.                                     targetFile:="C:\CS Default Library.dll",
  54.                                     sourceCode:=CodeDomUtil.Templates.TemplateCsLib,
  55.                                     mainMemberName:="MainNamespace.MainClass",
  56.                                     referencedAssemblies:=referencedAssemblies,
  57.                                     resources:=Nothing,
  58.                                     iconFile:=Nothing)
  59.  
  60.        ' Compile a C# local file that contains the sourcecode.
  61.        csCompiler.CompileFromFile(netAssembly:=CodeDomUtil.NetAssembly.WinExe,
  62.                                   targetFile:="C:\CS Custom App.exe",
  63.                                   sourceFile:="C:\SourceCode.cs",
  64.                                   mainMemberName:="MainNamespace.MainClass",
  65.                                   referencedAssemblies:=referencedAssemblies,
  66.                                   resources:=Nothing,
  67.                                   iconFile:=Nothing)
  68.  
  69.    End Sub
  70.  
  71.    ''' ----------------------------------------------------------------------------------------------------
  72.    ''' <summary>
  73.    ''' Handles the <see cref="CodeDomUtil.Compiler.CompilerWorkDone"/> event of the csCompiler instance.
  74.    ''' </summary>
  75.    ''' ----------------------------------------------------------------------------------------------------
  76.    ''' <param name="sender">
  77.    ''' The source of the event.
  78.    ''' </param>
  79.    '''
  80.    ''' <param name="e">
  81.    ''' The <see cref="CodeDomUtil.Compiler.CompilerWorkDoneEventArgs"/> instance containing the event data.
  82.    ''' </param>
  83.    ''' ----------------------------------------------------------------------------------------------------
  84.    Public Sub CsCompiler_CompilerWorkDone(ByVal sender As Object, ByVal e As CodeDomUtil.Compiler.CompilerWorkDoneEventArgs) _
  85.    Handles csCompiler.CompilerWorkDone
  86.  
  87.        Console.WriteLine(String.Format("Compiler: {0}", e.CodeDomProvider.ToString))
  88.        Console.WriteLine(String.Format("Parameters: {0}", e.CompilerParameters.CompilerOptions))
  89.  
  90.        For Each war As CodeDomUtil.Compiler.Warning In e.CompilerWarnings
  91.            Console.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  92.        Next war
  93.  
  94.        For Each err As CodeDomUtil.Compiler.Error In e.CompileErrors
  95.            Console.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  96.        Next err
  97.  
  98.        If Not e.CompileErrors.Any Then
  99.            Console.WriteLine(String.Format("Compilation Successful: {0}", e.TargetFilePath))
  100.        End If
  101.  
  102.        Console.WriteLine()
  103.  
  104.    End Sub
  105.  
  106. End Class

Por último, muestro el diagrama de class:








Espero que les haya servido de algo este aporte.

Saludos!


« Última modificación: 19 Septiembre 2015, 18:25 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #492 en: 26 Octubre 2015, 17:33 pm »

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!
« Última modificación: 26 Octubre 2015, 17:36 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #493 en: 28 Octubre 2015, 02:58 am »

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
  1. Imports System
  2. Imports System.Threading.Tasks
  3.  
  4. Public Class Form1 : Inherits Form
  5.  
  6.    Private Sub Test() Handles Me.Shown
  7.  
  8.        Dim taskTestTime As Task(Of TestExecutionInfo) =
  9.            ProfillingUtil.TestTimeAsync(Sub()
  10.                                             For x As Integer = 0 To 5000
  11.                                                 Console.WriteLine(x)
  12.                                             Next x
  13.                                         End Sub)
  14.  
  15.        taskTestTime.ContinueWith(Sub() Me.ShowTestExecutionInfo(taskTestTime.Result))
  16.  
  17.    End Sub
  18.  
  19.    Private Sub ShowTestExecutionInfo(ByVal teInfo As TestExecutionInfo)
  20.  
  21.        Dim sb As New StringBuilder
  22.        Select Case teInfo.Success
  23.  
  24.            Case True
  25.                With sb ' Set an information message.
  26.                    .AppendLine(String.Format("Method Name: {0}", teInfo.Method.Name))
  27.                    .AppendLine()
  28.                    .AppendLine(String.Format("Elapsed Time: {0}", teInfo.Elapsed.ToString("hh\:mm\:ss\:fff")))
  29.                End With
  30.                MessageBox.Show(sb.ToString, "Code Execution Measurer", MessageBoxButtons.OK, MessageBoxIcon.Information)
  31.  
  32.            Case Else
  33.                With sb ' Set an error message.
  34.                    .AppendLine("Exception occurred during code execution measuring.")
  35.                    .AppendLine()
  36.                    .AppendLine(String.Format("Method Name: {0}", teInfo.Method.Name))
  37.                    .AppendLine()
  38.                    .AppendLine(String.Format("Exception Type: {0}", teInfo.Exception.GetType.Name))
  39.                    .AppendLine()
  40.                    .AppendLine("Exception Message:")
  41.                    .AppendLine(teInfo.Exception.Message)
  42.                    .AppendLine()
  43.                    .AppendLine("Exception Stack Trace:")
  44.                    .AppendLine(teInfo.Exception.StackTrace)
  45.                End With
  46.                MessageBox.Show(sb.ToString, "Code Execution Measurer", MessageBoxButtons.OK, MessageBoxIcon.Error)
  47.  
  48.        End Select
  49.  
  50.    End Sub
  51.  
  52. End Class

Ejemplo de uso síncronico:

Código
  1.    Sub Test()
  2.  
  3.        Dim successful As Boolean =
  4.            ProfillingUtil.TestSuccess(Sub() Convert.ToInt32("Hello World!"))
  5.  
  6.        Dim teInfo As TestExecutionInfo =
  7.            ProfillingUtil.TestTime(Sub()
  8.                                        For x As Integer = 0 To 2500
  9.                                            Console.WriteLine(x)
  10.                                        Next x
  11.                                    End Sub)
  12.  
  13.        Dim sb As New StringBuilder
  14.        Select Case teInfo.Success
  15.  
  16.            Case True
  17.                With sb ' Set an information message.
  18.                    .AppendLine(String.Format("Method Name: {0}", teInfo.Method.Name))
  19.                    .AppendLine()
  20.                    .AppendLine(String.Format("Elapsed Time: {0}", teInfo.Elapsed.ToString("hh\:mm\:ss\:fff")))
  21.                End With
  22.                MessageBox.Show(sb.ToString, "Code Execution Measurer", MessageBoxButtons.OK, MessageBoxIcon.Information)
  23.  
  24.            Case Else
  25.                With sb ' Set an error message.
  26.                    .AppendLine("Exception occurred during code execution measuring.")
  27.                    .AppendLine()
  28.                    .AppendLine(String.Format("Method Name: {0}", teInfo.Method.Name))
  29.                    .AppendLine()
  30.                    .AppendLine(String.Format("Exception Type: {0}", teInfo.Exception.GetType.Name))
  31.                    .AppendLine()
  32.                    .AppendLine("Exception Message:")
  33.                    .AppendLine(teInfo.Exception.Message)
  34.                    .AppendLine()
  35.                    .AppendLine("Exception Stack Trace:")
  36.                    .AppendLine(teInfo.Exception.StackTrace)
  37.                End With
  38.                MessageBox.Show(sb.ToString, "Code Execution Measurer", MessageBoxButtons.OK, MessageBoxIcon.Error)
  39.  
  40.        End Select
  41.  
  42.    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
« Última modificación: 28 Octubre 2015, 03:01 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #494 en: 29 Octubre 2015, 17:12 pm »

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
  1. Dim recorder As New WaveRecorder
  2.  
  3. Sub Button_Record_Click() Handles Button_Record.Click
  4.  
  5.    If Not (recorder.Status = WaveRecorder.RecorderStatus.Recording) Then
  6.        recorder.Record()
  7.    End If
  8.  
  9. End Sub
  10.  
  11. Sub Button_Stop_Click() Handles Button_Stop.Click
  12.  
  13.    If (recorder.Status = WaveRecorder.RecorderStatus.Recording) Then
  14.        recorder.Stop()
  15.    End If
  16.  
  17. End Sub
  18.  
  19. Sub Button_Play_Click() Handles Button_Play.Click
  20.  
  21.    If (recorder.Status = WaveRecorder.RecorderStatus.Stopped) Then
  22.        recorder.Play()
  23.    End If
  24.  
  25. End Sub
  26.  
  27. Sub Button_Delete_Click() Handles Button_Delete.Click
  28.  
  29.    If Not (recorder.Status = WaveRecorder.RecorderStatus.Empty) Then
  30.        recorder.Delete()
  31.    End If
  32.  
  33. End Sub
  34.  
  35. Sub Button_Save_Click() Handles Button_Save.Click
  36.  
  37.    If Not (recorder.Status = WaveRecorder.RecorderStatus.Empty) Then
  38.        recorder.Save("C:\File.wav", overWrite:=True)
  39.    End If
  40.  
  41. End Sub

Ejemplo de uso de la class AudioPlayer:

Código
  1. Dim player As New AudioPlayer
  2.  
  3. Sub Button_LoadFile_Click() Handles Button_LoadFile.Click
  4.  
  5.    If Not player.IsFileLoaded Then
  6.        player.LoadFile("C:\File.wav")
  7.    End If
  8.  
  9. End Sub
  10.  
  11. Sub Button_Play_Click() Handles Button_Play.Click
  12.  
  13.    If Not (player.Status = AudioPlayer.PlayerState.Playing) Then
  14.        player.Play(AudioPlayMode.Background)
  15.    End If
  16.  
  17. End Sub
  18.  
  19. Sub Button_Stop_Click() Handles Button_Stop.Click
  20.  
  21.    If Not (player.Status = AudioPlayer.PlayerState.Stopped) Then
  22.        player.Stop()
  23.    End If
  24.  
  25. End Sub
  26.  
  27. Sub Button_PauseResume_Click() Handles Button_PauseResume.Click
  28.  
  29.    If (player.Status = AudioPlayer.PlayerState.Playing) Then
  30.        player.Pause()
  31.  
  32.    ElseIf (player.Status = AudioPlayer.PlayerState.Paused) Then
  33.        player.Resume()
  34.  
  35.    End If
  36.  
  37. End Sub
  38.  
  39. Private Sub Button_SeekBackward_Click(sender As Object, e As EventArgs) Handles Button_SeekBackward.Click
  40.  
  41.    Dim currentPosition As Long = CLng(player.Position.TotalMilliseconds)
  42.  
  43.    If ((currentPosition - 5000) <= 0) Then
  44.        player.Seek(0)
  45.  
  46.    Else
  47.        player.Seek(currentPosition - 5000)
  48.  
  49.    End If
  50.  
  51. End Sub
  52.  
  53. Private Sub Button_SeekForward_Click(sender As Object, e As EventArgs) Handles Button_SeekForward.Click
  54.  
  55.    Dim currentPosition As Long = CLng(player.Position.TotalMilliseconds)
  56.  
  57.    If Not ((currentPosition + 5000) >= player.Length) Then
  58.        player.Seek(currentPosition + 5000)
  59.    End If
  60.  
  61. End Sub
  62.  
  63. Sub Button_UnloadFile_Click() Handles Button_UnloadFile.Click
  64.  
  65.    If player.IsFileLoaded Then
  66.        player.UnLoadFile()
  67.    End If
  68.  
  69. End Sub



Código fuente:

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


Saludos!
« Última modificación: 29 Octubre 2015, 17:14 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #495 en: 8 Noviembre 2015, 04:10 am »

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
  1. Dim colorString As New ColorString(Color.FromArgb(255, 91, 146, 198))
  2.  
  3. Console.WriteLine(String.Format("ColorString Structure Size: {0}", Marshal.SizeOf(GetType(ColorString)).ToString))
  4. Console.WriteLine(String.Format("Color.Tostring      : {0}", colorString.Color.ToString))
  5. Console.WriteLine(String.Format("ColorString.Tostring: {0}", colorString.ToString))
  6. Console.WriteLine()
  7.  
  8. Console.WriteLine(String.Format("Numeric Format (Standard)    : {0}", colorString.Numeric(ColorString.ColorStringSyntax.Standard)))
  9. Console.WriteLine(String.Format("Numeric Format (CSharp)      : {0}", colorString.Numeric(ColorString.ColorStringSyntax.CSharp)))
  10. Console.WriteLine(String.Format("Numeric Format (VbNet)       : {0}", colorString.Numeric(ColorString.ColorStringSyntax.VbNet)))
  11. Console.WriteLine(String.Format("Numeric Format (VisualStudio): {0}", colorString.Numeric(ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
  12. Console.WriteLine()
  13.  
  14. Console.WriteLine(String.Format("Hexadecimal Format (Standard)    : {0}", colorString.Hexadecimal(ColorString.ColorStringSyntax.Standard)))
  15. Console.WriteLine(String.Format("Hexadecimal Format (CSharp)      : {0}", colorString.Hexadecimal(ColorString.ColorStringSyntax.CSharp)))
  16. Console.WriteLine(String.Format("Hexadecimal Format (VbNet)       : {0}", colorString.Hexadecimal(ColorString.ColorStringSyntax.VbNet)))
  17. Console.WriteLine(String.Format("Hexadecimal Format (VisualStudio): {0}", colorString.Hexadecimal(ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
  18. Console.WriteLine()
  19.  
  20. Console.WriteLine(String.Format("Web Format (Standard)    : {0}", colorString.Web(ColorString.ColorStringSyntax.Standard)))
  21. Console.WriteLine(String.Format("Web Format (CSharp)      : {0}", colorString.Web(ColorString.ColorStringSyntax.CSharp)))
  22. Console.WriteLine(String.Format("Web Format (VbNet)       : {0}", colorString.Web(ColorString.ColorStringSyntax.VbNet)))
  23. Console.WriteLine(String.Format("Web Format (VisualStudio): {0}", colorString.Web(ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))

Resultado de ejecución:
Citar
ColorString 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
  1.    ''' ----------------------------------------------------------------------------------------------------
  2.    ''' <summary>
  3.    ''' Defines a <see cref="Color"/> with an unique string-format representation in the specified string-syntax.
  4.    ''' </summary>
  5.    ''' ----------------------------------------------------------------------------------------------------
  6.    ''' <example> This is a code example.
  7.    ''' <code>
  8.    ''' Dim colorString As New ColorString(Color.FromArgb(255, 91, 146, 198))
  9.    '''
  10.    ''' Console.WriteLine(String.Format("ColorString Structure Size: {0}", Marshal.SizeOf(GetType(ColorString)).ToString))
  11.    ''' Console.WriteLine(String.Format("Color.Tostring      : {0}", colorString.Color.ToString))
  12.    ''' Console.WriteLine(String.Format("ColorString.Tostring: {0}", colorString.ToString))
  13.    ''' Console.WriteLine()
  14.    ''' Console.WriteLine(String.Format("Numeric Format (Standard)    : {0}", colorString.Numeric(ColorUtil.ColorString.ColorStringSyntax.Standard)))
  15.    ''' Console.WriteLine(String.Format("Numeric Format (CSharp)      : {0}", colorString.Numeric(ColorUtil.ColorString.ColorStringSyntax.CSharp)))
  16.    ''' Console.WriteLine(String.Format("Numeric Format (VbNet)       : {0}", colorString.Numeric(ColorUtil.ColorString.ColorStringSyntax.VbNet)))
  17.    ''' Console.WriteLine(String.Format("Numeric Format (VisualStudio): {0}", colorString.Numeric(ColorUtil.ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
  18.    ''' Console.WriteLine()
  19.    ''' Console.WriteLine(String.Format("Hexadecimal Format (Standard)    : {0}", colorString.Hexadecimal(ColorUtil.ColorString.ColorStringSyntax.Standard)))
  20.    ''' Console.WriteLine(String.Format("Hexadecimal Format (CSharp)      : {0}", colorString.Hexadecimal(ColorUtil.ColorString.ColorStringSyntax.CSharp)))
  21.    ''' Console.WriteLine(String.Format("Hexadecimal Format (VbNet)       : {0}", colorString.Hexadecimal(ColorUtil.ColorString.ColorStringSyntax.VbNet)))
  22.    ''' Console.WriteLine(String.Format("Hexadecimal Format (VisualStudio): {0}", colorString.Hexadecimal(ColorUtil.ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
  23.    ''' Console.WriteLine()
  24.    ''' Console.WriteLine(String.Format("Web Format (Standard)    : {0}", colorString.Web(ColorUtil.ColorString.ColorStringSyntax.Standard)))
  25.    ''' Console.WriteLine(String.Format("Web Format (CSharp)      : {0}", colorString.Web(ColorUtil.ColorString.ColorStringSyntax.CSharp)))
  26.    ''' Console.WriteLine(String.Format("Web Format (VbNet)       : {0}", colorString.Web(ColorUtil.ColorString.ColorStringSyntax.VbNet)))
  27.    ''' Console.WriteLine(String.Format("Web Format (VisualStudio): {0}", colorString.Web(ColorUtil.ColorString.ColorStringSyntax.VisualStudioPropertyGrid)))
  28.    ''' </code>
  29.    ''' </example>
  30.    ''' ----------------------------------------------------------------------------------------------------
  31.    <Serializable>
  32.    <StructLayout(LayoutKind.Sequential)>
  33.    Public Structure ColorString
  34.  
  35. #Region " Properties "
  36.  
  37.        ''' ----------------------------------------------------------------------------------------------------
  38.        ''' <summary>
  39.        ''' Gets the <see cref="Color"/>.
  40.        ''' </summary>
  41.        ''' ----------------------------------------------------------------------------------------------------
  42.        ''' <value>
  43.        ''' The <see cref="Color"/>.
  44.        ''' </value>
  45.        ''' ----------------------------------------------------------------------------------------------------
  46.        Public ReadOnly Property Color As Color
  47.            <DebuggerStepThrough>
  48.            Get
  49.                Return Me.colorB
  50.            End Get
  51.        End Property
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        ''' <summary>
  54.        ''' ( Backing field )
  55.        ''' The <see cref="Color"/>.
  56.        ''' </summary>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        Private ReadOnly colorB As Color
  59.  
  60.        ''' ----------------------------------------------------------------------------------------------------
  61.        ''' <summary>
  62.        ''' Gets the numeric color-string representation for this instance.
  63.        ''' </summary>
  64.        ''' ----------------------------------------------------------------------------------------------------
  65.        ''' <value>
  66.        ''' The numeric color-string representation.
  67.        ''' </value>
  68.        ''' ----------------------------------------------------------------------------------------------------
  69.        Public ReadOnly Property Numeric(ByVal colorStringSyntax As ColorStringSyntax) As String
  70.            <DebuggerStepThrough>
  71.            Get
  72.                Return Me.GetNumericString(colorStringSyntax)
  73.            End Get
  74.        End Property
  75.  
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <summary>
  78.        ''' Gets the Hexadecimal color-string representation for this instance.
  79.        ''' </summary>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <value>
  82.        ''' The Hexadecimal color-string representation.
  83.        ''' </value>
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        Public ReadOnly Property Hexadecimal(ByVal colorStringSyntax As ColorStringSyntax) As String
  86.            <DebuggerStepThrough>
  87.            Get
  88.                Return Me.GetHexadecimalString(colorStringSyntax)
  89.            End Get
  90.        End Property
  91.  
  92.        ''' ----------------------------------------------------------------------------------------------------
  93.        ''' <summary>
  94.        ''' Gets the Web color-string representation for this instance.
  95.        ''' </summary>
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        ''' <value>
  98.        ''' The Web color-string representation.
  99.        ''' </value>
  100.        ''' ----------------------------------------------------------------------------------------------------
  101.        Public ReadOnly Property Web(ByVal colorStringSyntax As ColorStringSyntax) As String
  102.            <DebuggerStepThrough>
  103.            Get
  104.                Return Me.GetWebString(colorStringSyntax)
  105.            End Get
  106.        End Property
  107.  
  108. #End Region
  109.  
  110. #Region " Enumerations "
  111.  
  112.        ''' ----------------------------------------------------------------------------------------------------
  113.        ''' <summary>
  114.        ''' Specifies a string syntax to represent a color value.
  115.        ''' </summary>
  116.        ''' ----------------------------------------------------------------------------------------------------
  117.        Public Enum ColorStringSyntax As Integer
  118.  
  119.            ''' <summary>
  120.            ''' Standard syntax.
  121.            ''' </summary>
  122.            Standard = 0
  123.  
  124.            ''' <summary>
  125.            ''' C# language syntax.
  126.            ''' </summary>
  127.            CSharp = 1
  128.  
  129.            ''' <summary>
  130.            ''' Visual Basic.Net language syntax.
  131.            ''' </summary>
  132.            VbNet = 2
  133.  
  134.            ''' <summary>
  135.            ''' VisualStudio IDE's property grid syntax.
  136.            ''' </summary>
  137.            VisualStudioPropertyGrid = 3
  138.  
  139.        End Enum
  140.  
  141. #End Region
  142.  
  143. #Region " Constructors "
  144.  
  145.        ''' ----------------------------------------------------------------------------------------------------
  146.        ''' <summary>
  147.        ''' Initializes a new instance of the <see cref="ColorString"/> structure.
  148.        ''' </summary>
  149.        ''' ----------------------------------------------------------------------------------------------------
  150.        ''' <param name="color">
  151.        ''' The source <see cref="Color"/>.
  152.        ''' </param>
  153.        ''' ----------------------------------------------------------------------------------------------------
  154.        <DebuggerStepThrough>
  155.        Public Sub New(ByVal color As Color)
  156.  
  157.            Me.colorB = color
  158.  
  159.        End Sub
  160.  
  161.        ''' ----------------------------------------------------------------------------------------------------
  162.        ''' <summary>
  163.        ''' Initializes a new instance of the <see cref="ColorString"/> structure.
  164.        ''' </summary>
  165.        ''' ----------------------------------------------------------------------------------------------------
  166.        ''' <param name="brush">
  167.        ''' The source <see cref="SolidBrush"/>.
  168.        ''' </param>
  169.        ''' ----------------------------------------------------------------------------------------------------
  170.        <DebuggerStepThrough>
  171.        Public Sub New(ByVal brush As SolidBrush)
  172.  
  173.            Me.colorB = brush.Color
  174.  
  175.        End Sub
  176.  
  177.        ''' ----------------------------------------------------------------------------------------------------
  178.        ''' <summary>
  179.        ''' Initializes a new instance of the <see cref="ColorString"/> structure.
  180.        ''' </summary>
  181.        ''' ----------------------------------------------------------------------------------------------------
  182.        ''' <param name="pen">
  183.        ''' The source <see cref="Pen"/>.
  184.        ''' </param>
  185.        ''' ----------------------------------------------------------------------------------------------------
  186.        <DebuggerStepThrough>
  187.        Public Sub New(ByVal pen As Pen)
  188.  
  189.            Me.colorB = pen.Color
  190.  
  191.        End Sub
  192.  
  193. #End Region
  194.  
  195. #Region " Private Methods "
  196.  
  197.        ''' ----------------------------------------------------------------------------------------------------
  198.        ''' <summary>
  199.        ''' Gets the numeric string representation of a <see cref="Color"/>, in the specified <see cref="ColorStringSyntax"/> syntax.
  200.        ''' </summary>
  201.        ''' ----------------------------------------------------------------------------------------------------
  202.        ''' <param name="syntax">
  203.        ''' The color-string syntax.
  204.        ''' </param>
  205.        ''' ----------------------------------------------------------------------------------------------------
  206.        ''' <returns>
  207.        ''' The numeric string representation.
  208.        ''' </returns>
  209.        ''' ----------------------------------------------------------------------------------------------------
  210.        ''' <exception cref="InvalidEnumArgumentException">
  211.        ''' syntax
  212.        ''' </exception>
  213.        ''' ----------------------------------------------------------------------------------------------------
  214.        <DebuggerStepThrough>
  215.        Private Function GetNumericString(ByVal syntax As ColorStringSyntax) As String
  216.  
  217.            Dim byteString As String =
  218.                String.Format("{0}, {1}, {2}, {3}",
  219.                              Convert.ToString(Me.colorB.A),
  220.                              Convert.ToString(Me.colorB.R),
  221.                              Convert.ToString(Me.colorB.G),
  222.                              Convert.ToString(Me.colorB.B))
  223.  
  224.            Select Case syntax
  225.  
  226.                Case ColorString.ColorStringSyntax.Standard
  227.                    Return byteString
  228.  
  229.                Case ColorString.ColorStringSyntax.CSharp
  230.                    Return String.Format("Color.FromArgb({0});", byteString)
  231.  
  232.                Case ColorString.ColorStringSyntax.VbNet
  233.                    Return String.Format("Color.FromArgb({0})", byteString)
  234.  
  235.                Case ColorString.ColorStringSyntax.VisualStudioPropertyGrid
  236.                    Return byteString.Replace(",", ";")
  237.  
  238.                Case Else
  239.                    Throw New InvalidEnumArgumentException("syntax", syntax, GetType(ColorStringSyntax))
  240.  
  241.            End Select
  242.  
  243.        End Function
  244.  
  245.        ''' ----------------------------------------------------------------------------------------------------
  246.        ''' <summary>
  247.        ''' Gets the numeric string representation of a <see cref="Color"/>, in the specified <see cref="ColorStringSyntax"/> syntax.
  248.        ''' </summary>
  249.        ''' ----------------------------------------------------------------------------------------------------
  250.        ''' <param name="syntax">
  251.        ''' The color-string syntax.
  252.        ''' </param>
  253.        ''' ----------------------------------------------------------------------------------------------------
  254.        ''' <returns>
  255.        ''' The numeric string representation.
  256.        ''' </returns>
  257.        ''' ----------------------------------------------------------------------------------------------------
  258.        ''' <exception cref="InvalidEnumArgumentException">
  259.        ''' syntax
  260.        ''' </exception>
  261.        ''' ----------------------------------------------------------------------------------------------------
  262.        <DebuggerStepThrough>
  263.        Private Function GetHexadecimalString(ByVal syntax As ColorStringSyntax) As String
  264.  
  265.            Dim a As String = Convert.ToString(Me.colorB.A, 16).ToUpper
  266.            Dim r As String = Convert.ToString(Me.colorB.R, 16).ToUpper
  267.            Dim g As String = Convert.ToString(Me.colorB.G, 16).ToUpper
  268.            Dim b As String = Convert.ToString(Me.colorB.B, 16).ToUpper
  269.  
  270.            Select Case syntax
  271.  
  272.                Case ColorString.ColorStringSyntax.Standard
  273.                    Return String.Format("{0}{1}{2}{3}", a, r, g, b)
  274.  
  275.                Case ColorString.ColorStringSyntax.CSharp
  276.                    Return String.Format("Color.FromArgb(0x{0}, 0x{1}, 0x{2}, 0x{3});", a, r, g, b)
  277.  
  278.                Case ColorString.ColorStringSyntax.VbNet
  279.                    Return String.Format("Color.FromArgb(&H{0}, &H{1}, &H{2}, &H{3})", a, r, g, b)
  280.  
  281.                Case ColorString.ColorStringSyntax.VisualStudioPropertyGrid
  282.                    Return String.Format("0x{0}{1}{2}{3}", a, r, g, b)
  283.  
  284.                Case Else
  285.                    Throw New InvalidEnumArgumentException("syntax", syntax, GetType(ColorStringSyntax))
  286.  
  287.            End Select
  288.  
  289.        End Function
  290.  
  291.        ''' ----------------------------------------------------------------------------------------------------
  292.        ''' <summary>
  293.        ''' Gets the Web string representation of a <see cref="Color"/>, in the specified <see cref="ColorStringSyntax"/> syntax.
  294.        ''' </summary>
  295.        ''' ----------------------------------------------------------------------------------------------------
  296.        ''' <param name="syntax">
  297.        ''' The color-string syntax.
  298.        ''' </param>
  299.        ''' ----------------------------------------------------------------------------------------------------
  300.        ''' <returns>
  301.        ''' The Web string representation.
  302.        ''' </returns>
  303.        ''' ----------------------------------------------------------------------------------------------------
  304.        ''' <exception cref="InvalidEnumArgumentException">
  305.        ''' syntax
  306.        ''' </exception>
  307.        ''' ----------------------------------------------------------------------------------------------------
  308.        <DebuggerStepThrough>
  309.        Private Function GetWebString(ByVal syntax As ColorStringSyntax) As String
  310.  
  311.            Dim htmlString As String = ColorTranslator.ToHtml(Color)
  312.  
  313.            Select Case syntax
  314.  
  315.                Case ColorString.ColorStringSyntax.Standard
  316.                    Return htmlString
  317.  
  318.                Case ColorString.ColorStringSyntax.CSharp
  319.                    Return String.Format("ColorTranslator.FromHtml(""{0}"");", htmlString)
  320.  
  321.                Case ColorString.ColorStringSyntax.VbNet
  322.                    Return String.Format("ColorTranslator.FromHtml(""{0}"")", htmlString)
  323.  
  324.                Case ColorString.ColorStringSyntax.VisualStudioPropertyGrid
  325.                    Return htmlString
  326.  
  327.                Case Else
  328.                    Throw New InvalidEnumArgumentException("syntax", syntax, GetType(ColorStringSyntax))
  329.  
  330.            End Select
  331.  
  332.        End Function
  333.  
  334. #End Region
  335.  
  336. #Region " Public Methods "
  337.  
  338.        ''' ----------------------------------------------------------------------------------------------------
  339.        ''' <summary>
  340.        ''' Performs an implicit conversion from <see cref="ColorString"/> to <see cref="Color"/>.
  341.        ''' </summary>
  342.        ''' ----------------------------------------------------------------------------------------------------
  343.        ''' <param name="colorString">
  344.        ''' The <see cref="ColorString"/>.
  345.        ''' </param>
  346.        ''' ----------------------------------------------------------------------------------------------------
  347.        ''' <returns>
  348.        ''' The resulting <see cref="Color"/> of the conversion.
  349.        ''' </returns>
  350.        ''' ----------------------------------------------------------------------------------------------------
  351.        Public Shared Widening Operator CType(ByVal colorString As ColorString) As Color
  352.  
  353.            Return Drawing.Color.FromArgb(colorString.Color.R, colorString.Color.G, colorString.Color.B)
  354.  
  355.        End Operator
  356.  
  357.        ''' ----------------------------------------------------------------------------------------------------
  358.        ''' <summary>
  359.        ''' Performs an implicit conversion from <see cref="Color"/> to <see cref="ColorString"/>.
  360.        ''' </summary>
  361.        ''' ----------------------------------------------------------------------------------------------------
  362.        ''' <param name="color">
  363.        ''' The <see cref="Color"/>.
  364.        ''' </param>
  365.        ''' ----------------------------------------------------------------------------------------------------
  366.        ''' <returns>
  367.        ''' The resulting <see cref="ColorString"/> of the conversion.
  368.        ''' </returns>
  369.        ''' ----------------------------------------------------------------------------------------------------
  370.        Public Shared Narrowing Operator CType(ByVal color As Color) As ColorString
  371.  
  372.            Return New ColorString(color)
  373.  
  374.        End Operator
  375.  
  376.        ''' ----------------------------------------------------------------------------------------------------
  377.        ''' <summary>
  378.        ''' Implements the operator =.
  379.        ''' </summary>
  380.        ''' ----------------------------------------------------------------------------------------------------
  381.        ''' <param name="colorString1">
  382.        ''' The first <see cref="ColorString"/> to evaluate.
  383.        ''' </param>
  384.        '''
  385.        ''' <param name="colorString2">
  386.        ''' The second <see cref="ColorString"/> to evaluate.
  387.        ''' </param>
  388.        ''' ----------------------------------------------------------------------------------------------------
  389.        ''' <returns>
  390.        ''' The result of the operator.
  391.        ''' </returns>
  392.        ''' ----------------------------------------------------------------------------------------------------
  393.        Public Shared Operator =(ByVal colorString1 As ColorString,
  394.                                 ByVal colorString2 As ColorString) As Boolean
  395.  
  396.            Return colorString1.Equals(colorString2)
  397.  
  398.        End Operator
  399.  
  400.        ''' ----------------------------------------------------------------------------------------------------
  401.        ''' <summary>
  402.        ''' Implements the operator &lt;&gt;.
  403.        ''' </summary>
  404.        ''' ----------------------------------------------------------------------------------------------------
  405.        ''' <param name="colorString1">
  406.        ''' The first <see cref="ColorString"/> to evaluate.
  407.        ''' </param>
  408.        '''
  409.        ''' <param name="colorString2">
  410.        ''' The second <see cref="ColorString"/> to evaluate.
  411.        ''' </param>
  412.        ''' ----------------------------------------------------------------------------------------------------
  413.        ''' <returns>
  414.        ''' The result of the operator.
  415.        ''' </returns>
  416.        ''' ----------------------------------------------------------------------------------------------------
  417.        Public Shared Operator <>(ByVal colorString1 As ColorString,
  418.                                  ByVal colorString2 As ColorString) As Boolean
  419.  
  420.            Return Not colorString1.Equals(colorString2)
  421.  
  422.        End Operator
  423.  
  424.        ''' ----------------------------------------------------------------------------------------------------
  425.        ''' <summary>
  426.        ''' Determines whether the specified <see cref="System.Object"/> is equal to this instance.
  427.        ''' </summary>
  428.        ''' ----------------------------------------------------------------------------------------------------
  429.        ''' <param name="obj">
  430.        ''' Another object to compare to.
  431.        ''' </param>
  432.        ''' ----------------------------------------------------------------------------------------------------
  433.        ''' <returns>
  434.        ''' <see langword="True"/> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <see langword="False"/>.
  435.        ''' </returns>
  436.        ''' ----------------------------------------------------------------------------------------------------
  437.        Public Overrides Function Equals(ByVal obj As Object) As Boolean
  438.  
  439.            If (TypeOf obj Is ColorString) Then
  440.                Return Me.Equals(DirectCast(obj, ColorString))
  441.  
  442.            ElseIf (TypeOf obj Is Color) Then
  443.                Return Me.Equals(New ColorString(DirectCast(obj, Color)))
  444.  
  445.            Else
  446.                Return False
  447.  
  448.            End If
  449.  
  450.        End Function
  451.  
  452.        ''' ----------------------------------------------------------------------------------------------------
  453.        ''' <summary>
  454.        ''' Determines whether the specified <see cref="ColorString"/> is equal to this instance.
  455.        ''' </summary>
  456.        ''' ----------------------------------------------------------------------------------------------------
  457.        ''' <param name="colorString">
  458.        ''' Another <see cref="ColorString"/> to compare to.
  459.        ''' </param>
  460.        ''' ----------------------------------------------------------------------------------------------------
  461.        ''' <returns>
  462.        ''' <see langword="True"/> if the specified <see cref="ColorString"/> is equal to this instance; otherwise, <see langword="False"/>.
  463.        ''' </returns>
  464.        ''' ----------------------------------------------------------------------------------------------------
  465.        Public Overloads Function Equals(ByVal colorString As ColorString) As Boolean
  466.  
  467.            Return (colorString.Color.ToArgb = Me.colorB.ToArgb)
  468.  
  469.        End Function
  470.  
  471.        ''' ----------------------------------------------------------------------------------------------------
  472.        ''' <summary>
  473.        ''' Returns a hash code for this instance.
  474.        ''' </summary>
  475.        ''' ----------------------------------------------------------------------------------------------------
  476.        ''' <returns>
  477.        ''' A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
  478.        ''' </returns>
  479.        ''' ----------------------------------------------------------------------------------------------------
  480.        Public Overrides Function GetHashCode() As Integer
  481.  
  482.            Return Me.colorB.GetHashCode()
  483.  
  484.        End Function
  485.  
  486.        ''' ----------------------------------------------------------------------------------------------------
  487.        ''' <summary>
  488.        ''' Returns a <see cref="System.String"/> that represents this instance.
  489.        ''' </summary>
  490.        ''' ----------------------------------------------------------------------------------------------------
  491.        ''' <returns>
  492.        ''' A <see cref="System.String"/> that represents this instance.
  493.        ''' </returns>
  494.        ''' ----------------------------------------------------------------------------------------------------
  495.        Public Overrides Function ToString() As String
  496.  
  497.            Return String.Format(CultureInfo.CurrentCulture, "{{A={0}, R={1}, G={2}, B={3}}}",
  498.                                 Me.colorB.A, Me.colorB.R, Me.colorB.G, Me.colorB.B)
  499.  
  500.        End Function
  501.  
  502. #End Region
  503.  
  504.    End Structure
« Última modificación: 8 Noviembre 2015, 04:25 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #496 en: 9 Noviembre 2015, 15:28 pm »

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
  1. Dim md5 As String = CryptoUtil.ComputeHashOfString(Of MD5CryptoServiceProvider)("Hello World!")
  2. Dim sha1 As String = CryptoUtil.ComputeHashOfString(Of SHA1CryptoServiceProvider)("Hello World!")
  3. Dim sha256 As String = CryptoUtil.ComputeHashOfString(Of SHA256CryptoServiceProvider)("Hello World!")
  4. Dim sha384 As String = CryptoUtil.ComputeHashOfString(Of SHA384CryptoServiceProvider)("Hello World!")
  5. Dim sha512 As String = CryptoUtil.ComputeHashOfString(Of SHA512CryptoServiceProvider)("Hello World!")

Código
  1. Dim md5 As String = CryptoUtil.ComputeHashOfFile(Of MD5CryptoServiceProvider)("C:\File.ext")
  2. Dim sha1 As String = CryptoUtil.ComputeHashOfFile(Of SHA1CryptoServiceProvider)("C:\File.ext")
  3. Dim sha256 As String = CryptoUtil.ComputeHashOfFile(Of SHA256CryptoServiceProvider)("C:\File.ext")
  4. Dim sha384 As String = CryptoUtil.ComputeHashOfFile(Of SHA384CryptoServiceProvider)("C:\File.ext")
  5. Dim sha512 As String = CryptoUtil.ComputeHashOfFile(Of SHA512CryptoServiceProvider)("C:\File.ext")

Código fuente:
Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Computes the hash, using the given hash algorithm, for the specified string.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <example> This is a code example.
  7. ''' <code>
  8. ''' Dim md5 As String = CryptoUtil.ComputeHashOfString(Of MD5CryptoServiceProvider)("Hello World!")
  9. ''' Dim sha1 As String = CryptoUtil.ComputeHashOfString(Of SHA1CryptoServiceProvider)("Hello World!")
  10. ''' Dim sha256 As String = CryptoUtil.ComputeHashOfString(Of SHA256CryptoServiceProvider)("Hello World!")
  11. ''' Dim sha384 As String = CryptoUtil.ComputeHashOfString(Of SHA384CryptoServiceProvider)("Hello World!")
  12. ''' Dim sha512 As String = CryptoUtil.ComputeHashOfString(Of SHA512CryptoServiceProvider)("Hello World!")
  13. ''' </code>
  14. ''' </example>
  15. ''' ----------------------------------------------------------------------------------------------------
  16. ''' <typeparam name="T">
  17. ''' The <see cref="HashAlgorithm"/> provider.
  18. ''' </typeparam>
  19. '''
  20. ''' <param name="str">
  21. ''' The string.
  22. ''' </param>
  23. '''
  24. ''' <param name="enc">
  25. ''' The text <see cref="Encoding"/>.
  26. ''' </param>
  27. ''' ----------------------------------------------------------------------------------------------------
  28. ''' <returns>
  29. ''' An Hexadecimal representation of the resulting hash value.
  30. ''' </returns>
  31. ''' ----------------------------------------------------------------------------------------------------
  32. <DebuggerStepThrough>
  33. Public Function ComputeHashOfString(Of T As HashAlgorithm)(ByVal str As String,
  34.                                                           Optional ByVal enc As Encoding = Nothing) As String
  35.  
  36.    If (enc Is Nothing) Then
  37.        enc = Encoding.Default
  38.    End If
  39.  
  40.    Using algorithm As HashAlgorithm = DirectCast(Activator.CreateInstance(GetType(T)), HashAlgorithm)
  41.  
  42.        Dim data As Byte() = enc.GetBytes(str)
  43.        Dim hash As Byte() = algorithm.ComputeHash(data)
  44.        Dim sb As New StringBuilder(capacity:=hash.Length * 2)
  45.  
  46.        For Each b As Byte In hash
  47.            sb.Append(b.ToString("X2"))
  48.        Next
  49.  
  50.        Return sb.ToString
  51.  
  52.    End Using
  53.  
  54. End Function
  55.  
  56. ''' ----------------------------------------------------------------------------------------------------
  57. ''' <summary>
  58. ''' Computes the hash, using the given hash algorithm, for the specified file.
  59. ''' </summary>
  60. ''' ----------------------------------------------------------------------------------------------------
  61. ''' <example> This is a code example.
  62. ''' <code>
  63. ''' Dim md5 As String = CryptoUtil.ComputeHashOfFile(Of MD5CryptoServiceProvider)("C:\File.ext")
  64. ''' Dim sha1 As String = CryptoUtil.ComputeHashOfFile(Of SHA1CryptoServiceProvider)("C:\File.ext")
  65. ''' Dim sha256 As String = CryptoUtil.ComputeHashOfFile(Of SHA256CryptoServiceProvider)("C:\File.ext")
  66. ''' Dim sha384 As String = CryptoUtil.ComputeHashOfFile(Of SHA384CryptoServiceProvider)("C:\File.ext")
  67. ''' Dim sha512 As String = CryptoUtil.ComputeHashOfFile(Of SHA512CryptoServiceProvider)("C:\File.ext")
  68. ''' </code>
  69. ''' </example>
  70. ''' ----------------------------------------------------------------------------------------------------
  71. ''' <typeparam name="T">
  72. ''' The <see cref="HashAlgorithm"/> provider.
  73. ''' </typeparam>
  74. '''
  75. ''' <param name="filepath">
  76. ''' The filepath.
  77. ''' </param>
  78. ''' ----------------------------------------------------------------------------------------------------
  79. ''' <returns>
  80. ''' An Hexadecimal representation of the resulting hash value.
  81. ''' </returns>
  82. ''' ----------------------------------------------------------------------------------------------------
  83. <DebuggerStepThrough>
  84. Public Function ComputeHashOfFile(Of T As HashAlgorithm)(ByVal filepath As String) As String
  85.  
  86.    Using fs As New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)
  87.  
  88.        Using algorithm As HashAlgorithm = DirectCast(Activator.CreateInstance(GetType(T)), HashAlgorithm)
  89.  
  90.            Dim hash As Byte() = algorithm.ComputeHash(fs)
  91.            Dim sb As New StringBuilder(capacity:=hash.Length * 2)
  92.  
  93.            For Each b As Byte In hash
  94.                sb.Append(b.ToString("X2"))
  95.            Next b
  96.  
  97.            Return sb.ToString
  98.  
  99.        End Using
  100.  
  101.    End Using
  102.  
  103. End Function
« Última modificación: 9 Noviembre 2015, 15:30 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #497 en: 11 Noviembre 2015, 08:25 am »

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

Ejemplo de uso:
Código
  1.    Friend WithEvents DriveMon As New DriveWatcher
  2.  
  3.    ''' ----------------------------------------------------------------------------------------------------
  4.    ''' <summary>
  5.    ''' Handles the <see cref="DriveWatcher.DriveStatusChanged"/> event of the <see cref="DriveMon"/> instance.
  6.    ''' </summary>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    ''' <param name="sender">
  9.    ''' The source of the event.
  10.    ''' </param>
  11.    '''
  12.    ''' <param name="e">
  13.    ''' The <see cref="DriveWatcher.DriveStatusChangedEventArgs"/> instance containing the event data.
  14.    ''' </param>
  15.    ''' ----------------------------------------------------------------------------------------------------
  16.    Private Sub DriveMon_DriveStatusChanged(ByVal sender As Object, ByVal e As DriveWatcher.DriveStatusChangedEventArgs) _
  17.    Handles DriveMon.DriveStatusChanged
  18.  
  19.        Select Case e.DeviceEvent
  20.  
  21.            Case DriveWatcher.DeviceEvents.Arrival
  22.                Dim sb As New StringBuilder
  23.                sb.AppendLine("New drive connected...'")
  24.                sb.AppendLine(String.Format("Type......: {0}", e.DriveInfo.DriveType.ToString))
  25.                sb.AppendLine(String.Format("Label.....: {0}", e.DriveInfo.VolumeLabel))
  26.                sb.AppendLine(String.Format("Name......: {0}", e.DriveInfo.Name))
  27.                sb.AppendLine(String.Format("Root......: {0}", e.DriveInfo.RootDirectory))
  28.                sb.AppendLine(String.Format("FileSystem: {0}", e.DriveInfo.DriveFormat))
  29.                sb.AppendLine(String.Format("Size......: {0} GB", (e.DriveInfo.TotalSize / (1024 ^ 3)).ToString("n1")))
  30.                sb.AppendLine(String.Format("Free space: {0} GB", (e.DriveInfo.AvailableFreeSpace / (1024 ^ 3)).ToString("n1")))
  31.                Console.WriteLine(sb.ToString)
  32.  
  33.            Case DriveWatcher.DeviceEvents.RemoveComplete
  34.                Dim sb As New StringBuilder
  35.                sb.AppendLine("Drive disconnected...'")
  36.                sb.AppendLine(String.Format("Name: {0}", e.DriveInfo.Name))
  37.                sb.AppendLine(String.Format("Root: {0}", e.DriveInfo.RootDirectory))
  38.                Console.WriteLine(sb.ToString)
  39.  
  40.        End Select
  41.  
  42.    End Sub
  43.  
  44.    Private Sub StartMon_Click(ByVal sender As Object, ByVal e As EventArgs) _
  45.    Handles Button_StartMon.Click
  46.  
  47.        Me.DriveMon.Start()
  48.  
  49.    End Sub
  50.  
  51.    Private Sub StopMon_Click(ByVal sender As Object, ByVal e As EventArgs) _
  52.    Handles Button_StopMon.Click
  53.  
  54.        Me.DriveMon.Stop()
  55.  
  56.    End Sub

Código fuente:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 11-November-2015
  4. ' ***********************************************************************
  5. ' <copyright file="DriveWatcher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. ''' ----------------------------------------------------------------------------------------------------
  11. ''' <summary>
  12. ''' A device insertion and removal monitor.
  13. ''' </summary>
  14. ''' ----------------------------------------------------------------------------------------------------
  15. Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
  16.  
  17. #Region " Properties "
  18.  
  19.    ''' ----------------------------------------------------------------------------------------------------
  20.    ''' <summary>
  21.    ''' Gets the connected drives on this computer.
  22.    ''' </summary>
  23.    ''' ----------------------------------------------------------------------------------------------------
  24.    Public ReadOnly Property Drives As IEnumerable(Of DriveInfo)
  25.        <DebuggerStepThrough>
  26.        Get
  27.            Return DriveInfo.GetDrives
  28.        End Get
  29.    End Property
  30.  
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    ''' <summary>
  33.    ''' Gets a value that determines whether the monitor is running.
  34.    ''' </summary>
  35.    ''' ----------------------------------------------------------------------------------------------------
  36.    Public ReadOnly Property IsRunning As Boolean
  37.        <DebuggerStepThrough>
  38.        Get
  39.            Return Me.isRunningB
  40.        End Get
  41.    End Property
  42.    Private isRunningB As Boolean
  43.  
  44. #End Region
  45.  
  46. #Region " Events "
  47.  
  48.    ''' ----------------------------------------------------------------------------------------------------
  49.    ''' <summary>
  50.    ''' A list of event delegates.
  51.    ''' </summary>
  52.    ''' ----------------------------------------------------------------------------------------------------
  53.    Private ReadOnly events As EventHandlerList
  54.  
  55.    ''' ----------------------------------------------------------------------------------------------------
  56.    ''' <summary>
  57.    ''' Occurs when a drive is inserted, removed, or changed.
  58.    ''' </summary>
  59.    ''' ----------------------------------------------------------------------------------------------------
  60.    Public Custom Event DriveStatusChanged As EventHandler(Of DriveStatusChangedEventArgs)
  61.  
  62.        <DebuggerNonUserCode>
  63.        <DebuggerStepThrough>
  64.        AddHandler(ByVal value As EventHandler(Of DriveStatusChangedEventArgs))
  65.            Me.events.AddHandler("DriveStatusChangedEvent", value)
  66.        End AddHandler
  67.  
  68.        <DebuggerNonUserCode>
  69.        <DebuggerStepThrough>
  70.        RemoveHandler(ByVal value As EventHandler(Of DriveStatusChangedEventArgs))
  71.            Me.events.RemoveHandler("DriveStatusChangedEvent", value)
  72.        End RemoveHandler
  73.  
  74.        <DebuggerNonUserCode>
  75.        <DebuggerStepThrough>
  76.        RaiseEvent(ByVal sender As Object, ByVal e As DriveStatusChangedEventArgs)
  77.            Dim handler As EventHandler(Of DriveStatusChangedEventArgs) =
  78.                DirectCast(Me.events("DriveStatusChangedEvent"), EventHandler(Of DriveStatusChangedEventArgs))
  79.  
  80.            If (handler IsNot Nothing) Then
  81.                handler.Invoke(sender, e)
  82.            End If
  83.        End RaiseEvent
  84.  
  85.    End Event
  86.  
  87. #End Region
  88.  
  89. #Region " Events Data "
  90.  
  91. #Region " DriveStatusChangedEventArgs "
  92.  
  93.    ''' ----------------------------------------------------------------------------------------------------
  94.    ''' <summary>
  95.    ''' Contains the event-data of a <see cref="DriveStatusChanged"/> event.
  96.    ''' </summary>
  97.    ''' ----------------------------------------------------------------------------------------------------
  98.    Public NotInheritable Class DriveStatusChangedEventArgs : Inherits EventArgs
  99.  
  100. #Region " Properties "
  101.  
  102.        ''' ----------------------------------------------------------------------------------------------------
  103.        ''' <summary>
  104.        ''' Gets the device event that occurred.
  105.        ''' </summary>
  106.        ''' ----------------------------------------------------------------------------------------------------
  107.        ''' <value>
  108.        ''' The drive info.
  109.        ''' </value>
  110.        ''' ----------------------------------------------------------------------------------------------------
  111.        Public ReadOnly Property DeviceEvent As DeviceEvents
  112.            <DebuggerStepThrough>
  113.            Get
  114.                Return Me.deviceEventsB
  115.            End Get
  116.        End Property
  117.        ''' ----------------------------------------------------------------------------------------------------
  118.        ''' <summary>
  119.        ''' ( Backing field )
  120.        ''' The device event that occurred.
  121.        ''' </summary>
  122.        ''' ----------------------------------------------------------------------------------------------------
  123.        Private ReadOnly deviceEventsB As DeviceEvents
  124.  
  125.        ''' ----------------------------------------------------------------------------------------------------
  126.        ''' <summary>
  127.        ''' Gets the drive info.
  128.        ''' </summary>
  129.        ''' ----------------------------------------------------------------------------------------------------
  130.        ''' <value>
  131.        ''' The drive info.
  132.        ''' </value>
  133.        ''' ----------------------------------------------------------------------------------------------------
  134.        Public ReadOnly Property DriveInfo As DriveInfo
  135.            <DebuggerStepThrough>
  136.            Get
  137.                Return Me.driveInfoB
  138.            End Get
  139.        End Property
  140.        ''' ----------------------------------------------------------------------------------------------------
  141.        ''' <summary>
  142.        ''' ( Backing field )
  143.        ''' The drive info.
  144.        ''' </summary>
  145.        ''' ----------------------------------------------------------------------------------------------------
  146.        Private ReadOnly driveInfoB As DriveInfo
  147.  
  148. #End Region
  149.  
  150. #Region " Constructors "
  151.  
  152.        ''' ----------------------------------------------------------------------------------------------------
  153.        ''' <summary>
  154.        ''' Prevents a default instance of the <see cref="DriveStatusChangedEventArgs"/> class from being created.
  155.        ''' </summary>
  156.        ''' ----------------------------------------------------------------------------------------------------
  157.        <DebuggerNonUserCode>
  158.        Private Sub New()
  159.        End Sub
  160.  
  161.        ''' ----------------------------------------------------------------------------------------------------
  162.        ''' <summary>
  163.        ''' Initializes a new instance of the <see cref="DriveStatusChangedEventArgs"/> class.
  164.        ''' </summary>
  165.        ''' ----------------------------------------------------------------------------------------------------
  166.        ''' <param name="driveInfo">
  167.        ''' The drive info.
  168.        ''' </param>
  169.        ''' ----------------------------------------------------------------------------------------------------
  170.        <DebuggerStepThrough>
  171.        Public Sub New(ByVal deviceEvent As DeviceEvents, ByVal driveInfo As DriveInfo)
  172.  
  173.            Me.deviceEventsB = deviceEvent
  174.            Me.driveInfoB = driveInfo
  175.  
  176.        End Sub
  177.  
  178. #End Region
  179.  
  180.    End Class
  181.  
  182. #End Region
  183.  
  184. #End Region
  185.  
  186. #Region " Event Invocators "
  187.  
  188.    ''' ----------------------------------------------------------------------------------------------------
  189.    ''' <summary>
  190.    ''' Raises <see cref="DriveStatusChanged"/> event.
  191.    ''' </summary>
  192.    ''' ----------------------------------------------------------------------------------------------------
  193.    ''' <param name="e">
  194.    ''' The <see cref="DriveStatusChangedEventArgs"/> instance containing the event data.
  195.    ''' </param>
  196.    ''' ----------------------------------------------------------------------------------------------------
  197.    <DebuggerStepThrough>
  198.    Protected Overridable Sub OnDriveStatusChanged(ByVal e As DriveStatusChangedEventArgs)
  199.  
  200.        RaiseEvent DriveStatusChanged(Me, e)
  201.  
  202.    End Sub
  203.  
  204. #End Region
  205.  
  206. #Region " Enumerations "
  207.  
  208.    ''' ----------------------------------------------------------------------------------------------------
  209.    ''' <summary>
  210.    ''' Specifies a change to the hardware configuration of a device.
  211.    ''' </summary>
  212.    ''' ----------------------------------------------------------------------------------------------------
  213.    ''' <remarks>
  214.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx"/>
  215.    ''' <para></para>
  216.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx"/>
  217.    ''' </remarks>
  218.    ''' ----------------------------------------------------------------------------------------------------
  219.    Public Enum DeviceEvents As Integer
  220.  
  221.        ' *****************************************************************************
  222.        '                            WARNING!, NEED TO KNOW...
  223.        '
  224.        '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS PROJECT
  225.        ' *****************************************************************************
  226.  
  227.        ''' <summary>
  228.        ''' The current configuration has changed, due to a dock or undock.
  229.        ''' </summary>
  230.        Change = &H219
  231.  
  232.        ''' <summary>
  233.        ''' A device or piece of media has been inserted and becomes available.
  234.        ''' </summary>
  235.        Arrival = &H8000
  236.  
  237.        ''' <summary>
  238.        ''' Request permission to remove a device or piece of media.
  239.        ''' <para></para>
  240.        ''' This message is the last chance for applications and drivers to prepare for this removal.
  241.        ''' However, any application can deny this request and cancel the operation.
  242.        ''' </summary>
  243.        QueryRemove = &H8001
  244.  
  245.        ''' <summary>
  246.        ''' A request to remove a device or piece of media has been canceled.
  247.        ''' </summary>
  248.        QueryRemoveFailed = &H8002
  249.  
  250.        ''' <summary>
  251.        ''' A device or piece of media is being removed and is no longer available for use.
  252.        ''' </summary>
  253.        RemovePending = &H8003
  254.  
  255.        ''' <summary>
  256.        ''' A device or piece of media has been removed.
  257.        ''' </summary>
  258.        RemoveComplete = &H8004
  259.  
  260.    End Enum
  261.  
  262.    ''' ----------------------------------------------------------------------------------------------------
  263.    ''' <summary>
  264.    ''' Specifies a computer device type.
  265.    ''' </summary>
  266.    ''' ----------------------------------------------------------------------------------------------------
  267.    ''' <remarks>
  268.    ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363246%28v=vs.85%29.aspx"/>
  269.    ''' </remarks>
  270.    ''' ----------------------------------------------------------------------------------------------------
  271.    Private Enum DeviceType As Integer
  272.  
  273.        ' *****************************************************************************
  274.        '                            WARNING!, NEED TO KNOW...
  275.        '
  276.        '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS PROJECT
  277.        ' *****************************************************************************
  278.  
  279.        ''' <summary>
  280.        ''' Logical volume.
  281.        ''' </summary>
  282.        Logical = &H2
  283.  
  284.    End Enum
  285.  
  286. #End Region
  287.  
  288. #Region " Types "
  289.  
  290.    ''' ----------------------------------------------------------------------------------------------------
  291.    ''' <summary>
  292.    ''' Contains information about a logical volume.
  293.    ''' </summary>
  294.    ''' ----------------------------------------------------------------------------------------------------
  295.    ''' <remarks>
  296.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx"/>
  297.    ''' </remarks>
  298.    ''' ----------------------------------------------------------------------------------------------------
  299.    <DebuggerStepThrough>
  300.    <StructLayout(LayoutKind.Sequential)>
  301.    Private Structure DevBroadcastVolume
  302.  
  303.        ''' ----------------------------------------------------------------------------------------------------
  304.        ''' <summary>
  305.        ''' The size of this structure, in bytes.
  306.        ''' </summary>
  307.        ''' ----------------------------------------------------------------------------------------------------
  308.        Public Size As UInteger
  309.  
  310.        ''' ----------------------------------------------------------------------------------------------------
  311.        ''' <summary>
  312.        ''' Set to DBT_DEVTYP_VOLUME (2).
  313.        ''' </summary>
  314.        ''' ----------------------------------------------------------------------------------------------------
  315.        Public Type As UInteger
  316.  
  317.        ''' ----------------------------------------------------------------------------------------------------
  318.        ''' <summary>
  319.        ''' Reserved parameter; do not use this.
  320.        ''' </summary>
  321.        ''' ----------------------------------------------------------------------------------------------------
  322.        Public Reserved As UInteger
  323.  
  324.        ''' ----------------------------------------------------------------------------------------------------
  325.        ''' <summary>
  326.        ''' The logical unit mask identifying one or more logical units.
  327.        ''' Each bit in the mask corresponds to one logical drive.
  328.        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
  329.        ''' </summary>
  330.        ''' ----------------------------------------------------------------------------------------------------
  331.        Public Mask As UInteger
  332.  
  333.        ''' ----------------------------------------------------------------------------------------------------
  334.        ''' <summary>
  335.        ''' This parameter can be one of the following values:
  336.        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
  337.        ''' '0x0002': Indicated logical volume is a network volume.
  338.        ''' </summary>
  339.        ''' ----------------------------------------------------------------------------------------------------
  340.        Public Flags As UShort
  341.  
  342.    End Structure
  343.  
  344. #End Region
  345.  
  346. #Region " Constructor "
  347.  
  348.    ''' ----------------------------------------------------------------------------------------------------
  349.    ''' <summary>
  350.    ''' Initializes a new instance of <see cref="DriveWatcher"/> class.
  351.    ''' </summary>
  352.    ''' ----------------------------------------------------------------------------------------------------
  353.    <DebuggerStepThrough>
  354.    Public Sub New()
  355.  
  356.        Me.events = New EventHandlerList
  357.  
  358.    End Sub
  359.  
  360. #End Region
  361.  
  362. #Region " Public Methods "
  363.  
  364.    ''' ----------------------------------------------------------------------------------------------------
  365.    ''' <summary>
  366.    ''' Starts monitoring.
  367.    ''' </summary>
  368.    ''' ----------------------------------------------------------------------------------------------------
  369.    ''' <exception cref="Exception">
  370.    ''' Monitor is already running.
  371.    ''' </exception>
  372.    ''' ----------------------------------------------------------------------------------------------------
  373.    <DebuggerStepThrough>
  374.    Public Overridable Sub Start()
  375.  
  376.        If (Me.Handle = IntPtr.Zero) Then
  377.            MyBase.CreateHandle(New CreateParams)
  378.            Me.isRunningB = True
  379.  
  380.        Else
  381.            Throw New Exception(message:="Monitor is already running.")
  382.  
  383.        End If
  384.  
  385.    End Sub
  386.  
  387.    ''' ----------------------------------------------------------------------------------------------------
  388.    ''' <summary>
  389.    ''' Stops monitoring.
  390.    ''' </summary>
  391.    ''' ----------------------------------------------------------------------------------------------------
  392.    ''' <exception cref="Exception">
  393.    ''' Monitor is already stopped.
  394.    ''' </exception>
  395.    ''' ----------------------------------------------------------------------------------------------------
  396.    <DebuggerStepThrough>
  397.    Public Overridable Sub [Stop]()
  398.  
  399.        If (Me.Handle <> IntPtr.Zero) Then
  400.            MyBase.DestroyHandle()
  401.            Me.isRunningB = False
  402.  
  403.        Else
  404.            Throw New Exception(message:="Monitor is already stopped.")
  405.  
  406.        End If
  407.  
  408.    End Sub
  409.  
  410. #End Region
  411.  
  412. #Region " Private Methods "
  413.  
  414.    ''' ----------------------------------------------------------------------------------------------------
  415.    ''' <summary>
  416.    ''' Gets the drive letter stored in a <see cref="DevBroadcastVolume"/> structure.
  417.    ''' </summary>
  418.    ''' ----------------------------------------------------------------------------------------------------
  419.    ''' <param name="Device">
  420.    ''' The <see cref="DevBroadcastVolume"/> structure containing the device mask.
  421.    ''' </param>
  422.    ''' ----------------------------------------------------------------------------------------------------
  423.    ''' <returns>
  424.    ''' The drive letter.
  425.    ''' </returns>
  426.    ''' ----------------------------------------------------------------------------------------------------
  427.    <DebuggerStepThrough>
  428.    Private Function GetDriveLetter(ByVal device As DevBroadcastVolume) As Char
  429.  
  430.        Dim driveLetters As Char() = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray
  431.  
  432.        Dim deviceID As New BitArray(BitConverter.GetBytes(device.Mask))
  433.  
  434.        For i As Integer = 0 To deviceID.Length
  435.  
  436.            If deviceID(i) Then
  437.                Return driveLetters(i)
  438.            End If
  439.  
  440.        Next i
  441.  
  442.        Return Nothing
  443.  
  444.    End Function
  445.  
  446. #End Region
  447.  
  448. #Region " Window Procedure (WndProc) "
  449.  
  450.    ''' ----------------------------------------------------------------------------------------------------
  451.    ''' <summary>
  452.    ''' Invokes the default window procedure associated with this window to process messages for this Window.
  453.    ''' </summary>
  454.    ''' ----------------------------------------------------------------------------------------------------
  455.    ''' <param name="m">
  456.    ''' A <see cref="T:System.Windows.Forms.Message"/> that is associated with the current Windows message.
  457.    ''' </param>
  458.    ''' ----------------------------------------------------------------------------------------------------
  459.    <DebuggerStepThrough>
  460.    Protected Overrides Sub WndProc(ByRef m As Message)
  461.  
  462.        Select Case m.Msg
  463.  
  464.            Case DeviceEvents.Change ' The hardware has changed.
  465.  
  466.                If (m.LParam = IntPtr.Zero) Then
  467.                    Exit Select
  468.                End If
  469.  
  470.                ' If it's an storage device then...
  471.                If Marshal.ReadInt32(m.LParam, 4) = DeviceType.Logical Then
  472.  
  473.                    ' Transform the LParam pointer into the data structure.
  474.                    Dim currentWDrive As DevBroadcastVolume =
  475.                        DirectCast(Marshal.PtrToStructure(m.LParam, GetType(DevBroadcastVolume)), DevBroadcastVolume)
  476.  
  477.                    Dim driveLetter As Char = Me.GetDriveLetter(currentWDrive)
  478.                    Dim deviceEvent As DeviceEvents = DirectCast(m.WParam.ToInt32, DeviceEvents)
  479.                    Dim driveInfo As New DriveInfo(driveLetter)
  480.  
  481.                    Me.OnDriveStatusChanged(New DriveStatusChangedEventArgs(deviceEvent, driveInfo))
  482.  
  483.                End If
  484.  
  485.        End Select
  486.  
  487.        ' Return Message to base message handler.
  488.        MyBase.WndProc(m)
  489.  
  490.    End Sub
  491.  
  492. #End Region
  493.  
  494. #Region " Hidden methods "
  495.  
  496.    ''' ----------------------------------------------------------------------------------------------------
  497.    ''' <summary>
  498.    ''' Serves as a hash function for a particular type.
  499.    ''' </summary>
  500.    ''' ----------------------------------------------------------------------------------------------------
  501.    <EditorBrowsable(EditorBrowsableState.Never)>
  502.    <DebuggerNonUserCode>
  503.    Public Shadows Function GetHashCode() As Integer
  504.        Return MyBase.GetHashCode
  505.    End Function
  506.  
  507.    ''' ----------------------------------------------------------------------------------------------------
  508.    ''' <summary>
  509.    ''' Gets the <see cref="System.Type"/> of the current instance.
  510.    ''' </summary>
  511.    ''' ----------------------------------------------------------------------------------------------------
  512.    ''' <returns>
  513.    ''' The exact runtime type of the current instance.
  514.    ''' </returns>
  515.    ''' ----------------------------------------------------------------------------------------------------
  516.    <EditorBrowsable(EditorBrowsableState.Never)>
  517.    <DebuggerNonUserCode>
  518.    Public Shadows Function [GetType]() As Type
  519.        Return MyBase.GetType
  520.    End Function
  521.  
  522.    ''' ----------------------------------------------------------------------------------------------------
  523.    ''' <summary>
  524.    ''' Determines whether the specified <see cref="System.Object"/> instances are considered equal.
  525.    ''' </summary>
  526.    ''' ----------------------------------------------------------------------------------------------------
  527.    <EditorBrowsable(EditorBrowsableState.Never)>
  528.    <DebuggerNonUserCode>
  529.    Public Shadows Function Equals(ByVal obj As Object) As Boolean
  530.        Return MyBase.Equals(obj)
  531.    End Function
  532.  
  533.    ''' ----------------------------------------------------------------------------------------------------
  534.    ''' <summary>
  535.    ''' Returns a String that represents the current object.
  536.    ''' </summary>
  537.    ''' ----------------------------------------------------------------------------------------------------
  538.    <EditorBrowsable(EditorBrowsableState.Never)>
  539.    <DebuggerNonUserCode>
  540.    Public Shadows Function ToString() As String
  541.        Return MyBase.ToString
  542.    End Function
  543.  
  544.    ''' ----------------------------------------------------------------------------------------------------
  545.    ''' <summary>
  546.    ''' Assigns a handle to this window.
  547.    ''' </summary>
  548.    ''' ----------------------------------------------------------------------------------------------------
  549.    <EditorBrowsable(EditorBrowsableState.Never)>
  550.    <DebuggerNonUserCode>
  551.    Public Shadows Sub AssignHandle(ByVal handle As IntPtr)
  552.        MyBase.AssignHandle(handle)
  553.    End Sub
  554.  
  555.    ''' ----------------------------------------------------------------------------------------------------
  556.    ''' <summary>
  557.    ''' Creates a window and its handle with the specified creation parameters.
  558.    ''' </summary>
  559.    ''' ----------------------------------------------------------------------------------------------------
  560.    <EditorBrowsable(EditorBrowsableState.Never)>
  561.    <DebuggerNonUserCode>
  562.    Public Shadows Sub CreateHandle(ByVal cp As CreateParams)
  563.        MyBase.CreateHandle(cp)
  564.    End Sub
  565.  
  566.    ''' ----------------------------------------------------------------------------------------------------
  567.    ''' <summary>
  568.    ''' Destroys the window and its handle.
  569.    ''' </summary>
  570.    ''' ----------------------------------------------------------------------------------------------------
  571.    <EditorBrowsable(EditorBrowsableState.Never)>
  572.    <DebuggerNonUserCode>
  573.    Public Shadows Sub DestroyHandle()
  574.        MyBase.DestroyHandle()
  575.    End Sub
  576.  
  577.    ''' ----------------------------------------------------------------------------------------------------
  578.    ''' <summary>
  579.    ''' Releases the handle associated with this window.
  580.    ''' </summary>
  581.    ''' ----------------------------------------------------------------------------------------------------
  582.    <EditorBrowsable(EditorBrowsableState.Never)>
  583.    <DebuggerNonUserCode>
  584.    Public Shadows Sub ReleaseHandle()
  585.        MyBase.ReleaseHandle()
  586.    End Sub
  587.  
  588.    ''' ----------------------------------------------------------------------------------------------------
  589.    ''' <summary>
  590.    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
  591.    ''' </summary>
  592.    ''' ----------------------------------------------------------------------------------------------------
  593.    <EditorBrowsable(EditorBrowsableState.Never)>
  594.    <DebuggerNonUserCode>
  595.    Public Shadows Function GetLifeTimeService() As Object
  596.        Return MyBase.GetLifetimeService
  597.    End Function
  598.  
  599.    ''' ----------------------------------------------------------------------------------------------------
  600.    ''' <summary>
  601.    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
  602.    ''' </summary>
  603.    ''' ----------------------------------------------------------------------------------------------------
  604.    <EditorBrowsable(EditorBrowsableState.Never)>
  605.    <DebuggerNonUserCode>
  606.    Public Shadows Function InitializeLifeTimeService() As Object
  607.        Return MyBase.InitializeLifetimeService
  608.    End Function
  609.  
  610.    ''' ----------------------------------------------------------------------------------------------------
  611.    ''' <summary>
  612.    ''' Creates an object that contains all the relevant information to generate a proxy used to communicate with a remote object.
  613.    ''' </summary>
  614.    ''' ----------------------------------------------------------------------------------------------------
  615.    <EditorBrowsable(EditorBrowsableState.Never)>
  616.    <DebuggerNonUserCode>
  617.    Public Shadows Function CreateObjRef(ByVal requestedType As Type) As System.Runtime.Remoting.ObjRef
  618.        Return MyBase.CreateObjRef(requestedType)
  619.    End Function
  620.  
  621.    ''' ----------------------------------------------------------------------------------------------------
  622.    ''' <summary>
  623.    ''' Invokes the default window procedure associated with this window.
  624.    ''' </summary>
  625.    ''' ----------------------------------------------------------------------------------------------------
  626.    <EditorBrowsable(EditorBrowsableState.Never)>
  627.    <DebuggerNonUserCode>
  628.    Public Shadows Sub DefWndProc(ByRef m As Message)
  629.        MyBase.DefWndProc(m)
  630.    End Sub
  631.  
  632. #End Region
  633.  
  634. #Region " IDisposable Implementation "
  635.  
  636.    ''' ----------------------------------------------------------------------------------------------------
  637.    ''' <summary>
  638.    ''' To detect redundant calls when disposing.
  639.    ''' </summary>
  640.    ''' ----------------------------------------------------------------------------------------------------
  641.    Private isDisposed As Boolean
  642.  
  643.    ''' ----------------------------------------------------------------------------------------------------
  644.    ''' <summary>
  645.    ''' Releases all the resources used by this instance.
  646.    ''' </summary>
  647.    ''' ----------------------------------------------------------------------------------------------------
  648.    <DebuggerStepThrough>
  649.    Public Sub Dispose() Implements IDisposable.Dispose
  650.  
  651.        Me.Dispose(isDisposing:=True)
  652.        GC.SuppressFinalize(obj:=Me)
  653.  
  654.    End Sub
  655.  
  656.    ''' ----------------------------------------------------------------------------------------------------
  657.    ''' <summary>
  658.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  659.    ''' Releases unmanaged and - optionally - managed resources.
  660.    ''' </summary>
  661.    ''' ----------------------------------------------------------------------------------------------------
  662.    ''' <param name="isDisposing">
  663.    ''' <see langword="True"/>  to release both managed and unmanaged resources;
  664.    ''' <see langword="False"/> to release only unmanaged resources.
  665.    ''' </param>
  666.    ''' ----------------------------------------------------------------------------------------------------
  667.    <DebuggerStepThrough>
  668.    Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)
  669.  
  670.        If (Not Me.isDisposed) AndAlso (isDisposing) Then
  671.  
  672.            Me.events.Dispose()
  673.            Me.Stop()
  674.  
  675.        End If
  676.  
  677.        Me.isDisposed = True
  678.  
  679.    End Sub
  680.  
  681. #End Region
  682.  
  683. End Class
En línea

Borito30


Desconectado Desconectado

Mensajes: 481


Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #498 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 línea

Estoy en contra del foro libre y la Sección de juegos y consolas (distraen al personal)
z3nth10n


Desconectado Desconectado

Mensajes: 1.583


"Jack of all trades, master of none." - Zenthion


Ver Perfil WWW
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #499 en: 3 Marzo 2017, 23:43 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.
En línea


Interesados hablad por Discord.
Páginas: 1 ... 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 [50] 51 52 53 54 55 56 57 58 59 Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines