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

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


  Mostrar Mensajes
Páginas: 1 ... 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 [692] 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 ... 1236
6911  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 17:55 pm
Ya van 30 páginas xD

Pues vamos a por las 300 :)

(triplicando mis espectativas xD)

Saludos!
6912  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 17:23 pm
Ejemplos de uso de la librería dnlib (de4dot): https://github.com/0xd4d/dnlib

Aunque de momento es una Class muy básica, pues dnlib es muy extenso pero con documentación muy escasa.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-03-2014
  4. ' ***********************************************************************
  5. ' <copyright file="dnlibHelper.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Private Sub Test() Handles MyBase.Shown
  13. '
  14. '    Dim Assembly As ModuleDefMD =
  15. '        dnlibHelper.LoadAssembly("C:\Application.exe")
  16. '
  17. '    Dim FrameworkVersion As String =
  18. '        dnlibHelper.GetRuntimeVersion(Assembly)
  19. '
  20. '    Dim IsNativeCoded As Boolean =
  21. '        dnlibHelper.AssemblyHasNativeCode(Assembly)
  22. '
  23. '    Dim Methods As List(Of MethodDef) =
  24. '        dnlibHelper.GetMethods(Assembly, "Main") ' Searchs a Class named "Main"
  25. '
  26. '    For Each Method As MethodDef In Methods
  27. '
  28. '        ' If method contains instructions then...
  29. '        If Method.HasBody Then
  30. '
  31. '            Dim sb As New System.Text.StringBuilder
  32. '            With sb
  33. '                .AppendLine(String.Format("Method Name: {0}", Method.Name))
  34. '                .AppendLine()
  35. '                .AppendLine(String.Format("Method Signature: {0}", Method.Signature.ToString))
  36. '                .AppendLine()
  37. '                .AppendLine(String.Format("Method Instructions: {0}", Environment.NewLine &
  38. '                                          String.Join(Environment.NewLine, Method.Body.Instructions)))
  39. '            End With
  40. '
  41. '            MessageBox.Show(sb.ToString)
  42. '
  43. '        End If ' method.HasBody
  44. '
  45. '    Next Method
  46. '
  47. 'End Sub
  48.  
  49. #End Region
  50.  
  51. #Region " Imports "
  52.  
  53. Imports dnlib.DotNet
  54. Imports dnlib.DotNet.Emit
  55.  
  56. #End Region
  57.  
  58. ''' <summary>
  59. ''' Class dnlibHelper. This class cannot be inherited.
  60. ''' </summary>
  61. Public NotInheritable Class dnlibHelper
  62.  
  63.    ''' <summary>
  64.    ''' Loads an Assembly into a ModuleDefMD instance.
  65.    ''' </summary>
  66.    ''' <param name="Assembly">The assembly filepath.</param>
  67.    ''' <returns>ModuleDefMD.</returns>
  68.    Public Shared Function LoadAssembly(ByVal Assembly As String) As ModuleDefMD
  69.  
  70.        Return ModuleDefMD.Load(Assembly)
  71.  
  72.    End Function
  73.  
  74.    ''' <summary>
  75.    ''' Determines whether a .Net Assembly has native code (C++/CLI).
  76.    ''' </summary>
  77.    ''' <param name="Assembly">The Assembly.</param>
  78.    ''' <returns><c>true</c> if Assembly contains native code; otherwise, <c>false</c>.</returns>
  79.    Public Shared Function AssemblyHasNativeCode(ByVal Assembly As ModuleDef) As Boolean
  80.  
  81.        If Assembly.IsILOnly Then
  82.            ' This assembly has only IL code, and no native code (for example it's a C# or VB.NET assembly)
  83.            Return True
  84.  
  85.        Else
  86.            ' This assembly has native code (for example it's C++/CLI)
  87.            Return False
  88.  
  89.        End If
  90.  
  91.    End Function
  92.  
  93.    ''' <summary>
  94.    ''' Determines whether a .Net Assembly has native code (C++/CLI).
  95.    ''' </summary>
  96.    ''' <param name="Assembly">The Assembly filepath.</param>
  97.    ''' <returns><c>true</c> if Assembly contains native code; otherwise, <c>false</c>.</returns>
  98.    Public Shared Function AssemblyHasNativeCode(ByVal Assembly As String) As Boolean
  99.  
  100.        Using ass As ModuleDefMD = ModuleDefMD.Load(Assembly)
  101.  
  102.            Return AssemblyHasNativeCode(ass)
  103.  
  104.        End Using
  105.  
  106.    End Function
  107.  
  108.    ''' <summary>
  109.    ''' Gets the .Net Framework runtime version of a .Net assembly.
  110.    ''' </summary>
  111.    ''' <param name="Assembly">The assembly.</param>
  112.    ''' <returns>System.String.</returns>
  113.    Public Shared Function GetRuntimeVersion(ByVal Assembly As ModuleDefMD) As String
  114.  
  115.        Return Assembly.RuntimeVersion
  116.  
  117.    End Function
  118.  
  119.    ''' <summary>
  120.    ''' Gets the .Net Framework runtime version of a .Net assembly.
  121.    ''' </summary>
  122.    ''' <param name="Assembly">The assembly filepath.</param>
  123.    ''' <returns>System.String.</returns>
  124.    Public Shared Function GetRuntimeVersion(ByVal Assembly As String) As String
  125.  
  126.        Using ass As ModuleDefMD = ModuleDefMD.Load(Assembly)
  127.            Return GetRuntimeVersion(ass)
  128.        End Using
  129.  
  130.    End Function
  131.  
  132.    ''' <summary>
  133.    ''' Gets all the Types defined (including nested Types) inside a .Net assembly.
  134.    ''' </summary>
  135.    ''' <param name="Assembly">The assembly.</param>
  136.    ''' <returns>TypeDef().</returns>
  137.    Public Shared Function GetTypes(ByVal Assembly As ModuleDefMD) As List(Of TypeDef)
  138.  
  139.        Return Assembly.GetTypes.ToList
  140.  
  141.    End Function
  142.  
  143.    ''' <summary>
  144.    ''' Gets all the Methods defined in a existing Type inside a .Net assembly.
  145.    ''' </summary>
  146.    ''' <param name="Assembly">The assembly.</param>
  147.    ''' <param name="TypeName">Name of the type to find.</param>
  148.    ''' <returns>MethodDef().</returns>
  149.    Public Shared Function GetMethods(ByVal Assembly As ModuleDefMD,
  150.                                      ByVal TypeName As String) As List(Of MethodDef)
  151.  
  152.        Dim methods As List(Of MethodDef) = Nothing
  153.  
  154.        For Each t As TypeDef In Assembly.GetTypes
  155.  
  156.            If t.HasMethods AndAlso t.Name.String.Equals(TypeName, StringComparison.OrdinalIgnoreCase) Then
  157.                methods = t.Methods.ToList
  158.                Exit For
  159.            End If
  160.  
  161.        Next t
  162.  
  163.        Return methods
  164.  
  165.    End Function
  166.  
  167. End Class
6913  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 10:40 am
Ejemplo de como usar un Proxy:

Código
  1.        Dim Request As Net.HttpWebRequest = Net.HttpWebRequest.Create("http://whatismyipaddress.com/")
  2.  
  3.        With Request
  4.            .Proxy = New Net.WebProxy(Host:="93.115.8.229", Port:=7808)
  5.        End With
  6.  
  7.        Using StrReader As New IO.StreamReader(Request.GetResponse().GetResponseStream)
  8.  
  9.            Dim IPRegEx As New System.Text.RegularExpressions.Regex("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
  10.            Dim IPValue As String = IPRegEx.Match(StrReader.ReadToEnd).Value
  11.  
  12.            MessageBox.Show(String.Format("Your IP Adress is: {0}", IPValue))
  13.  
  14.        End Using



Hace parpadear la ventana o el botón de la barra de tareas de un proceso

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-03-2014
  4. ' ***********************************************************************
  5. ' <copyright file="WindowFlasher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ''Flash the Button TaskBar until the window becomes active.
  13. 'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.TaskBar Or WindowFlasher.FlashFlags.Until_Foreground)
  14.  
  15. ''Flash the Caption and the Button TaskBar until the "Stop" flag is set.
  16. 'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.All Or WindowFlasher.FlashFlags.Until_Stop)
  17.  
  18. ''Set the "Stop" flag, to stop flashing.
  19. 'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.Stop)
  20.  
  21. #End Region
  22.  
  23. #Region " Imports "
  24.  
  25. Imports System.ComponentModel
  26. Imports System.Runtime.InteropServices
  27.  
  28. #End Region
  29.  
  30. ''' <summary>
  31. ''' Flashes a Window and/or it's button in the TaskBar.
  32. ''' </summary>
  33. Public Class WindowFlasher
  34.  
  35. #Region " P/Invoke "
  36.  
  37.    ''' <summary>
  38.    ''' Contains Native Windows API Methods.
  39.    ''' </summary>
  40.    Friend Class NativeMethods
  41.  
  42. #Region " Methods "
  43.  
  44.        ''' <summary>
  45.        ''' Flashes the specified window.
  46.        ''' It does not change the active state of the window.
  47.        ''' For more info see here:
  48.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms679347%28v=vs.85%29.aspx
  49.        ''' </summary>
  50.        ''' <param name="pwfi">A pointer to a FLASHWINFO structure.</param>
  51.        ''' <returns>
  52.        ''' The return value specifies the window's state before the call to the FlashWindowEx function.
  53.        ''' If the window caption was drawn as active before the call, the return value is nonzero.
  54.        ''' Otherwise, the return value is zero.
  55.        ''' </returns>
  56.        <DllImport("user32.dll")>
  57.        Friend Shared Function FlashWindowEx(
  58.               ByRef pwfi As FLASHWINFO
  59.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  60.        End Function
  61.  
  62. #End Region
  63.  
  64. #Region " Structures "
  65.  
  66.        ''' <summary>
  67.        ''' Contains the flash status for a window and the number of times the system should flash the window.
  68.        ''' For more info see here:
  69.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms679348%28v=vs.85%29.aspx
  70.        ''' </summary>
  71.        <StructLayout(LayoutKind.Sequential)>
  72.        Friend Structure FLASHWINFO
  73.  
  74.            ''' <summary>
  75.            ''' The size of the structure, in bytes.
  76.            ''' </summary>
  77.            Friend cbSize As UInteger
  78.  
  79.            ''' <summary>
  80.            ''' A handle to the window to be flashed.
  81.            ''' The window can be either opened or minimized.
  82.            ''' </summary>
  83.            Friend hwnd As IntPtr
  84.  
  85.            ''' <summary>
  86.            ''' The flash status.
  87.            ''' </summary>
  88.            Friend dwFlags As FlashFlags
  89.  
  90.            ''' <summary>
  91.            ''' The number of times to flash the window.
  92.            ''' </summary>
  93.            Friend uCount As UInteger
  94.  
  95.            ''' <summary>
  96.            ''' The rate at which the window is to be flashed, in milliseconds.
  97.            ''' If dwTimeout is zero, the function uses the default cursor blink rate.
  98.            ''' </summary>
  99.            Friend dwTimeout As UInteger
  100.  
  101.        End Structure
  102.  
  103. #End Region
  104.  
  105.    End Class
  106.  
  107. #End Region
  108.  
  109. #Region " Enumerations "
  110.  
  111.    ''' <summary>
  112.    ''' Contains the flash status for a window.
  113.    ''' </summary>
  114.    <Description("Enum used as 'FlashFlags' parameter in 'FlashWindow' function.")>
  115.    <Flags>
  116.    Public Enum FlashFlags As Integer
  117.  
  118.        ''' <summary>
  119.        ''' Stop flashing.
  120.        ''' The system restores the window to its original state.
  121.        ''' </summary>    
  122.        [Stop] = 0I
  123.  
  124.        ''' <summary>
  125.        ''' Flash the window caption.
  126.        ''' </summary>
  127.        Caption = 1I
  128.  
  129.        ''' <summary>
  130.        ''' Flash the taskbar button.
  131.        ''' </summary>
  132.        TaskBar = 2I
  133.  
  134.        ''' <summary>
  135.        ''' Flash both the window caption and taskbar button.
  136.        ''' This is equivalent to setting the 'Caption Or TaskBar' flags.
  137.        ''' </summary>
  138.        All = 3I
  139.  
  140.        ''' <summary>
  141.        ''' Flash continuously, until the 'Stop' flag is set.
  142.        ''' </summary>
  143.        Until_Stop = 4I
  144.  
  145.        ''' <summary>
  146.        ''' Flash continuously until the window comes to the foreground.
  147.        ''' </summary>
  148.        Until_Foreground = 12I
  149.  
  150.    End Enum
  151.  
  152. #End Region
  153.  
  154. #Region " Public Methods "
  155.  
  156.    ''' <summary>
  157.    ''' Flashes the specified window.
  158.    ''' It does not change the active state of the window.
  159.    ''' </summary>
  160.    ''' <param name="Handle">
  161.    ''' Indicates the handle to the window to flash.
  162.    ''' </param>
  163.    ''' <param name="FlashFlags">
  164.    ''' Indicates the flash flags.
  165.    ''' </param>
  166.    ''' <param name="FlashCount">
  167.    ''' Indicates the number of times to flash the window.
  168.    ''' </param>
  169.    ''' <param name="FlashDelay">
  170.    ''' Indicates the rate at which the window is to be flashed, in milliseconds.
  171.    ''' If dwTimeout is zero, the function uses the default cursor blink rate.
  172.    ''' </param>
  173.    ''' <returns>
  174.    ''' The return value specifies the window's state before the call to the FlashWindowEx function.
  175.    ''' If the window caption was drawn as active before the call, the return value is nonzero.
  176.    ''' Otherwise, the return value is zero.
  177.    ''' </returns>
  178.    Public Shared Function Flash(ByVal [Handle] As IntPtr,
  179.                                 ByVal FlashFlags As FlashFlags,
  180.                                 Optional ByVal FlashCount As UInteger = UInteger.MaxValue,
  181.                                 Optional ByVal FlashDelay As UInteger = 0UI) As Boolean
  182.  
  183.        Dim fInfo As New NativeMethods.FLASHWINFO()
  184.  
  185.        With fInfo
  186.  
  187.            .cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo))
  188.            .hwnd = [Handle]
  189.            .dwFlags = FlashFlags
  190.            .uCount = FlashCount
  191.            .dwTimeout = FlashDelay
  192.  
  193.        End With
  194.  
  195.        Return NativeMethods.FlashWindowEx(fInfo)
  196.  
  197.    End Function
  198.  
  199. #End Region
  200.  
  201. End Class
  202.  
6914  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 09:05 am
Como convertir una expresión de un valor Hexadecimal al tipo de expresión que se usa en VB.NET:

Nota: Esta es una forma más eficiente que la que posteé hace mucho tiempo.

Código
  1.   ' Hex To VBHex
  2.    ' By Elektro
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    ' MsgBox(HexToVBHex("FF4"))                        ' Result: &HFF4
  7.    ' MsgBox(HexToVBHex("0xFF4"))                      ' Result: &HFF4
  8.    ' Dim Value As Integer = CInt(HexToVBHex("0xFF4")) ' Result: 4084
  9.    '
  10.    ''' <summary>
  11.    ''' Converts an Hexadecimal value to VisualBasic Hexadecimal syntax.
  12.    ''' </summary>
  13.    ''' <param name="Value">The Hexadecimal value as String.</param>
  14.    ''' <returns>System.String.</returns>
  15.    Public Function HexToVBHex(ByVal Value As String) As String
  16.  
  17.        If (String.IsNullOrEmpty(Value) Or String.IsNullOrWhiteSpace(Value)) Then
  18.            Throw New ArgumentNullException(Value)
  19.        End If
  20.  
  21.        Return String.Format("&H{0}", Value.
  22.                                      TrimStart({"0"c, "x"c, "X"c, " "c, ControlChars.NullChar}).
  23.                                      TrimEnd({" "c, ControlChars.NullChar}))
  24.  
  25.    End Function



Como obtener una cadena de texto aleatoria ...dado un set de caracteres, con la posibilidad de randomizar también el String-Case (upper-case/lower-case) de cada letra.

Código
  1.    Dim Randomizer As New Random
  2.  
  3.    ' Get Random String
  4.    ' // By Elektro
  5.    '
  6.    ' Usage Examples :
  7.    ' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 10))
  8.    ' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyz", 10, RandomizeCase:=True))
  9.    '
  10.    ''' <summary>
  11.    ''' Gets a random string.
  12.    ''' </summary>
  13.    ''' <param name="CharacterSet">Indicates the characters to randomize.</param>
  14.    ''' <param name="StringLength">Indicates the resulting string length.</param>
  15.    ''' <param name="RandomizeCase">If set to <c>true</c>, lower-case and upper-case are randomized.</param>
  16.    ''' <returns>System.String.</returns>
  17.    ''' <exception cref="System.Exception">
  18.    ''' CharacterSet is empty.
  19.    ''' or
  20.    ''' String-Length must be greater than 0.
  21.    ''' </exception>
  22.    Private Function GetRandomString(ByVal CharacterSet As Char(),
  23.                                     ByVal StringLength As Integer,
  24.                                     Optional ByVal RandomizeCase As Boolean = False) As String
  25.  
  26.        Select Case CharacterSet.Count
  27.  
  28.            Case Is = 0
  29.                Throw New Exception("CharacterSet is empty.")
  30.  
  31.            Case Is = 1
  32.                Return New String(CharacterSet.First, Math.Abs(StringLength))
  33.  
  34.            Case Else
  35.  
  36.                Select Case StringLength
  37.  
  38.                    Case Is < 1
  39.                        Throw New Exception("String-Length must be greater than 0.")
  40.  
  41.                    Case Else
  42.  
  43.                        Dim CharSetLength As Integer = CharacterSet.Length
  44.                        Dim CharSB As New System.Text.StringBuilder
  45.  
  46.                        Do Until CharSB.Length = StringLength
  47.  
  48.                            If Not RandomizeCase Then
  49.                                CharSB.Append(CharacterSet(Randomizer.Next(0, CharSetLength)))
  50.  
  51.                            Else
  52.  
  53.                                Select Case Randomizer.Next(0, 2)
  54.  
  55.                                    Case 0 ' Lower-Case
  56.                                        CharSB.Append(Char.ToLower(CharacterSet(Randomizer.Next(0, CharSetLength))))
  57.  
  58.                                    Case 1 ' Upper-Case
  59.                                        CharSB.Append(Char.ToUpper(CharacterSet(Randomizer.Next(0, CharSetLength))))
  60.  
  61.                                End Select
  62.  
  63.                            End If '/ Not RandomizeCase
  64.  
  65.                        Loop '/ CharSB.Length = StringLength
  66.  
  67.                        Return CharSB.ToString
  68.  
  69.                End Select '/ StringLength
  70.  
  71.        End Select '/  CharacterSet.Count
  72.  
  73.    End Function




Una expresión regular para obtener las Ipv4 de un String:

Código
  1.    ' RegEx-Match IPv4
  2.    ' By Elektro
  3.    '
  4.    ' expression taken from: http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  5.    '
  6.    ' Usage Examples :
  7.    ' Dim Addresses As String = "127.0.0.1 | 192.17.200.13 | 255.255.255.255 | 999.999.999.999"
  8.    ' Dim Matches As System.Text.RegularExpressions.MatchCollection = RegExMatch_IPv4(Addresses)
  9.    ' For Each m As System.Text.RegularExpressions.Match In Matches
  10.    '     MessageBox.Show(m.Value)
  11.    ' Next
  12.    '
  13.    ''' <summary>
  14.    ''' Matches the IPv4 addresses contained in a String, using Regular Expressions.
  15.    ''' </summary>
  16.    ''' <param name="str">The string.</param>
  17.    ''' <param name="options">The RegEx options.</param>
  18.    ''' <returns>System.Text.RegularExpressions.MatchCollection.</returns>
  19.    Private Function RegExMatch_IPv4(ByVal str As String,
  20.                                     Optional ByVal options As System.Text.RegularExpressions.RegexOptions =
  21.                                                               System.Text.RegularExpressions.RegexOptions.None
  22.                                                               ) As System.Text.RegularExpressions.MatchCollection
  23.  
  24.        ' Match criteria:
  25.        '
  26.        ' ([0-255].[0-255].[0-255].[0-255])
  27.  
  28.        Dim Pattern As String =
  29.            <a><![CDATA[((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])]]></a>.Value
  30.  
  31.        Return New System.Text.RegularExpressions.Regex(Pattern).Matches(str)
  32.  
  33.    End Function



Una expresión regular para obtener las Ipv6 de un String:

Nota: La expresión da fallos con ip's comprimidas como por ejemplo esta:
Código:
fec0:fff::1
por lo demás todo bien.

Código
  1.    ' RegEx-Match IPv6
  2.    ' By Elektro
  3.    '
  4.    ' expression taken from: http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  5.    '
  6.    ' Usage Examples :
  7.    ' Dim Addresses As String = "FE80:0000:0000:0000:0202:B3FF:FE1E:8329 | FEC0:FFFF:0000:0000:0000:0000:0000:1"
  8.    ' Dim Matches As System.Text.RegularExpressions.MatchCollection = RegExMatch_IPv6(Addresses)
  9.    ' For Each m As System.Text.RegularExpressions.Match In Matches
  10.    '     MessageBox.Show(m.Value)
  11.    ' Next
  12.    '
  13.    ''' <summary>
  14.    ''' Matches the IPv6 addresses (full or compressed) contained in a String, using Regular Expressions.
  15.    ''' </summary>
  16.    ''' <param name="str">The string.</param>
  17.    ''' <param name="options">The RegEx options.</param>
  18.    ''' <returns>System.Text.RegularExpressions.MatchCollection.</returns>
  19.    Private Function RegExMatch_IPv6(ByVal str As String,
  20.                                     Optional ByVal options As System.Text.RegularExpressions.RegexOptions =
  21.                                                               System.Text.RegularExpressions.RegexOptions.None
  22.                                                               ) As System.Text.RegularExpressions.MatchCollection
  23.  
  24.        Dim Pattern As String =
  25.            <a><![CDATA[(([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]))]]></a>.Value
  26.  
  27.        Return New System.Text.RegularExpressions.Regex(Pattern).Matches(str)
  28.  
  29.    End Function
6915  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 09:02 am
Contiene métodos para enumerar los símbolos de una librería externa, como por ejemplo las funciones publicas, algo parecido a lo que hace la aplicación 'DLL Export Viewer': http://www.nirsoft.net/utils/dll_export_viewer.html

Nota: Como dato de interés, algo que yo también me pregunté en su momento:
         No existe ingeniería inversa posible para obtener las firmas de los métodos, los datatypes de los parámetros.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 05-03-2014
  4. ' ***********************************************************************
  5. ' <copyright file="Symbols.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Private Sub Test() Handles MyBase.Load
  13.  
  14. '    Dim dll As String = "C:\C++ lib x64.dll"
  15. '    Dim initialized As Boolean = False
  16. '    Dim hProcess As IntPtr = Nothing
  17.  
  18. '    Try
  19. '        hProcess = Process.GetCurrentProcess().Handle
  20.  
  21. '        If (Symbols.SymInitialize(hProcess, Nothing, True)) Then
  22. '            initialized = True
  23. '        Else
  24. '            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
  25. '        End If
  26.  
  27. '        Dim baseOfDll As IntPtr = Symbols.SymLoadModuleEx(hProcess, IntPtr.Zero, dll,
  28. '                                                          Nothing, 0, 0, IntPtr.Zero,
  29. '                                                          Symbols.SymLoadModuleFlags.Module_And_Symbols)
  30.  
  31. '        If (baseOfDll = IntPtr.Zero) Then
  32. '            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
  33. '        End If
  34.  
  35. '        If Not Symbols.SymEnumSymbols(
  36. '            hProcess,
  37. '            baseOfDll,
  38. '            "*",
  39. '            AddressOf EnumSymProc, IntPtr.Zero
  40. '        ) Then
  41. '            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
  42. '        End If
  43.  
  44. '    Catch ex As Exception
  45. '        Debug.WriteLine(ex.Message)
  46. '    Finally
  47. '        If (initialized) Then
  48. '            Symbols.SymCleanup(hProcess)
  49. '        End If
  50. '    End Try
  51.  
  52. 'End Sub
  53.  
  54. 'Friend Shared Function EnumSymProc(ByVal pSymInfo As IntPtr,
  55. '                                   ByVal SymbolSize As UInteger,
  56. '                                   ByVal UserContext As IntPtr) As Boolean
  57.  
  58. '    Dim Symbol As New Symbols.SYMBOL_INFO With
  59. '        {
  60. '            .SizeOfStruct = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Symbols.SYMBOL_INFO))
  61. '        }
  62.  
  63. '    System.Runtime.InteropServices.Marshal.PtrToStructure(pSymInfo, Symbol)
  64.  
  65. '    Dim sb As New System.Text.StringBuilder
  66.  
  67. '    With sb
  68.  
  69. '        .AppendLine(String.Format("Address: {0}", CStr(Symbol.Address)))
  70. '        .AppendLine(String.Format("Flags: {0}", Symbol.Flags.ToString))
  71. '        .AppendLine(String.Format("Index: {0}", CStr(Symbol.Index)))
  72. '        .AppendLine(String.Format("Module Base Address: {0}", CStr(Symbol.ModBase)))
  73. '        .AppendLine(String.Format("Name: {0}", Symbol.Name))
  74. '        .AppendLine(String.Format("Size: {0}", CStr(Symbol.Size)))
  75. '        .AppendLine(String.Format("Tag: {0}", Symbol.Tag.ToString))
  76.  
  77. '    End With
  78.  
  79. '    Debug.WriteLine(sb.ToString)
  80.  
  81. '    Return True
  82.  
  83. 'End Function
  84.  
  85. #End Region
  86.  
  87. #Region " Imports "
  88.  
  89. Imports System.ComponentModel
  90. Imports System.Runtime.InteropServices
  91.  
  92. #End Region
  93.  
  94. Public Class Symbols
  95.  
  96. #Region " P/Invoke "
  97.  
  98. #Region " Methods "
  99.  
  100.    ''' <summary>
  101.    ''' Initializes the symbol handler for a process.
  102.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681351%28v=vs.85%29.aspx
  103.    ''' </summary>
  104.    ''' <param name="hProcess">
  105.    ''' A handle that identifies the caller.
  106.    ''' This value should be unique and nonzero, but need not be a process handle.
  107.    ''' However, if you do use a process handle, be sure to use the correct handle.
  108.    ''' If the application is a debugger, use the process handle for the process being debugged.
  109.    ''' Do not use the handle returned by 'GetCurrentProcess' when debugging another process,
  110.    ''' because calling functions like 'SymLoadModuleEx' can have unexpected results.
  111.    ''' </param>
  112.    ''' <param name="UserSearchPath">
  113.    ''' The path, or series of paths separated by a semicolon (;), that is used to search for symbol files.
  114.    ''' If this parameter is NULL, the library attempts to form a symbol path from the following sources:
  115.    ''' The current working directory of the application.
  116.    ''' The _NT_SYMBOL_PATH environment variable.
  117.    ''' The _NT_ALTERNATE_SYMBOL_PATH environment variable.
  118.    ''' </param>
  119.    ''' <param name="fInvadeProcess">
  120.    ''' If this value is TRUE, enumerates the loaded modules for the process
  121.    ''' and effectively calls the 'SymLoadModule64' function for each module.</param>
  122.    ''' <returns>
  123.    ''' If the function succeeds, the return value is <c>true</c>.
  124.    ''' If the function fails, the return value is <c>false</c>.
  125.    ''' </returns>
  126.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  127.    Friend Shared Function SymInitialize(
  128.               ByVal hProcess As IntPtr,
  129.               ByVal UserSearchPath As String,
  130.               <MarshalAs(UnmanagedType.Bool)>
  131.               ByVal fInvadeProcess As Boolean
  132.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  133.    End Function
  134.  
  135.    ''' <summary>
  136.    ''' Deallocates all resources associated with the process handle.
  137.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680696%28v=vs.85%29.aspx
  138.    ''' </summary>
  139.    ''' <param name="hProcess">A handle to the process that was originally passed to the 'SymInitialize' function.</param>
  140.    ''' <returns>
  141.    ''' If the function succeeds, the return value is <c>true</c>.
  142.    ''' If the function fails, the return value is <c>false</c>.
  143.    ''' </returns>
  144.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  145.    Friend Shared Function SymCleanup(
  146.               ByVal hProcess As IntPtr
  147.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  148.    End Function
  149.  
  150.    ''' <summary>
  151.    ''' Sets the options mask.
  152.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681366%28v=vs.85%29.aspx
  153.    ''' </summary>
  154.    ''' <param name="SymOptions"></param>
  155.    ''' <returns>The function returns the current options mask.</returns>
  156.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  157.    Friend Shared Function SymSetOptions(
  158.               ByVal SymOptions As SymOptionFlags
  159.        ) As Integer
  160.    End Function
  161.  
  162.    ''' <summary>
  163.    ''' Loads the symbol table for the specified module.
  164.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681353%28v=vs.85%29.aspx
  165.    ''' </summary>
  166.    ''' <param name="hProcess">
  167.    ''' A handle to the process that was originally passed to the 'SymInitialize' function.
  168.    ''' </param>
  169.    ''' <param name="hFile">
  170.    ''' The 'h fileA' handle to the file for the executable image.
  171.    ''' This argument is used mostly by debuggers, where the debugger passes the file handle obtained from a debugging event.
  172.    ''' A value of NULL indicates that 'hFile' is not used.
  173.    ''' </param>
  174.    ''' <param name="ImageName">
  175.    ''' The name of the executable image.
  176.    ''' This name can contain a partial path, a full path, or no path at all.
  177.    ''' If the file cannot be located by the name provided, the symbol search path is used.
  178.    ''' </param>
  179.    ''' <param name="ModuleName">
  180.    ''' A shortcut name for the module.
  181.    ''' If the pointer value is NULL, the library creates a name using the base name of the symbol file.
  182.    ''' </param>
  183.    ''' <param name="BaseOfDll">
  184.    ''' The load address of the module.
  185.    ''' If the value is zero, the library obtains the load address from the symbol file.
  186.    ''' The load address contained in the symbol file is not necessarily the actual load address.
  187.    ''' Debuggers and other applications having an actual load address should use the real load address when calling this function.
  188.    ''' If the image is a '.pdb' file, this parameter cannot be zero.
  189.    ''' </param>
  190.    ''' <param name="DllSize">
  191.    ''' The size of the module, in bytes.
  192.    ''' If the value is zero, the library obtains the size from the symbol file.
  193.    ''' The size contained in the symbol file is not necessarily the actual size.
  194.    ''' Debuggers and other applications having an actual size should use the real size when calling this function.
  195.    ''' If the image is a '.pdb' file, this parameter cannot be zero.
  196.    ''' </param>
  197.    ''' <param name="Data">
  198.    ''' A pointer to a 'MODLOAD_DATA' structure that represents headers other than the standard PE header.
  199.    ''' This parameter is optional and can be NULL.
  200.    ''' </param>
  201.    ''' <param name="Flags">
  202.    ''' This parameter can be one or more of the 'SymLoadModuleFlags' Enum values.
  203.    ''' If this parameter is zero, the function loads the modules and the symbols for the module.
  204.    ''' </param>
  205.    ''' <returns>
  206.    ''' If the function succeeds, the return value is the base address of the loaded module.
  207.    ''' If the function fails, the return value is zero. To retrieve extended error information, call 'GetLastError'.
  208.    ''' If the module is already loaded, the return value is zero and 'GetLastError' returns 'ERROR_SUCCESS'.
  209.    ''' </returns>
  210.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  211.    Friend Shared Function SymLoadModuleEx(
  212.               ByVal hProcess As IntPtr,
  213.               ByVal hFile As IntPtr,
  214.               ByVal ImageName As String,
  215.               ByVal ModuleName As String,
  216.               ByVal BaseOfDll As Long,
  217.               ByVal DllSize As Integer,
  218.               ByVal Data As IntPtr,
  219.               ByVal Flags As SymLoadModuleFlags
  220.        ) As ULong
  221.    End Function
  222.  
  223.    ''' <summary>
  224.    ''' Enumerates all symbols in a process.
  225.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680718%28v=vs.85%29.aspx
  226.    ''' </summary>
  227.    ''' <param name="hProcess">
  228.    ''' A handle to a process.
  229.    ''' This handle must have been previously passed to the 'SymInitialize' function.
  230.    ''' </param>
  231.    ''' <param name="BaseOfDll">
  232.    ''' The base address of the module.
  233.    ''' If this value is zero and 'Mask' contains an exclamation point (!),
  234.    ''' the function looks across modules.
  235.    ''' If this value is zero and 'Mask' does not contain an exclamation point,
  236.    ''' the function uses the scope established by the 'SymSetContext' function.
  237.    ''' </param>
  238.    ''' <param name="Mask">
  239.    ''' A wildcard string that indicates the names of the symbols to be enumerated.
  240.    ''' The text can optionally contain the wildcards, "*" and "?".
  241.    ''' </param>
  242.    ''' <param name="EnumSymbolsCallback">
  243.    ''' A 'SymEnumSymbolsProc' callback function that receives the symbol information.
  244.    ''' </param>
  245.    ''' <param name="UserContext">
  246.    ''' A user-defined value that is passed to the callback function, or NULL.
  247.    ''' This parameter is typically used by an application to pass a pointer to a data structure
  248.    ''' that provides context for the callback function.
  249.    ''' </param>
  250.    ''' <returns>
  251.    ''' If the function succeeds, the return value is <c>true</c>.
  252.    ''' If the function fails, the return value is <c>false</c>.
  253.    ''' </returns>
  254.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  255.    Friend Shared Function SymEnumSymbols(
  256.               ByVal hProcess As IntPtr,
  257.               ByVal BaseOfDll As ULong,
  258.               <MarshalAs(UnmanagedType.LPWStr)>
  259.               ByVal Mask As String,
  260.               ByVal EnumSymbolsCallback As SymEnumSymbolsProc,
  261.               ByVal UserContext As IntPtr
  262.        ) As Boolean
  263.    End Function
  264.  
  265. #End Region
  266.  
  267. #End Region
  268.  
  269. #Region " Types "
  270.  
  271.    ''' <summary>
  272.    ''' Contains symbol information.
  273.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680686%28v=vs.85%29.aspx
  274.    ''' </summary>
  275.    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
  276.    Public Class SYMBOL_INFO
  277.  
  278.        ''' <summary>
  279.        ''' The size of the structure, in bytes.
  280.        ''' This member must be set to sizeof(SYMBOL_INFO).
  281.        ''' Note that the total size of the data is the SizeOfStruct + (MaxNameLen - 1) * sizeof(TCHAR).
  282.        ''' The reason to subtract one is that the first character in the name is accounted for in the size of the structure.
  283.        ''' </summary>
  284.        Public SizeOfStruct As UInteger
  285.  
  286.        ''' <summary>
  287.        ''' A unique value that identifies the type data that describes the symbol.
  288.        ''' This value does not persist between sessions.
  289.        ''' </summary>
  290.        Public TypeIndex As UInteger
  291.  
  292.        ''' <summary>
  293.        ''' This member is reserved for system use.
  294.        ''' </summary>
  295.        Public Reserved1 As ULong
  296.  
  297.        ''' <summary>
  298.        ''' This member is reserved for system use.
  299.        ''' </summary>
  300.        Public Reserved2 As ULong
  301.  
  302.        ''' <summary>
  303.        ''' The unique value for the symbol.
  304.        ''' The value associated with a symbol is not guaranteed to be the same each time you run the process.
  305.        ''' For PDB symbols, the index value for a symbol is not generated until
  306.        ''' the symbol is enumerated or retrieved through a search by name or address.
  307.        ''' The index values for all CodeView and COFF symbols are generated when the symbols are loaded.
  308.        ''' </summary>
  309.        Public Index As UInteger
  310.  
  311.        ''' <summary>
  312.        ''' The symbol size, in bytes.
  313.        ''' This value is meaningful only if the module symbols are from a pdb file;
  314.        ''' otherwise, this value is typically zero and should be ignored.
  315.        ''' </summary>
  316.        Public Size As UInteger
  317.  
  318.        ''' <summary>
  319.        ''' The base address of the module that contains the symbol.
  320.        ''' </summary>
  321.        Public ModBase As ULong
  322.  
  323.        ''' <summary>
  324.        ''' The symbol information.
  325.        ''' This member can be one or more of the 'SymFlag' values.
  326.        ''' </summary>
  327.        Public Flags As SymFlag
  328.  
  329.        ''' <summary>
  330.        ''' The value of a constant.
  331.        ''' </summary>
  332.        Public Value As ULong
  333.  
  334.        ''' <summary>
  335.        ''' The virtual address of the start of the symbol.
  336.        ''' </summary>
  337.        Public Address As ULong
  338.  
  339.        ''' <summary>
  340.        ''' The register.
  341.        ''' </summary>
  342.        Public Register As UInteger
  343.  
  344.        ''' <summary>
  345.        ''' The DIA scope.
  346.        ''' For more information, see the Debug Interface Access SDK in the Visual Studio documentation.
  347.        ''' (This resource may not be available in some languages and countries.)
  348.        ''' </summary>
  349.        Public Scope As UInteger
  350.  
  351.        ''' <summary>
  352.        ''' The PDB classification.
  353.        ''' These values are defined in 'Dbghelp.h' in the 'SymTagEnum' enumeration type.
  354.        ''' </summary>
  355.        Public Tag As SymTagEnum
  356.  
  357.        ''' <summary>
  358.        ''' The length of the name, in characters, not including the null-terminating character.
  359.        ''' </summary>
  360.        Public NameLen As UInteger
  361.  
  362.        ''' <summary>
  363.        ''' The size of the Name buffer, in characters.
  364.        ''' If this member is 0, the Name member is not used.
  365.        ''' </summary>
  366.        Public MaxNameLen As UInteger
  367.  
  368.        ''' <summary>
  369.        ''' The name of the symbol.
  370.        ''' The name can be undecorated if the 'SYMOPT_UNDNAME' option is used with the 'SymSetOptions' function.
  371.        ''' </summary>
  372.        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1024I)>
  373.        Public Name As String
  374.  
  375.    End Class
  376.  
  377. #End Region
  378.  
  379. #Region " Enumerations "
  380.  
  381.    ''' <summary>
  382.    ''' Flags for 'SymLoadModuleEx' function.
  383.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681353%28v=vs.85%29.aspx
  384.    ''' </summary>
  385.    <Description("Enum used as 'Flags' parameter of 'SymLoadModuleEx' function")>
  386.    <FlagsAttribute()>
  387.    Public Enum SymLoadModuleFlags As Integer
  388.  
  389.        ''' <summary>
  390.        ''' Loads the module and the symbols for the module.
  391.        ''' </summary>
  392.        Module_And_Symbols = &H0UI
  393.  
  394.        ''' <summary>
  395.        ''' Loads the module but not the symbols for the module.
  396.        ''' </summary>
  397.        Only_Module = &H4UI
  398.  
  399.        ''' <summary>
  400.        ''' Creates a virtual module named 'ModuleName' at the address specified in 'BaseOfDll'.
  401.        ''' To add symbols to this module, call the 'SymAddSymbol' function.
  402.        ''' </summary>
  403.        Virtual = &H1UI
  404.  
  405.    End Enum
  406.  
  407.    ''' <summary>
  408.    ''' Contains symbol information.
  409.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680686%28v=vs.85%29.aspx
  410.    ''' </summary>
  411.    <Description("Enum used as 'Flags' property of 'SYMBOL_INFO' Class")>
  412.    <FlagsAttribute>
  413.    Public Enum SymFlag As UInteger
  414.  
  415.        ''' <summary>
  416.        ''' The Value member is used.
  417.        ''' </summary>
  418.        VALUEPRESENT = &H1UI
  419.  
  420.        ''' <summary>
  421.        ''' The symbol is a register.
  422.        ''' The Register member is used.
  423.        ''' </summary>
  424.        REGISTER = &H8UI
  425.  
  426.        ''' <summary>
  427.        ''' Offsets are register relative.
  428.        ''' </summary>
  429.        REGREL = &H10UI
  430.  
  431.        ''' <summary>
  432.        ''' Offsets are frame relative.
  433.        ''' </summary>
  434.        FRAMEREL = &H20UI
  435.  
  436.        ''' <summary>
  437.        ''' The symbol is a parameter.
  438.        ''' </summary>
  439.        PARAMETER = &H40UI
  440.  
  441.        ''' <summary>
  442.        ''' The symbol is a local variable.
  443.        ''' </summary>
  444.        LOCAL = &H80UI
  445.  
  446.        ''' <summary>
  447.        ''' The symbol is a constant.
  448.        ''' </summary>
  449.        CONSTANT = &H100UI
  450.  
  451.        ''' <summary>
  452.        ''' The symbol is from the export table.
  453.        ''' </summary>
  454.        EXPORT = &H200UI
  455.  
  456.        ''' <summary>
  457.        ''' The symbol is a forwarder.
  458.        ''' </summary>
  459.        FORWARDER = &H400UI
  460.  
  461.        ''' <summary>
  462.        ''' The symbol is a known function.
  463.        ''' </summary>
  464.        [FUNCTION] = &H800UI
  465.  
  466.        ''' <summary>
  467.        ''' The symbol is a virtual symbol created by the 'SymAddSymbol' function.
  468.        ''' </summary>
  469.        VIRTUAL = &H1000UI
  470.  
  471.        ''' <summary>
  472.        ''' The symbol is a thunk.
  473.        ''' </summary>
  474.        THUNK = &H2000UI
  475.  
  476.        ''' <summary>
  477.        ''' The symbol is an offset into the TLS data area.
  478.        ''' </summary>
  479.        TLSREL = &H4000UI
  480.  
  481.        ''' <summary>
  482.        ''' The symbol is a managed code slot.
  483.        ''' </summary>
  484.        SLOT = &H8000UI
  485.  
  486.        ''' <summary>
  487.        ''' The symbol address is an offset relative to the beginning of the intermediate language block.
  488.        ''' This applies to managed code only.
  489.        ''' </summary>
  490.        ILREL = &H10000UI
  491.  
  492.        ''' <summary>
  493.        ''' The symbol is managed metadata.
  494.        ''' </summary>
  495.        METADATA = &H20000UI
  496.  
  497.        ''' <summary>
  498.        ''' The symbol is a CLR token.
  499.        ''' </summary>
  500.        CLR_TOKEN = &H40000UI
  501.  
  502.    End Enum
  503.  
  504.    ''' <summary>
  505.    ''' Specifies the type of symbol.
  506.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/bkedss5f.aspx
  507.    ''' </summary>
  508.    <Description("Enum used as 'Tag' property of 'SYMBOL_INFO' Class")>
  509.    <Flags>
  510.    Public Enum SymTagEnum As UInteger
  511.  
  512.        ''' <summary>
  513.        ''' Indicates that the symbol has no type.
  514.        ''' </summary>
  515.        Null
  516.  
  517.        ''' <summary>
  518.        ''' Indicates that the symbol is an .exe file.
  519.        ''' There is only one SymTagExe symbol per symbol store.
  520.        ''' It serves as the global scope and does not have a lexical parent.
  521.        ''' </summary>
  522.        Exe
  523.  
  524.        ''' <summary>
  525.        ''' Indicates the compiland symbol for each compiland component of the symbol store.
  526.        ''' For native applications, SymTagCompiland symbols correspond to the object files linked into the image.
  527.        ''' For some kinds of Microsoft Intermediate Language (MSIL) images, there is one compiland per class.
  528.        ''' </summary>
  529.        Compiland
  530.  
  531.        ''' <summary>
  532.        ''' Indicates that the symbol contains extended attributes of the compiland.
  533.        ''' Retrieving these properties may require loading compiland symbols.
  534.        ''' </summary>
  535.        CompilandDetails
  536.  
  537.        ''' <summary>
  538.        ''' Indicates that the symbol is an environment string defined for the compiland.
  539.        ''' </summary>
  540.        CompilandEnv
  541.  
  542.        ''' <summary>
  543.        ''' Indicates that the symbol is a function.
  544.        ''' </summary>
  545.        [Function]
  546.  
  547.        ''' <summary>
  548.        ''' Indicates that the symbol is a nested block.
  549.        ''' </summary>
  550.        Block
  551.  
  552.        ''' <summary>
  553.        ''' Indicates that the symbol is data.
  554.        ''' </summary>
  555.        Data
  556.  
  557.        ''' <summary>
  558.        ''' Indicates that the symbol is for a code annotation.
  559.        ''' Children of this symbol are constant data strings (SymTagData, LocIsConstant, DataIsConstant).
  560.        ''' Most clients ignore this symbol.
  561.        ''' </summary>
  562.        Annotation
  563.  
  564.        ''' <summary>
  565.        ''' Indicates that the symbol is a label.
  566.        ''' </summary>
  567.        Label
  568.  
  569.        ''' <summary>
  570.        ''' Indicates that the symbol is a public symbol. For native applications,
  571.        ''' this symbol is the COFF external symbol encountered while linking the image.
  572.        ''' </summary>
  573.        PublicSymbol
  574.  
  575.        ''' <summary>
  576.        ''' Indicates that the symbol is a user-defined type (structure, class, or union).
  577.        ''' </summary>
  578.        UDT
  579.  
  580.        ''' <summary>
  581.        ''' Indicates that the symbol is an enumeration.
  582.        ''' </summary>
  583.        [Enum]
  584.  
  585.        ''' <summary>
  586.        ''' Indicates that the symbol is a function signature type.
  587.        ''' </summary>
  588.        FunctionType
  589.  
  590.        ''' <summary>
  591.        ''' Indicates that the symbol is a pointer type.
  592.        ''' </summary>
  593.        PointerType
  594.  
  595.        ''' <summary>
  596.        ''' Indicates that the symbol is an array type.
  597.        ''' </summary>
  598.        ArrayType
  599.  
  600.        ''' <summary>
  601.        ''' Indicates that the symbol is a base type.
  602.        ''' </summary>
  603.        BaseType
  604.  
  605.        ''' <summary>
  606.        ''' Indicates that the symbol is a typedef, that is, an alias for another type.
  607.        ''' </summary>
  608.        Typedef
  609.  
  610.        ''' <summary>
  611.        ''' Indicates that the symbol is a base class of a user-defined type.
  612.        ''' </summary>
  613.        BaseClass
  614.  
  615.        ''' <summary>
  616.        ''' Indicates that the symbol is a friend of a user-defined type.
  617.        ''' </summary>
  618.        [Friend]
  619.  
  620.        ''' <summary>
  621.        ''' Indicates that the symbol is a function argument.
  622.        ''' </summary>
  623.        FunctionArgType
  624.  
  625.        ''' <summary>
  626.        ''' Indicates that the symbol is the end location of the function's prologue code.
  627.        ''' </summary>
  628.        FuncDebugStart
  629.  
  630.        ''' <summary>
  631.        ''' Indicates that the symbol is the beginning location of the function's epilogue code.
  632.        ''' </summary>
  633.        FuncDebugEnd
  634.  
  635.        ''' <summary>
  636.        ''' Indicates that the symbol is a namespace name, active in the current scope.
  637.        ''' </summary>
  638.        UsingNamespace
  639.  
  640.        ''' <summary>
  641.        ''' Indicates that the symbol is a virtual table description.
  642.        ''' </summary>
  643.        VTableShape
  644.  
  645.        ''' <summary>
  646.        ''' Indicates that the symbol is a virtual table pointer.
  647.        ''' </summary>
  648.        VTable
  649.  
  650.        ''' <summary>
  651.        ''' Indicates that the symbol is a custom symbol and is not interpreted by DIA.
  652.        ''' </summary>
  653.        Custom
  654.  
  655.        ''' <summary>
  656.        ''' Indicates that the symbol is a thunk used for sharing data between 16 and 32 bit code.
  657.        ''' </summary>
  658.        Thunk
  659.  
  660.        ''' <summary>
  661.        ''' Indicates that the symbol is a custom compiler symbol.
  662.        ''' </summary>
  663.        CustomType
  664.  
  665.        ''' <summary>
  666.        ''' Indicates that the symbol is in metadata.
  667.        ''' </summary>
  668.        ManagedType
  669.  
  670.        ''' <summary>
  671.        ''' Indicates that the symbol is a FORTRAN multi-dimensional array.
  672.        ''' </summary>
  673.        Dimension
  674.  
  675.        ''' <summary>
  676.        ''' Indicates that the symbol represents the call site.
  677.        ''' </summary>
  678.        CallSite
  679.  
  680.        ''' <summary>
  681.        ''' Indicates that the symbol represents the inline site.
  682.        ''' </summary>
  683.        InlineSite
  684.  
  685.        ''' <summary>
  686.        ''' Indicates that the symbol is a base interface.
  687.        ''' </summary>
  688.        BaseInterface
  689.  
  690.        ''' <summary>
  691.        ''' Indicates that the symbol is a vector type.
  692.        ''' </summary>
  693.        VectorType
  694.  
  695.        ''' <summary>
  696.        ''' Indicates that the symbol is a matrix type.
  697.        ''' </summary>
  698.        MatrixType
  699.  
  700.        ''' <summary>
  701.        ''' Indicates that the symbol is a High Level Shader Language type.
  702.        ''' </summary>
  703.        HLSLType
  704.  
  705.    End Enum
  706.  
  707.    ''' <summary>
  708.    ''' Sets the options mask.
  709.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681366%28v=vs.85%29.aspx
  710.    ''' </summary>
  711.    <Description("Enum used as 'SymOptions' parameter of 'SymSetOptions' function")>
  712.    <Flags>
  713.    Public Enum SymOptionFlags As Integer
  714.  
  715.        ''' <summary>
  716.        ''' Enables the use of symbols that do not have an address.
  717.        ''' By default, DbgHelp filters out symbols that do not have an address.
  718.        ''' </summary>
  719.        ALLOW_ZERO_ADDRESS = &H1000000
  720.  
  721.        ''' <summary>
  722.        ''' All symbol searches are insensitive to case.
  723.        ''' </summary>
  724.        CASE_INSENSITIVE = &H1
  725.  
  726.        ''' <summary>
  727.        ''' Pass debug output through OutputDebugString or the SymRegisterCallbackProc64 callback function.
  728.        ''' </summary>
  729.        DEBUG = &H80000000
  730.  
  731.        ''' <summary>
  732.        ''' Symbols are not loaded until a reference is made requiring the symbols be loaded.
  733.        ''' This is the fastest, most efficient way to use the symbol handler.
  734.        ''' </summary>
  735.        DEFERRED_LOADS = &H4
  736.  
  737.        ''' <summary>
  738.        ''' Do not load an unmatched .pdb file.
  739.        ''' Do not load export symbols if all else fails.
  740.        ''' </summary>
  741.        EXACT_SYMBOLS = &H400
  742.  
  743.        ''' <summary>
  744.        ''' Do not display system dialog boxes when there is a media failure such as no media in a drive.
  745.        ''' Instead, the failure happens silently.
  746.        ''' </summary>
  747.        FAIL_CRITICAL_ERRORS = &H200
  748.  
  749.        ''' <summary>
  750.        ''' If there is both an uncompressed and a compressed file available, favor the compressed file.
  751.        ''' This option is good for slow connections.
  752.        ''' </summary>
  753.        FAVOR_COMPRESSED = &H800000
  754.  
  755.        ''' <summary>
  756.        ''' Ignore path information in the CodeView record of the image header when loading a .pdb file.
  757.        ''' </summary>
  758.        IGNORE_CVREC = &H80
  759.  
  760.        ''' <summary>
  761.        ''' When debugging on 64-bit Windows, include any 32-bit modules.
  762.        ''' </summary>
  763.        INCLUDE_32BIT_MODULES = &H2000
  764.  
  765.        ''' <summary>
  766.        ''' Disable checks to ensure a file (.exe, .dbg., or .pdb) is the correct file.
  767.        ''' Instead, load the first file located.
  768.        ''' </summary>
  769.        LOAD_ANYTHING = &H40
  770.  
  771.        ''' <summary>
  772.        ''' Loads line number information.
  773.        ''' </summary>
  774.        LOAD_LINES = &H10
  775.  
  776.        ''' <summary>
  777.        ''' All C++ decorated symbols containing the symbol separator "::" are replaced by "__".
  778.        ''' This option exists for debuggers that cannot handle parsing real C++ symbol names.
  779.        ''' </summary>
  780.        NO_CPP = &H8
  781.  
  782.        ''' <summary>
  783.        ''' Prevents prompting for validation from the symbol server.
  784.        ''' </summary>
  785.        NO_PROMPTS = &H80000
  786.  
  787.        ''' <summary>
  788.        ''' Prevents symbols from being loaded when the caller examines symbols across multiple modules.
  789.        ''' Examine only the module whose symbols have already been loaded.
  790.        ''' </summary>
  791.        NO_UNQUALIFIED_LOADS = &H100
  792.  
  793.        ''' <summary>
  794.        ''' DbgHelp will not load any symbol server other than SymSrv. SymSrv will not use the downstream store specified in _NT_SYMBOL_PATH. After this flag has been set, it cannot be cleared.
  795.        ''' DbgHelp 6.0 and 6.1:  This flag can be cleared.
  796.        ''' DbgHelp 5.1:  This value is not supported.
  797.        ''' </summary>
  798.        SECURE = &H40000
  799.  
  800.        ''' <summary>
  801.        ''' All symbols are presented in undecorated form.
  802.        ''' This option has no effect on global or local symbols because they are stored undecorated.
  803.        ''' This option applies only to public symbols.
  804.        ''' </summary>
  805.        UNDNAME = &H2
  806.  
  807.    End Enum
  808.  
  809. #End Region
  810.  
  811. #Region " Delegates "
  812.  
  813.    ''' <summary>
  814.    ''' An application-defined callback function used with the 'SymEnumSymbols', 'SymEnumTypes', and 'SymEnumTypesByName' functions.
  815.    ''' </summary>
  816.    ''' <param name="pSymInfo">
  817.    ''' A pointer to a 'SYMBOL_INFO' structure that provides information about the symbol.
  818.    ''' </param>
  819.    ''' <param name="SymbolSize">
  820.    ''' The size of the symbol, in bytes.
  821.    ''' The size is calculated and is actually a guess.
  822.    ''' In some cases, this value can be zero.
  823.    ''' </param>
  824.    ''' <param name="UserContext">
  825.    ''' The user-defined value passed from the 'SymEnumSymbols' or 'SymEnumTypes' function, or NULL.
  826.    ''' This parameter is typically used by an application to pass a pointer to a data structure
  827.    ''' that provides context information for the callback function.</param>
  828.    ''' <returns>
  829.    ''' If the function returns <c>true</c>, the enumeration will continue.
  830.    ''' If the function returns <c>false</c>, the enumeration will stop.
  831.    ''' </returns>
  832.    Friend Delegate Function SymEnumSymbolsProc(
  833.           ByVal pSymInfo As IntPtr,
  834.           ByVal SymbolSize As UInteger,
  835.           ByVal UserContext As IntPtr
  836.    ) As Boolean
  837.  
  838. #End Region
  839.  
  840. End Class
6916  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 08:51 am
Como crear un archivo dummy (vacío) de cualquier tamaño:

Código
  1.    ' Create Dummy File
  2.    ' By Elektro
  3.    '
  4.    ' Usage Examples:
  5.    ' CreateDummyFile("C:\DummyFile.tmp", 1024L ^ 3L) ' File with 1 GB size.
  6.    '
  7.    ''' <summary>
  8.    ''' Creates a dummy zero-filled file.
  9.    ''' </summary>
  10.    ''' <param name="Filepath">Indicates the filepath.</param>
  11.    ''' <param name="Length">Indicates the size, in Bytes.</param>
  12.    Public Sub CreateDummyFile(ByVal Filepath As String,
  13.                               Optional ByVal Length As Long = 0)
  14.  
  15.        Using fs As New IO.FileStream(Filepath, IO.FileMode.CreateNew)
  16.            fs.SetLength(Length)
  17.        End Using
  18.  
  19.    End Sub



Preserva, Restaura, o Establece las fechas de un archivo.

Nota: Esta versión tiene ciertas mejoras a la versión que publiqué en el foro, la mejora en concreto es la de poder restaurar las fechas si un archivo ha cambiado de ubicación o de nombre.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 07-22-2014
  4. ' ***********************************************************************
  5. ' <copyright file="FileDater.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. #Region " Example 1 "
  13.  
  14. '' Instance a test FileInfo using an unique temp file.
  15. 'Using fd As New FileDater(File:=New IO.FileInfo(IO.Path.GetTempFileName))
  16. '
  17. '    ' Preserve the current date-modified of the file.
  18. '    fd.Preserve(FileDater.DateType.Modified)
  19. '
  20. '    ' Do some kind of operation that alters the current date-modified of the file.
  21. '    IO.File.AppendAllText(fd.File.FullName, New String("X"c, 10I))
  22. '
  23. '    ' Restore the previously preserved date-modified on the TestFile.
  24. '    fd.Restore(FileDater.DateType.Modified)
  25.  
  26. 'End Using '/ fd
  27.  
  28. #End Region
  29.  
  30. #Region " Example 2 "
  31.  
  32. '' Declare a test filepath.
  33. 'Dim TestFile As String = "C:\Testfile.tmp"
  34. '
  35. '' Create the test file.
  36. 'If Not IO.File.Exists(TestFile) Then
  37. '    Using fs As New IO.FileStream(TestFile, IO.FileMode.CreateNew, IO.FileAccess.ReadWrite)
  38. '    End Using
  39. 'End If
  40. '
  41. '' Instance the FileDater Class.
  42. 'Using fd As New FileDater(File:=TestFile)
  43. '
  44. '    ' Preserve all the current dates of the TestFile.
  45. '    fd.Preserve()
  46. '
  47. '    ' Print the preserved dates in the debug console.
  48. '    Debug.WriteLine(String.Format("Preserved Creation   Date: {0}", fd.PreservedCreationDate.ToString))
  49. '    Debug.WriteLine(String.Format("Preserved LastAccess Date: {0}", fd.PreservedLastAccessDate.ToString))
  50. '    Debug.WriteLine(String.Format("Preserved LastModify Date: {0}", fd.PreservedLastModifyDate.ToString))
  51. '
  52. '    ' Copy the testfile to other location.
  53. '    IO.File.Copy(fd.File.FullName, "C:\New Testfile.tmp", True)
  54. '
  55. '    ' Assign the new location in the instanced FileDater.
  56. '    fd.SetFileLocation("C:\New Testfile.tmp")
  57. '
  58. '    ' Modify all the dated on the copied TestFile.
  59. '    fd.Set(Date.Parse("01/01/2015"))
  60. '
  61. '    ' Restore all the previously preserved dates on the new TestFile.
  62. '    fd.Restore()
  63. '
  64. '    ' Print the current testfile dates in the debug console.
  65. '    Debug.WriteLine(String.Format("Current Creation   Date: {0}", fd.File.CreationTime.ToString))
  66. '    Debug.WriteLine(String.Format("Current LastAccess Date: {0}", fd.File.LastAccessTime.ToString))
  67. '    Debug.WriteLine(String.Format("Current LastModify Date: {0}", fd.File.LastWriteTime.ToString))
  68. '
  69. 'End Using
  70.  
  71. #End Region
  72.  
  73. #End Region
  74.  
  75. #Region " Imports "
  76.  
  77. Imports System.ComponentModel
  78. Imports System.IO
  79.  
  80. #End Region
  81.  
  82. #Region " FileDater "
  83.  
  84. ''' <summary>
  85. ''' Contains methods to preserve, set, and restore the dates contained on file.
  86. ''' </summary>
  87. Public NotInheritable Class FileDater : Implements IDisposable
  88.  
  89. #Region " Objects "
  90.  
  91.    ''' <summary>
  92.    ''' Contains the files that are already used in the constructor to prevent a duplicated instance for the same file.
  93.    ''' </summary>
  94.    Private Shared InstancedFiles As New List(Of FileInfo)
  95.  
  96. #End Region
  97.  
  98. #Region " Properties "
  99.  
  100.    ''' <summary>
  101.    ''' Gets the file.
  102.    ''' </summary>
  103.    ''' <value>The file.</value>
  104.    Public ReadOnly Property [File] As FileInfo
  105.        Get
  106.            Return Me._File
  107.        End Get
  108.    End Property
  109.    Private _File As FileInfo
  110.  
  111.    ''' <summary>
  112.    ''' Gets the type of the current preserved dates.
  113.    ''' </summary>
  114.    Public ReadOnly Property PreservedTypes As DateType
  115.        Get
  116.            Return Me._PreservedTypes
  117.        End Get
  118.    End Property
  119.    Private _PreservedTypes As DateType = Nothing
  120.  
  121.    ''' <summary>
  122.    ''' Gets the preserved creation date.
  123.    ''' </summary>
  124.    ''' <value>The preserved creation date.</value>
  125.    Public ReadOnly Property PreservedCreationDate As Date
  126.        Get
  127.            Return Me._PreservedCreationDate
  128.        End Get
  129.    End Property
  130.    Private _PreservedCreationDate As Date
  131.  
  132.    ''' <summary>
  133.    ''' Gets the preserved last-access date.
  134.    ''' </summary>
  135.    ''' <value>The preserved creation date.</value>
  136.    Public ReadOnly Property PreservedLastAccessDate As Date
  137.        Get
  138.            Return Me._PreservedLastAccessDate
  139.        End Get
  140.    End Property
  141.    Private _PreservedLastAccessDate As Date
  142.  
  143.    ''' <summary>
  144.    ''' Gets the preserved last-modify date.
  145.    ''' </summary>
  146.    ''' <value>The preserved creation date.</value>
  147.    Public ReadOnly Property PreservedLastModifyDate As Date
  148.        Get
  149.            Return Me._PreservedLastModifyDate
  150.        End Get
  151.    End Property
  152.    Private _PreservedLastModifyDate As Date
  153.  
  154. #End Region
  155.  
  156. #Region " Enumerations "
  157.  
  158.    ''' <summary>
  159.    ''' Contains a FileDate flag.
  160.    ''' </summary>
  161.    <FlagsAttribute>
  162.    Public Enum DateType As Integer
  163.  
  164.        ''' <summary>
  165.        ''' The date when the file was created.
  166.        ''' </summary>
  167.        Created = 1I
  168.  
  169.        ''' <summary>
  170.        ''' The date when the file was accessed by last time.
  171.        ''' </summary>
  172.        Accessed = 2I
  173.  
  174.        ''' <summary>
  175.        ''' The date when the file was modified by last time.
  176.        ''' </summary>
  177.        Modified = 4I
  178.  
  179.    End Enum
  180.  
  181. #End Region
  182.  
  183. #Region " Constructors "
  184.  
  185.    ''' <summary>
  186.    ''' Initializes a new instance of the <see cref="FileDater"/> class.
  187.    ''' </summary>
  188.    ''' <param name="File">Indicates the <see cref="FileInfo"/> instance.</param>
  189.    ''' <exception cref="System.Exception"></exception>
  190.    Public Sub New(ByVal [File] As FileInfo)
  191.  
  192.        If Not InstancedFiles.Contains([File]) Then
  193.            Me._File = [File]
  194.            InstancedFiles.Add([File])
  195.  
  196.        Else
  197.            Throw New Exception(String.Format("Another instance of the '{0}' class is using the same file.", MyBase.GetType.Name))
  198.  
  199.        End If
  200.  
  201.    End Sub
  202.  
  203.    ''' <summary>
  204.    ''' Initializes a new instance of the <see cref="FileDater"/> class.
  205.    ''' </summary>
  206.    ''' <param name="File">Indicates the file.</param>
  207.    Public Sub New(ByVal [File] As String)
  208.        Me.New(New FileInfo([File]))
  209.    End Sub
  210.  
  211.    ''' <summary>
  212.    ''' Prevents a default instance of the <see cref="FileDater"/> class from being created.
  213.    ''' </summary>
  214.    Private Sub New()
  215.    End Sub
  216.  
  217. #End Region
  218.  
  219. #Region " Hidden Methods "
  220.  
  221.    ''' <summary>
  222.    ''' Serves as a hash function for a particular type.
  223.    ''' </summary>
  224.    <EditorBrowsable(EditorBrowsableState.Never)>
  225.    Public Shadows Sub GetHashCode()
  226.    End Sub
  227.  
  228.    ''' <summary>
  229.    ''' Determines whether the specified System.Object instances are considered equal.
  230.    ''' </summary>
  231.    <EditorBrowsable(EditorBrowsableState.Never)>
  232.    Public Shadows Sub Equals()
  233.    End Sub
  234.  
  235.    ''' <summary>
  236.    ''' Determines whether the specified System.Object instances are the same instance.
  237.    ''' </summary>
  238.    <EditorBrowsable(EditorBrowsableState.Never)>
  239.    Private Shadows Sub ReferenceEquals()
  240.    End Sub
  241.  
  242.    ''' <summary>
  243.    ''' Returns a String that represents the current object.
  244.    ''' </summary>
  245.    <EditorBrowsable(EditorBrowsableState.Never)>
  246.    Public Shadows Sub ToString()
  247.    End Sub
  248.  
  249. #End Region
  250.  
  251. #Region " Public Methods "
  252.  
  253.    ''' <summary>
  254.    ''' Preserves the specified dates of the file to restore them later at any time.
  255.    ''' Note: Dates can be preserved again at any time.
  256.    ''' </summary>
  257.    ''' <param name="DateType">Indicates the type of dates to preserve.</param>
  258.    Public Sub Preserve(ByVal DateType As DateType)
  259.  
  260.        Me.DisposedCheck()
  261.  
  262.        ' Creation
  263.        If DateType.HasFlag(FileDater.DateType.Created) Then
  264.            Me._PreservedCreationDate = Me._File.CreationTime
  265.        End If
  266.  
  267.        ' Accessed
  268.        If DateType.HasFlag(FileDater.DateType.Accessed) Then
  269.            Me._PreservedLastAccessDate = Me._File.LastAccessTime
  270.        End If
  271.  
  272.        ' Modified
  273.        If DateType.HasFlag(FileDater.DateType.Modified) Then
  274.            Me._PreservedLastModifyDate = Me._File.LastWriteTime
  275.        End If
  276.  
  277.        Me._PreservedTypes = DateType
  278.  
  279.    End Sub
  280.  
  281.    ''' <summary>
  282.    ''' Preserves at once all the dates of the file to restore them later at any time.
  283.    ''' Note: Dates can be preserved again at any time.
  284.    ''' </summary>
  285.    Public Sub Preserve()
  286.  
  287.        Me.DisposedCheck()
  288.  
  289.        Me._PreservedCreationDate = Me._File.CreationTime
  290.        Me._PreservedLastAccessDate = Me._File.LastAccessTime
  291.        Me._PreservedLastModifyDate = Me._File.LastWriteTime
  292.  
  293.        Me._PreservedTypes = DateType.Created Or DateType.Accessed Or DateType.Modified
  294.  
  295.    End Sub
  296.  
  297.    ''' <summary>
  298.    ''' Restores the specified preserved dates on the file.
  299.    ''' Note: Calling this method does not cause the deletion of any preserved date.
  300.    ''' </summary>
  301.    ''' <param name="DateType">Indicates the type of dates to restore on the file.</param>
  302.    ''' <exception cref="System.Exception">Any date was preserved.</exception>
  303.    Public Sub Restore(ByVal DateType As DateType)
  304.  
  305.        Me.DisposedCheck()
  306.  
  307.        ' Creation
  308.        If DateType.HasFlag(FileDater.DateType.Created) _
  309.        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then
  310.  
  311.            Me._File.CreationTime = Me._PreservedCreationDate
  312.  
  313.        ElseIf DateType.HasFlag(FileDater.DateType.Created) _
  314.        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then
  315.  
  316.            Throw New Exception(String.Format("The specified date was not preserved.")) With {
  317.                .Source = FileDater.DateType.Created.ToString
  318.            }
  319.  
  320.        End If
  321.  
  322.        ' Accessed
  323.        If DateType.HasFlag(FileDater.DateType.Accessed) _
  324.        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then
  325.  
  326.            Me._File.LastAccessTime = Me._PreservedLastAccessDate
  327.  
  328.        ElseIf DateType.HasFlag(FileDater.DateType.Accessed) _
  329.        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then
  330.  
  331.            Throw New Exception(String.Format("The specified date was not preserved.")) With {
  332.                .Source = FileDater.DateType.Accessed.ToString
  333.            }
  334.  
  335.        End If
  336.  
  337.        ' Modified
  338.        If DateType.HasFlag(FileDater.DateType.Modified) _
  339.        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then
  340.  
  341.            Me._File.LastWriteTime = Me._PreservedLastModifyDate
  342.  
  343.        ElseIf DateType.HasFlag(FileDater.DateType.Modified) _
  344.        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then
  345.  
  346.            Throw New Exception(String.Format("The specified date was not preserved.")) With {
  347.                .Source = FileDater.DateType.Modified.ToString
  348.            }
  349.  
  350.        End If
  351.  
  352.    End Sub
  353.  
  354.    ''' <summary>
  355.    ''' Restores at once all the preserved dates on the file.
  356.    ''' Note: Calling this method does not cause the deletion of any preserved date.
  357.    ''' </summary>
  358.    Public Sub Restore()
  359.  
  360.        Me.DisposedCheck()
  361.  
  362.        ' Creation
  363.        If Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then
  364.            Me._File.CreationTime = Me._PreservedCreationDate
  365.        End If
  366.  
  367.        ' Accessed
  368.        If Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then
  369.            Me._File.LastAccessTime = Me._PreservedLastAccessDate
  370.        End If
  371.  
  372.        ' Modified
  373.        If Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then
  374.            Me._File.LastWriteTime = Me._PreservedLastModifyDate
  375.        End If
  376.  
  377.    End Sub
  378.  
  379.    ''' <summary>
  380.    ''' Sets the specified dates on the file.
  381.    ''' Note:
  382.    ''' Calling this method does not cause the deletion of any preserved date.
  383.    ''' After setting a date, must call once the <see cref="Preserve"/> method if want to preserve any new date established.
  384.    ''' </summary>
  385.    ''' <param name="DateType">Indicates the type of dates to set on the file.</param>
  386.    ''' <param name="Date">Indicates the date.</param>
  387.    Public Sub [Set](ByVal DateType As DateType, ByVal [Date] As Date)
  388.  
  389.        Me.DisposedCheck()
  390.  
  391.        ' Creation
  392.        If DateType.HasFlag(FileDater.DateType.Created) Then
  393.            Me._File.CreationTime = [Date]
  394.        End If
  395.  
  396.        ' Accessed
  397.        If DateType.HasFlag(FileDater.DateType.Accessed) Then
  398.            Me._File.LastAccessTime = [Date]
  399.        End If
  400.  
  401.        ' Modified
  402.        If DateType.HasFlag(FileDater.DateType.Modified) Then
  403.            Me._File.LastWriteTime = [Date]
  404.        End If
  405.  
  406.    End Sub
  407.  
  408.    ''' <summary>
  409.    ''' Sets at once all the dates on the file.
  410.    ''' Note:
  411.    ''' Calling this method does not cause the deletion of any preserved date.
  412.    ''' After setting a date, must call once the <see cref="Preserve"/> method if want to preserve any new date established.
  413.    ''' </summary>
  414.    ''' <param name="Date">Indicates the date.</param>
  415.    Public Sub [Set](ByVal [Date] As Date)
  416.  
  417.        Me.DisposedCheck()
  418.  
  419.        Me._File.CreationTime = [Date]
  420.        Me._File.LastAccessTime = [Date]
  421.        Me._File.LastWriteTime = [Date]
  422.  
  423.    End Sub
  424.  
  425.    ''' <summary>
  426.    ''' Causes this <see cref="FileDater"/> instance to assign a new location for the current file.
  427.    ''' This could be useful if the preserved dates should be restored in a file that has changed its name/ubication.
  428.    ''' Note: Calling this method does not cause the deletion of any preserved date.
  429.    ''' </summary>
  430.    ''' <param name="File">Indicates the <see cref="FileInfo"/> instance.</param>
  431.    ''' <exception cref="System.Exception"></exception>
  432.    Public Sub SetFileLocation(ByVal [File] As FileInfo)
  433.  
  434.        If Not InstancedFiles.Contains([File]) Then
  435.            InstancedFiles.Remove(Me._File)
  436.            Me._File = [File]
  437.            InstancedFiles.Add([File])
  438.  
  439.        Else
  440.            Throw New Exception(String.Format("Another instance of the '{0}' class is using the same file.", MyBase.GetType.Name))
  441.  
  442.        End If
  443.  
  444.    End Sub
  445.  
  446.    ''' <summary>
  447.    ''' Causes this <see cref="FileDater"/> instance to assign a new location for the current file.
  448.    ''' This could be useful if the preserved dates should be restored in a file that has changed its name/ubication.
  449.    ''' Note: Calling this method does not cause the deletion of any preserved date.
  450.    ''' </summary>
  451.    ''' <param name="File">Indicates the file.</param>
  452.    ''' <exception cref="System.Exception"></exception>
  453.    Public Sub SetFileLocation(ByVal [File] As String)
  454.  
  455.        Me.SetFileLocation(New FileInfo([File]))
  456.  
  457.    End Sub
  458.  
  459. #End Region
  460.  
  461. #Region " IDisposable "
  462.  
  463.    ''' <summary>
  464.    ''' To detect redundant calls when disposing.
  465.    ''' </summary>
  466.    Private IsDisposed As Boolean = False
  467.  
  468.    ''' <summary>
  469.    ''' Prevent calls to methods after disposing.
  470.    ''' </summary>
  471.    ''' <exception cref="System.ObjectDisposedException"></exception>
  472.    Private Sub DisposedCheck()
  473.  
  474.        If Me.IsDisposed Then
  475.            Throw New ObjectDisposedException(Me.GetType().FullName)
  476.        End If
  477.  
  478.    End Sub
  479.  
  480.    ''' <summary>
  481.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  482.    ''' </summary>
  483.    Public Sub Dispose() Implements IDisposable.Dispose
  484.        Dispose(True)
  485.        GC.SuppressFinalize(Me)
  486.    End Sub
  487.  
  488.    ''' <summary>
  489.    ''' Releases unmanaged and - optionally - managed resources.
  490.    ''' </summary>
  491.    ''' <param name="IsDisposing">
  492.    ''' <c>true</c> to release both managed and unmanaged resources;
  493.    ''' <c>false</c> to release only unmanaged resources.
  494.    ''' </param>
  495.    Protected Sub Dispose(ByVal IsDisposing As Boolean)
  496.  
  497.        If Not Me.IsDisposed Then
  498.  
  499.            If IsDisposing Then
  500.                InstancedFiles.Remove(Me._File)
  501.            End If
  502.  
  503.        End If
  504.  
  505.        Me.IsDisposed = True
  506.  
  507.    End Sub
  508.  
  509. #End Region
  510.  
  511. End Class
  512.  
  513. #End Region
6917  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 08:48 am
Ejemplo detallado de como parsear la salida estándar y la salida de error de un proceso, de forma asíncrona.

Código
  1.    ' Usage Examples:
  2.    ' MessageBox.Show(RunCommand(Command:="Dir /B /S C:\*.*", Find:=".exe"))
  3.    ' MessageBox.Show(RunCommand(Command:="Dir /B /S C:\*.*", Find:=".xXx"))
  4.  
  5.    ''' <summary>
  6.    ''' The Process Object.
  7.    ''' </summary>
  8.    Private WithEvents MyProcess As Process =
  9.        New Process With {.StartInfo =
  10.            New ProcessStartInfo With {
  11.                .CreateNoWindow = True,
  12.                .UseShellExecute = False,
  13.                .RedirectStandardError = True,
  14.                .RedirectStandardOutput = True
  15.           }
  16.        }
  17.  
  18.    ''' <summary>
  19.    ''' Indicates the string to search.
  20.    ''' </summary>
  21.    Private Find As String = String.Empty
  22.  
  23.    ''' <summary>
  24.    ''' Determines whether a result is found.
  25.    ''' </summary>
  26.    Private ResultFound As Boolean = False
  27.  
  28.    ''' <summary>
  29.    ''' Runs a command on the CMD.
  30.    ''' </summary>
  31.    ''' <param name="Command">Indicates the Command to run.</param>
  32.    ''' <param name="Find">Indicates a string to find in the Output.</param>
  33.    ''' <returns><c>true</c> if the specified string is found, <c>false</c> otherwise.</returns>
  34.    Public Function RunCommand(ByVal Command As String,
  35.                               ByVal Find As String) As Boolean
  36.  
  37.        Me.Find = Find
  38.        Me.ResultFound = False
  39.  
  40.        With MyProcess
  41.  
  42.            AddHandler .OutputDataReceived, AddressOf RunCommand_OutputDataReceived
  43.            AddHandler .ErrorDataReceived, AddressOf RunCommand_ErrorDataReceived
  44.  
  45.            .StartInfo.FileName = "CMD.exe"
  46.            .StartInfo.Arguments = "/C " & ControlChars.Quote & Command & ControlChars.Quote
  47.  
  48.            .Start()
  49.            .BeginOutputReadLine()
  50.            .BeginErrorReadLine()
  51.            .WaitForExit()
  52.  
  53.            RemoveHandler .OutputDataReceived, AddressOf RunCommand_OutputDataReceived
  54.            RemoveHandler .ErrorDataReceived, AddressOf RunCommand_ErrorDataReceived
  55.  
  56.        End With
  57.  
  58.        Return Me.ResultFound
  59.  
  60.    End Function
  61.  
  62.    ''' <summary>
  63.    ''' Handles the 'OutputDataReceived' of the 'RunCommand' method.
  64.    ''' </summary>
  65.    ''' <param name="sender">The source of the event.</param>
  66.    ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
  67.    Private Sub RunCommand_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
  68.  
  69.        If e.Data Is Nothing OrElse Me.ResultFound Then
  70.  
  71.            With MyProcess
  72.  
  73.                .CancelOutputRead()
  74.  
  75.                If Not .HasExited Then
  76.                    Try
  77.                        .Kill()
  78.                        Debug.WriteLine("Process killed successfully!")
  79.                    Catch ex As Exception
  80.                        Debug.WriteLine(ex.Message)
  81.                    End Try
  82.                End If
  83.  
  84.            End With
  85.  
  86.        ElseIf e.Data.ToLower.Contains(Me.Find.ToLower) Then
  87.            Me.ResultFound = True
  88.            Debug.WriteLine("StdOut: " & e.Data)
  89.            Debug.WriteLine("Result Found!")
  90.            Debug.WriteLine("Stopping CMD execution at this point...")
  91.  
  92.        Else
  93.            Debug.WriteLine("StdOut: " & e.Data)
  94.  
  95.        End If
  96.  
  97.    End Sub
  98.  
  99.    ''' <summary>
  100.    ''' Handles the 'ErrorDataReceived' of the 'RunCommand' method.
  101.    ''' </summary>
  102.    ''' <param name="sender">The source of the event.</param>
  103.    ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
  104.    Private Sub RunCommand_ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
  105.  
  106.        If e.Data Is Nothing OrElse Me.ResultFound Then
  107.  
  108.            With MyProcess
  109.  
  110.                .CancelErrorRead()
  111.  
  112.                If Not .HasExited Then
  113.                    Try
  114.                        .Kill()
  115.                        Debug.WriteLine("Process killed successfully!")
  116.                    Catch ex As Exception
  117.                        Debug.WriteLine(ex.Message)
  118.                    End Try
  119.                End If
  120.  
  121.            End With
  122.  
  123.        Else
  124.            Debug.WriteLine("StdErr: " & e.Data)
  125.  
  126.        End If
  127.  
  128.    End Sub



Un ayudante del proceso MKVMerge (de MKVToolnix)

No le aádí casi funcionalidades, solamente las que necesité usar:

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 07-24-2014
  4. ' ***********************************************************************
  5. ' <copyright file="MKVMergeHelper.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Using MKVMerge As New MKVMergeHelper
  13.  
  14. '    MessageBox.Show(MKVMerge.Version)
  15. '    MessageBox.Show(MKVMerge.ContainsTrackType("File.mkv", MKVMergeHelper.TrackType.Subtitle))
  16.  
  17. 'End Using
  18.  
  19. #End Region
  20.  
  21. Public Class MKVMergeHelper : Implements IDisposable
  22.  
  23. #Region " Properties "
  24.  
  25.    ''' <summary>
  26.    ''' Gets or sets the mkvmerge.exe file location.
  27.    ''' </summary>
  28.    ''' <value>The MKVmerge.exe file location.</value>
  29.    Public Property MKVMergeLocation As String = ".\mkvmerge.exe"
  30.  
  31.    ''' <summary>
  32.    ''' Gets the MKVMerge.exe version.
  33.    ''' </summary>
  34.    ''' <value>The MKVMerge.exe version.</value>
  35.    Public ReadOnly Property Version As String
  36.        Get
  37.            Me.GetVersion()
  38.            Return Me._Version
  39.        End Get
  40.    End Property
  41.    Private _Version As String = String.Empty
  42.  
  43. #End Region
  44.  
  45. #Region " Other Objects "
  46.  
  47.    ''' <summary>
  48.    ''' The MKVMerge Process Object.
  49.    ''' </summary>
  50.    Private WithEvents procMKVMerge As Process =
  51.        New Process With {.StartInfo =
  52.            New ProcessStartInfo With {
  53.                .CreateNoWindow = True,
  54.                .UseShellExecute = False,
  55.                .RedirectStandardError = True,
  56.                .RedirectStandardOutput = True
  57.           }
  58.        }
  59.  
  60.    ''' <summary>
  61.    ''' Determines whether a file contains the specified track type.
  62.    ''' </summary>
  63.    Private TrackTypeFound As Boolean = False
  64.  
  65.    ''' <summary>
  66.    ''' Indicates the current tracktype to search.
  67.    ''' </summary>
  68.    Private CurrentTrackType As TrackType = Nothing
  69.  
  70. #End Region
  71.  
  72. #Region " Enumerations "
  73.  
  74.    ''' <summary>
  75.    ''' Specifies a type of track.
  76.    ''' </summary>
  77.    Public Enum TrackType As Integer
  78.  
  79.        ''' <summary>
  80.        ''' Video track.
  81.        ''' </summary>
  82.        Video = 0
  83.  
  84.        ''' <summary>
  85.        ''' Audio track.
  86.        ''' </summary>
  87.        Audio = 1
  88.  
  89.        ''' <summary>
  90.        ''' Subtitle.
  91.        ''' </summary>
  92.        Subtitle = 2
  93.  
  94.        ''' <summary>
  95.        ''' Attachment.
  96.        ''' </summary>
  97.        Attachment = 3
  98.  
  99.    End Enum
  100.  
  101. #End Region
  102.  
  103. #Region " Public Methods "
  104.  
  105.    ''' <summary>
  106.    ''' Determines whether mkvmerge.exe file exist.
  107.    ''' </summary>
  108.    ''' <returns><c>true</c> if mkvmerge.exe file exist; otherwise, <c>false</c>.</returns>
  109.    Public Function IsAvaliable() As Boolean
  110.  
  111.        Return IO.File.Exists(Me.MKVMergeLocation)
  112.  
  113.    End Function
  114.  
  115.    ''' <summary>
  116.    ''' Determines whether a file contains the specified track type.
  117.    ''' </summary>
  118.    ''' <param name="file">Indicates the file.</param>
  119.    ''' <param name="TrackType">Indicates the type of the track.</param>
  120.    ''' <returns><c>true</c> if the specified track type is found, <c>false</c> otherwise.</returns>
  121.    Public Function ContainsTrackType(ByVal file As String, ByVal TrackType As TrackType) As Boolean
  122.  
  123.        Me.CurrentTrackType = TrackType
  124.        Me.TrackTypeFound = False
  125.  
  126.        With procMKVMerge
  127.  
  128.            AddHandler .OutputDataReceived, AddressOf ContainsTrackType_OutputDataReceived
  129.  
  130.            .StartInfo.FileName = Me.MKVMergeLocation
  131.            .StartInfo.Arguments = String.Format("--identify ""{0}""", file)
  132.  
  133.            .Start()
  134.            .BeginOutputReadLine()
  135.            .WaitForExit()
  136.  
  137.            RemoveHandler .OutputDataReceived, AddressOf ContainsTrackType_OutputDataReceived
  138.  
  139.        End With
  140.  
  141.        Return Me.TrackTypeFound
  142.  
  143.    End Function
  144.  
  145. #End Region
  146.  
  147. #Region " Private Methods "
  148.  
  149.    ''' <summary>
  150.    ''' Gets the MKVMerge.exe file version.
  151.    ''' </summary>
  152.    ''' <returns>The MKVMerge.exe file version.</returns>
  153.    Private Function GetVersion() As String
  154.  
  155.        Me._Version = String.Empty
  156.  
  157.        With procMKVMerge
  158.  
  159.            AddHandler .OutputDataReceived, AddressOf GetVersion_OutputDataReceived
  160.  
  161.            .StartInfo.FileName = Me.MKVMergeLocation
  162.            .StartInfo.Arguments = String.Format("--version")
  163.  
  164.            .Start()
  165.            .BeginOutputReadLine()
  166.            .WaitForExit()
  167.  
  168.            RemoveHandler .OutputDataReceived, AddressOf GetVersion_OutputDataReceived
  169.  
  170.        End With
  171.  
  172.        Return Me.TrackTypeFound
  173.  
  174.    End Function
  175.  
  176. #End Region
  177.  
  178. #Region " Event Handlers "
  179.  
  180.    ''' <summary>
  181.    ''' Handles the OutputDataReceived of the ContainsTrackType method.
  182.    ''' </summary>
  183.    ''' <param name="sender">The source of the event.</param>
  184.    ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
  185.    ''' <exception cref="System.Exception"></exception>
  186.    Private Sub ContainsTrackType_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
  187.  
  188.        If e.Data Is Nothing OrElse Me.TrackTypeFound Then
  189.            With procMKVMerge
  190.                .CancelOutputRead()
  191.                If Not .HasExited Then
  192.                    Try
  193.                        .Kill()
  194.                    Catch
  195.                    End Try
  196.                End If
  197.            End With
  198.  
  199.        ElseIf e.Data.StartsWith("Error:", StringComparison.OrdinalIgnoreCase) Then
  200.            Throw New Exception(e.Data)
  201.  
  202.        ElseIf Me.CurrentTrackType = TrackType.Video _
  203.        AndAlso e.Data.ToLower Like "track id #*: video*" Then
  204.            Me.TrackTypeFound = True
  205.  
  206.        ElseIf Me.CurrentTrackType = TrackType.Audio _
  207.        AndAlso e.Data.ToLower Like "track id #*: audio*" Then
  208.            Me.TrackTypeFound = True
  209.  
  210.        ElseIf Me.CurrentTrackType = TrackType.Subtitle _
  211.        AndAlso e.Data.ToLower Like "track id #*: subtitle*" Then
  212.            Me.TrackTypeFound = True
  213.  
  214.        ElseIf Me.CurrentTrackType = TrackType.Attachment _
  215.        AndAlso e.Data.ToLower Like "attachment id*" Then
  216.            Me.TrackTypeFound = True
  217.  
  218.        End If
  219.  
  220.    End Sub
  221.  
  222.    ''' <summary>
  223.    ''' Handles the OutputDataReceived of the GetVersion method.
  224.    ''' </summary>
  225.    ''' <param name="sender">The source of the event.</param>
  226.    ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
  227.    ''' <exception cref="System.Exception"></exception>
  228.    Private Sub GetVersion_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
  229.  
  230.        If e.Data Is Nothing OrElse Not String.IsNullOrEmpty(Me._Version) Then
  231.            With procMKVMerge
  232.                .CancelOutputRead()
  233.                If Not .HasExited Then
  234.                    Try
  235.                        .Kill()
  236.                    Catch
  237.                    End Try
  238.                End If
  239.            End With
  240.  
  241.        ElseIf e.Data.StartsWith("Error:", StringComparison.OrdinalIgnoreCase) Then
  242.            Throw New Exception(e.Data)
  243.  
  244.        ElseIf e.Data.ToLower Like "mkvmerge v#.*" Then
  245.            Me._Version = e.Data.Split()(1).Substring(1)
  246.  
  247.        End If
  248.  
  249.    End Sub
  250.  
  251. #End Region
  252.  
  253. #Region " IDisposable "
  254.  
  255.    ''' <summary>
  256.    ''' To detect redundant calls when disposing.
  257.    ''' </summary>
  258.    Private IsDisposed As Boolean = False
  259.  
  260.    ''' <summary>
  261.    ''' Prevents calls to methods after disposing.
  262.    ''' </summary>
  263.    Private Sub DisposedCheck()
  264.        If Me.IsDisposed Then
  265.            Throw New ObjectDisposedException(Me.GetType().FullName)
  266.        End If
  267.    End Sub
  268.  
  269.    ''' <summary>
  270.    ''' Disposes the objects generated by this instance.
  271.    ''' </summary>
  272.    Public Sub Dispose() Implements IDisposable.Dispose
  273.        Dispose(True)
  274.        GC.SuppressFinalize(Me)
  275.    End Sub
  276.  
  277.    ' IDisposable
  278.    Protected Overridable Sub Dispose(IsDisposing As Boolean)
  279.  
  280.        If Not Me.IsDisposed Then
  281.  
  282.            If IsDisposing Then
  283.                procMKVMerge.Dispose()
  284.            End If
  285.  
  286.        End If
  287.  
  288.        Me.IsDisposed = True
  289.  
  290.    End Sub
  291.  
  292. #End Region
  293.  
  294. End Class



¿Como prevenir la instancia de una Class si ya tienes otra Class instanciada a la que le pasaste el mismo parámetro a su constructor?, pues de esta manera:

Código
  1. #Region " Example Usage "
  2.  
  3. 'Private Sub Test() Handles MyBase.Shown
  4. '
  5. '    Dim MyObject As Byte = 0
  6. '
  7. '    Using TestObj1 As New TestClass(MyObject)
  8. '
  9. '        Try
  10. '            Dim TestObj2 As New TestClass(MyObject)
  11. '
  12. '        Catch ex As Exception
  13. '            MessageBox.Show(ex.Message)
  14. '
  15. '        End Try
  16. '
  17. '    End Using
  18. '
  19. 'End Sub
  20.  
  21. #End Region
  22.  
  23. #Region " TestClass "
  24.  
  25. Public Class TestClass : Implements IDisposable
  26.  
  27.    Private Shared InstancedObjects As New List(Of Object)
  28.    Private _MyObject As Object
  29.  
  30.    Public Sub New(ByVal Parameter As Object)
  31.  
  32.        If Not InstancedObjects.Contains(Parameter) Then
  33.  
  34.            Me._MyObject = Parameter
  35.            InstancedObjects.Add(Parameter)
  36.  
  37.        Else
  38.  
  39.            Throw New Exception(String.Format("Another open instance of the '{0}' class is using the same '{1}' object.",
  40.                                              MyBase.GetType.Name, Parameter.GetType.Name))
  41.  
  42.        End If
  43.  
  44.    End Sub
  45.  
  46. #Region " IDisposable "
  47.  
  48.    ''' <summary>
  49.    ''' To detect redundant calls when disposing.
  50.    ''' </summary>
  51.    Private IsDisposed As Boolean = False
  52.  
  53.    ''' <summary>
  54.    ''' Prevent calls to methods after disposing.
  55.    ''' </summary>
  56.    ''' <exception cref="System.ObjectDisposedException"></exception>
  57.    Private Sub DisposedCheck()
  58.  
  59.        If Me.IsDisposed Then
  60.            Throw New ObjectDisposedException(Me.GetType.FullName)
  61.        End If
  62.  
  63.    End Sub
  64.  
  65.    ''' <summary>
  66.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  67.    ''' </summary>
  68.    Public Sub Dispose() Implements IDisposable.Dispose
  69.        Me.Dispose(True)
  70.        GC.SuppressFinalize(Me)
  71.    End Sub
  72.  
  73.    ''' <summary>
  74.    ''' Releases unmanaged and - optionally - managed resources.
  75.    ''' </summary>
  76.    ''' <param name="IsDisposing">
  77.    ''' <c>true</c> to release both managed and unmanaged resources;
  78.    ''' <c>false</c> to release only unmanaged resources.
  79.    ''' </param>
  80.    Protected Sub Dispose(ByVal IsDisposing As Boolean)
  81.  
  82.        If Not Me.IsDisposed Then
  83.  
  84.            If IsDisposing Then
  85.                InstancedObjects.Remove(Me._MyObject)
  86.            End If
  87.  
  88.        End If
  89.  
  90.        Me.IsDisposed = True
  91.  
  92.    End Sub
  93.  
  94. #End Region
  95.  
  96. End Class
  97.  
  98. #End Region
  99.  
6918  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 08:43 am
Como promprobar si un Type es serializable:

Código
  1.    ' Is Type Serializable?
  2.    ' By Elektro
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    'MsgBox(IsTypeSerializable(Of String))
  7.    'MsgBox(IsTypeSerializable(GetType(Form)))
  8.    'MsgBox(IsTypeSerializable(0.0F.GetType))
  9.    '
  10.    ''' <summary>
  11.    ''' Determines whether a Type can be serialized.
  12.    ''' </summary>
  13.    ''' <typeparam name="T"></typeparam>
  14.    ''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>
  15.    Private Function IsTypeSerializable(Of T)() As Boolean
  16.  
  17.        Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))
  18.  
  19.    End Function
  20.  
  21.    ''' <summary>
  22.    ''' Determines whether a Type can be serialized.
  23.    ''' </summary>
  24.    ''' <typeparam name="T"></typeparam>
  25.    ''' <param name="Type">The Type.</param>
  26.    ''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>
  27.    Private Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean
  28.  
  29.        Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))
  30.  
  31.    End Function
  32.  



Como comprobar si un objeto es serializable:

Código
  1.    ' Is Object Serializable?
  2.    ' By Elektro
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    'MsgBox(IsObjectSerializable(New ArrayList From {"String Item"}, SerializationFormat.Xml)) ' Result: True
  7.    'MsgBox(IsObjectSerializable(New ArrayList From {New Object() {"Collection", "Of", "Strings"}})) ' Result: False
  8.    '
  9.    ''' <summary>
  10.    ''' Determines whether an object can be serialized.
  11.    ''' </summary>
  12.    ''' <param name="Object">The object.</param>
  13.    ''' <returns><c>true</c> if object can be serialized; otherwise, <c>false</c>.</returns>
  14.    Private Function IsObjectSerializable(ByVal [Object] As Object,
  15.                                          Optional ByVal SerializationFormat As SerializationFormat =
  16.                                                                                SerializationFormat.Xml) As Boolean
  17.  
  18.        Dim Serializer As Object
  19.  
  20.        Using fs As New IO.MemoryStream
  21.  
  22.            Select Case SerializationFormat
  23.  
  24.                Case Data.SerializationFormat.Binary
  25.                    Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
  26.  
  27.                Case Data.SerializationFormat.Xml
  28.                    Serializer = New Xml.Serialization.XmlSerializer([Object].GetType)
  29.  
  30.                Case Else
  31.                    Throw New ArgumentException("Invalid SerializationFormat", SerializationFormat)
  32.  
  33.            End Select
  34.  
  35.            Try
  36.                Serializer.Serialize(fs, [Object])
  37.                Return True
  38.  
  39.            Catch ex As InvalidOperationException
  40.                Return False
  41.  
  42.            End Try
  43.  
  44.        End Using ' fs As New MemoryStream
  45.  
  46.    End Function
  47.  



Ejemplo de sintaxis para una condicional de .Net Framework del proyecto.

Código
  1. #If NET20 Then
  2.        ' This happens when the app targets .NEt Framework 2.0
  3.  
  4. #ElseIf NET40 Then
  5.        ' This happens when the app targets .NEt Framework 4.0
  6.  
  7. #End If
6919  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 3 Agosto 2014, 08:41 am
Como limpiar la consola de depuración, en cualquier momento:
Nota: Asegurarse de no tener más de 1 instancia de VisualStudio en ejecución.

Código
  1.    ' Clear Debug-Console Output
  2.    ' By Elektro
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'EnvDTE' and 'envdte80'
  6.    '
  7.    ''' <summary>
  8.    ''' Clears the debug console output.
  9.    ''' </summary>
  10.    Public Sub ClearDebugConsoleOutput()
  11.  
  12.        DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0"), EnvDTE80.DTE2).
  13.                   ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug").Clear()
  14.  
  15.    End Sub





Como obtener el output de la consola de depuración, en cualquier momento:
Nota: Asegurarse de no tener más de 1 instancia de VisualStudio en ejecución.

Código
  1.    ' Get Debug-Console Output
  2.    ' By Elektro
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'EnvDTE' and 'envdte80'
  6.    '
  7.    ' Usage Examples:
  8.    '
  9.    ' Clipboard.SetText(GetDebugConsoleOutput)
  10.    '
  11.    ''' <summary>
  12.    ''' Gets the debug console output.
  13.    ''' </summary>
  14.    ''' <returns>System.String.</returns>
  15.    Public Function GetDebugConsoleOutput() As String
  16.  
  17.        Dim Output As EnvDTE.TextSelection =
  18.            DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0"), EnvDTE80.DTE2).
  19.                       ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug").TextDocument.Selection
  20.  
  21.        Output.SelectAll()
  22.        Return Output.Text
  23.  
  24.    End Function
6920  Programación / Scripting / MOVIDO: (SOLUCIONADO) Ayuda referente a archivos .sublime-build en: 3 Agosto 2014, 07:41 am
El tema ha sido movido a Programación General.

http://foro.elhacker.net/index.php?topic=419440.0
Páginas: 1 ... 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 [692] 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines