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

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

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

Eleкtro

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 (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 05-03-2014
' ***********************************************************************
' <copyright file="Symbols.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

'Private Sub Test() Handles MyBase.Load

'    Dim dll As String = "C:\C++ lib x64.dll"
'    Dim initialized As Boolean = False
'    Dim hProcess As IntPtr = Nothing

'    Try
'        hProcess = Process.GetCurrentProcess().Handle

'        If (Symbols.SymInitialize(hProcess, Nothing, True)) Then
'            initialized = True
'        Else
'            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
'        End If

'        Dim baseOfDll As IntPtr = Symbols.SymLoadModuleEx(hProcess, IntPtr.Zero, dll,
'                                                          Nothing, 0, 0, IntPtr.Zero,
'                                                          Symbols.SymLoadModuleFlags.Module_And_Symbols)

'        If (baseOfDll = IntPtr.Zero) Then
'            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
'        End If

'        If Not Symbols.SymEnumSymbols(
'            hProcess,
'            baseOfDll,
'            "*",
'            AddressOf EnumSymProc, IntPtr.Zero
'        ) Then
'            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
'        End If

'    Catch ex As Exception
'        Debug.WriteLine(ex.Message)
'    Finally
'        If (initialized) Then
'            Symbols.SymCleanup(hProcess)
'        End If
'    End Try

'End Sub

'Friend Shared Function EnumSymProc(ByVal pSymInfo As IntPtr,
'                                   ByVal SymbolSize As UInteger,
'                                   ByVal UserContext As IntPtr) As Boolean

'    Dim Symbol As New Symbols.SYMBOL_INFO With
'        {
'            .SizeOfStruct = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Symbols.SYMBOL_INFO))
'        }

'    System.Runtime.InteropServices.Marshal.PtrToStructure(pSymInfo, Symbol)

'    Dim sb As New System.Text.StringBuilder

'    With sb

'        .AppendLine(String.Format("Address: {0}", CStr(Symbol.Address)))
'        .AppendLine(String.Format("Flags: {0}", Symbol.Flags.ToString))
'        .AppendLine(String.Format("Index: {0}", CStr(Symbol.Index)))
'        .AppendLine(String.Format("Module Base Address: {0}", CStr(Symbol.ModBase)))
'        .AppendLine(String.Format("Name: {0}", Symbol.Name))
'        .AppendLine(String.Format("Size: {0}", CStr(Symbol.Size)))
'        .AppendLine(String.Format("Tag: {0}", Symbol.Tag.ToString))

'    End With

'    Debug.WriteLine(sb.ToString)

'    Return True

'End Function

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Runtime.InteropServices

#End Region

Public Class Symbols

#Region " P/Invoke "

#Region " Methods "

   ''' <summary>
   ''' Initializes the symbol handler for a process.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681351%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="hProcess">
   ''' A handle that identifies the caller.
   ''' This value should be unique and nonzero, but need not be a process handle.
   ''' However, if you do use a process handle, be sure to use the correct handle.
   ''' If the application is a debugger, use the process handle for the process being debugged.
   ''' Do not use the handle returned by 'GetCurrentProcess' when debugging another process,
   ''' because calling functions like 'SymLoadModuleEx' can have unexpected results.
   ''' </param>
   ''' <param name="UserSearchPath">
   ''' The path, or series of paths separated by a semicolon (;), that is used to search for symbol files.
   ''' If this parameter is NULL, the library attempts to form a symbol path from the following sources:
   ''' The current working directory of the application.
   ''' The _NT_SYMBOL_PATH environment variable.
   ''' The _NT_ALTERNATE_SYMBOL_PATH environment variable.
   ''' </param>
   ''' <param name="fInvadeProcess">
   ''' If this value is TRUE, enumerates the loaded modules for the process
   ''' and effectively calls the 'SymLoadModule64' function for each module.</param>
   ''' <returns>
   ''' If the function succeeds, the return value is <c>true</c>.
   ''' If the function fails, the return value is <c>false</c>.
   ''' </returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymInitialize(
              ByVal hProcess As IntPtr,
              ByVal UserSearchPath As String,
              <MarshalAs(UnmanagedType.Bool)>
              ByVal fInvadeProcess As Boolean
       ) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ''' <summary>
   ''' Deallocates all resources associated with the process handle.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680696%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="hProcess">A handle to the process that was originally passed to the 'SymInitialize' function.</param>
   ''' <returns>
   ''' If the function succeeds, the return value is <c>true</c>.
   ''' If the function fails, the return value is <c>false</c>.
   ''' </returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymCleanup(
              ByVal hProcess As IntPtr
       ) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ''' <summary>
   ''' Sets the options mask.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681366%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="SymOptions"></param>
   ''' <returns>The function returns the current options mask.</returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymSetOptions(
              ByVal SymOptions As SymOptionFlags
       ) As Integer
   End Function

   ''' <summary>
   ''' Loads the symbol table for the specified module.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681353%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="hProcess">
   ''' A handle to the process that was originally passed to the 'SymInitialize' function.
   ''' </param>
   ''' <param name="hFile">
   ''' The 'h fileA' handle to the file for the executable image.
   ''' This argument is used mostly by debuggers, where the debugger passes the file handle obtained from a debugging event.
   ''' A value of NULL indicates that 'hFile' is not used.
   ''' </param>
   ''' <param name="ImageName">
   ''' The name of the executable image.
   ''' This name can contain a partial path, a full path, or no path at all.
   ''' If the file cannot be located by the name provided, the symbol search path is used.
   ''' </param>
   ''' <param name="ModuleName">
   ''' A shortcut name for the module.
   ''' If the pointer value is NULL, the library creates a name using the base name of the symbol file.
   ''' </param>
   ''' <param name="BaseOfDll">
   ''' The load address of the module.
   ''' If the value is zero, the library obtains the load address from the symbol file.
   ''' The load address contained in the symbol file is not necessarily the actual load address.
   ''' Debuggers and other applications having an actual load address should use the real load address when calling this function.
   ''' If the image is a '.pdb' file, this parameter cannot be zero.
   ''' </param>
   ''' <param name="DllSize">
   ''' The size of the module, in bytes.
   ''' If the value is zero, the library obtains the size from the symbol file.
   ''' The size contained in the symbol file is not necessarily the actual size.
   ''' Debuggers and other applications having an actual size should use the real size when calling this function.
   ''' If the image is a '.pdb' file, this parameter cannot be zero.
   ''' </param>
   ''' <param name="Data">
   ''' A pointer to a 'MODLOAD_DATA' structure that represents headers other than the standard PE header.
   ''' This parameter is optional and can be NULL.
   ''' </param>
   ''' <param name="Flags">
   ''' This parameter can be one or more of the 'SymLoadModuleFlags' Enum values.
   ''' If this parameter is zero, the function loads the modules and the symbols for the module.
   ''' </param>
   ''' <returns>
   ''' If the function succeeds, the return value is the base address of the loaded module.
   ''' If the function fails, the return value is zero. To retrieve extended error information, call 'GetLastError'.
   ''' If the module is already loaded, the return value is zero and 'GetLastError' returns 'ERROR_SUCCESS'.
   ''' </returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymLoadModuleEx(
              ByVal hProcess As IntPtr,
              ByVal hFile As IntPtr,
              ByVal ImageName As String,
              ByVal ModuleName As String,
              ByVal BaseOfDll As Long,
              ByVal DllSize As Integer,
              ByVal Data As IntPtr,
              ByVal Flags As SymLoadModuleFlags
       ) As ULong
   End Function

   ''' <summary>
   ''' Enumerates all symbols in a process.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680718%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="hProcess">
   ''' A handle to a process.
   ''' This handle must have been previously passed to the 'SymInitialize' function.
   ''' </param>
   ''' <param name="BaseOfDll">
   ''' The base address of the module.
   ''' If this value is zero and 'Mask' contains an exclamation point (!),
   ''' the function looks across modules.
   ''' If this value is zero and 'Mask' does not contain an exclamation point,
   ''' the function uses the scope established by the 'SymSetContext' function.
   ''' </param>
   ''' <param name="Mask">
   ''' A wildcard string that indicates the names of the symbols to be enumerated.
   ''' The text can optionally contain the wildcards, "*" and "?".
   ''' </param>
   ''' <param name="EnumSymbolsCallback">
   ''' A 'SymEnumSymbolsProc' callback function that receives the symbol information.
   ''' </param>
   ''' <param name="UserContext">
   ''' A user-defined value that is passed to the callback function, or NULL.
   ''' This parameter is typically used by an application to pass a pointer to a data structure
   ''' that provides context for the callback function.
   ''' </param>
   ''' <returns>
   ''' If the function succeeds, the return value is <c>true</c>.
   ''' If the function fails, the return value is <c>false</c>.
   ''' </returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymEnumSymbols(
              ByVal hProcess As IntPtr,
              ByVal BaseOfDll As ULong,
              <MarshalAs(UnmanagedType.LPWStr)>
              ByVal Mask As String,
              ByVal EnumSymbolsCallback As SymEnumSymbolsProc,
              ByVal UserContext As IntPtr
       ) As Boolean
   End Function

#End Region

#End Region

#Region " Types "

   ''' <summary>
   ''' Contains symbol information.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680686%28v=vs.85%29.aspx
   ''' </summary>
   <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
   Public Class SYMBOL_INFO

       ''' <summary>
       ''' The size of the structure, in bytes.
       ''' This member must be set to sizeof(SYMBOL_INFO).
       ''' Note that the total size of the data is the SizeOfStruct + (MaxNameLen - 1) * sizeof(TCHAR).
       ''' The reason to subtract one is that the first character in the name is accounted for in the size of the structure.
       ''' </summary>
       Public SizeOfStruct As UInteger

       ''' <summary>
       ''' A unique value that identifies the type data that describes the symbol.
       ''' This value does not persist between sessions.
       ''' </summary>
       Public TypeIndex As UInteger

       ''' <summary>
       ''' This member is reserved for system use.
       ''' </summary>
       Public Reserved1 As ULong

       ''' <summary>
       ''' This member is reserved for system use.
       ''' </summary>
       Public Reserved2 As ULong

       ''' <summary>
       ''' The unique value for the symbol.
       ''' The value associated with a symbol is not guaranteed to be the same each time you run the process.
       ''' For PDB symbols, the index value for a symbol is not generated until
       ''' the symbol is enumerated or retrieved through a search by name or address.
       ''' The index values for all CodeView and COFF symbols are generated when the symbols are loaded.
       ''' </summary>
       Public Index As UInteger

       ''' <summary>
       ''' The symbol size, in bytes.
       ''' This value is meaningful only if the module symbols are from a pdb file;
       ''' otherwise, this value is typically zero and should be ignored.
       ''' </summary>
       Public Size As UInteger

       ''' <summary>
       ''' The base address of the module that contains the symbol.
       ''' </summary>
       Public ModBase As ULong

       ''' <summary>
       ''' The symbol information.
       ''' This member can be one or more of the 'SymFlag' values.
       ''' </summary>
       Public Flags As SymFlag

       ''' <summary>
       ''' The value of a constant.
       ''' </summary>
       Public Value As ULong

       ''' <summary>
       ''' The virtual address of the start of the symbol.
       ''' </summary>
       Public Address As ULong

       ''' <summary>
       ''' The register.
       ''' </summary>
       Public Register As UInteger

       ''' <summary>
       ''' The DIA scope.
       ''' For more information, see the Debug Interface Access SDK in the Visual Studio documentation.
       ''' (This resource may not be available in some languages and countries.)
       ''' </summary>
       Public Scope As UInteger

       ''' <summary>
       ''' The PDB classification.
       ''' These values are defined in 'Dbghelp.h' in the 'SymTagEnum' enumeration type.
       ''' </summary>
       Public Tag As SymTagEnum

       ''' <summary>
       ''' The length of the name, in characters, not including the null-terminating character.
       ''' </summary>
       Public NameLen As UInteger

       ''' <summary>
       ''' The size of the Name buffer, in characters.
       ''' If this member is 0, the Name member is not used.
       ''' </summary>
       Public MaxNameLen As UInteger

       ''' <summary>
       ''' The name of the symbol.
       ''' The name can be undecorated if the 'SYMOPT_UNDNAME' option is used with the 'SymSetOptions' function.
       ''' </summary>
       <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1024I)>
       Public Name As String

   End Class

#End Region

#Region " Enumerations "

   ''' <summary>
   ''' Flags for 'SymLoadModuleEx' function.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681353%28v=vs.85%29.aspx
   ''' </summary>
   <Description("Enum used as 'Flags' parameter of 'SymLoadModuleEx' function")>
   <FlagsAttribute()>
   Public Enum SymLoadModuleFlags As Integer

       ''' <summary>
       ''' Loads the module and the symbols for the module.
       ''' </summary>
       Module_And_Symbols = &H0UI

       ''' <summary>
       ''' Loads the module but not the symbols for the module.
       ''' </summary>
       Only_Module = &H4UI

       ''' <summary>
       ''' Creates a virtual module named 'ModuleName' at the address specified in 'BaseOfDll'.
       ''' To add symbols to this module, call the 'SymAddSymbol' function.
       ''' </summary>
       Virtual = &H1UI

   End Enum

   ''' <summary>
   ''' Contains symbol information.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680686%28v=vs.85%29.aspx
   ''' </summary>
   <Description("Enum used as 'Flags' property of 'SYMBOL_INFO' Class")>
   <FlagsAttribute>
   Public Enum SymFlag As UInteger

       ''' <summary>
       ''' The Value member is used.
       ''' </summary>
       VALUEPRESENT = &H1UI

       ''' <summary>
       ''' The symbol is a register.
       ''' The Register member is used.
       ''' </summary>
       REGISTER = &H8UI

       ''' <summary>
       ''' Offsets are register relative.
       ''' </summary>
       REGREL = &H10UI

       ''' <summary>
       ''' Offsets are frame relative.
       ''' </summary>
       FRAMEREL = &H20UI

       ''' <summary>
       ''' The symbol is a parameter.
       ''' </summary>
       PARAMETER = &H40UI

       ''' <summary>
       ''' The symbol is a local variable.
       ''' </summary>
       LOCAL = &H80UI

       ''' <summary>
       ''' The symbol is a constant.
       ''' </summary>
       CONSTANT = &H100UI

       ''' <summary>
       ''' The symbol is from the export table.
       ''' </summary>
       EXPORT = &H200UI

       ''' <summary>
       ''' The symbol is a forwarder.
       ''' </summary>
       FORWARDER = &H400UI

       ''' <summary>
       ''' The symbol is a known function.
       ''' </summary>
       [FUNCTION] = &H800UI

       ''' <summary>
       ''' The symbol is a virtual symbol created by the 'SymAddSymbol' function.
       ''' </summary>
       VIRTUAL = &H1000UI

       ''' <summary>
       ''' The symbol is a thunk.
       ''' </summary>
       THUNK = &H2000UI

       ''' <summary>
       ''' The symbol is an offset into the TLS data area.
       ''' </summary>
       TLSREL = &H4000UI

       ''' <summary>
       ''' The symbol is a managed code slot.
       ''' </summary>
       SLOT = &H8000UI

       ''' <summary>
       ''' The symbol address is an offset relative to the beginning of the intermediate language block.
       ''' This applies to managed code only.
       ''' </summary>
       ILREL = &H10000UI

       ''' <summary>
       ''' The symbol is managed metadata.
       ''' </summary>
       METADATA = &H20000UI

       ''' <summary>
       ''' The symbol is a CLR token.
       ''' </summary>
       CLR_TOKEN = &H40000UI

   End Enum

   ''' <summary>
   ''' Specifies the type of symbol.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/bkedss5f.aspx
   ''' </summary>
   <Description("Enum used as 'Tag' property of 'SYMBOL_INFO' Class")>
   <Flags>
   Public Enum SymTagEnum As UInteger

       ''' <summary>
       ''' Indicates that the symbol has no type.
       ''' </summary>
       Null

       ''' <summary>
       ''' Indicates that the symbol is an .exe file.
       ''' There is only one SymTagExe symbol per symbol store.
       ''' It serves as the global scope and does not have a lexical parent.
       ''' </summary>
       Exe

       ''' <summary>
       ''' Indicates the compiland symbol for each compiland component of the symbol store.
       ''' For native applications, SymTagCompiland symbols correspond to the object files linked into the image.
       ''' For some kinds of Microsoft Intermediate Language (MSIL) images, there is one compiland per class.
       ''' </summary>
       Compiland

       ''' <summary>
       ''' Indicates that the symbol contains extended attributes of the compiland.
       ''' Retrieving these properties may require loading compiland symbols.
       ''' </summary>
       CompilandDetails

       ''' <summary>
       ''' Indicates that the symbol is an environment string defined for the compiland.
       ''' </summary>
       CompilandEnv

       ''' <summary>
       ''' Indicates that the symbol is a function.
       ''' </summary>
       [Function]

       ''' <summary>
       ''' Indicates that the symbol is a nested block.
       ''' </summary>
       Block

       ''' <summary>
       ''' Indicates that the symbol is data.
       ''' </summary>
       Data

       ''' <summary>
       ''' Indicates that the symbol is for a code annotation.
       ''' Children of this symbol are constant data strings (SymTagData, LocIsConstant, DataIsConstant).
       ''' Most clients ignore this symbol.
       ''' </summary>
       Annotation

       ''' <summary>
       ''' Indicates that the symbol is a label.
       ''' </summary>
       Label

       ''' <summary>
       ''' Indicates that the symbol is a public symbol. For native applications,
       ''' this symbol is the COFF external symbol encountered while linking the image.
       ''' </summary>
       PublicSymbol

       ''' <summary>
       ''' Indicates that the symbol is a user-defined type (structure, class, or union).
       ''' </summary>
       UDT

       ''' <summary>
       ''' Indicates that the symbol is an enumeration.
       ''' </summary>
       [Enum]

       ''' <summary>
       ''' Indicates that the symbol is a function signature type.
       ''' </summary>
       FunctionType

       ''' <summary>
       ''' Indicates that the symbol is a pointer type.
       ''' </summary>
       PointerType

       ''' <summary>
       ''' Indicates that the symbol is an array type.
       ''' </summary>
       ArrayType

       ''' <summary>
       ''' Indicates that the symbol is a base type.
       ''' </summary>
       BaseType

       ''' <summary>
       ''' Indicates that the symbol is a typedef, that is, an alias for another type.
       ''' </summary>
       Typedef

       ''' <summary>
       ''' Indicates that the symbol is a base class of a user-defined type.
       ''' </summary>
       BaseClass

       ''' <summary>
       ''' Indicates that the symbol is a friend of a user-defined type.
       ''' </summary>
       [Friend]

       ''' <summary>
       ''' Indicates that the symbol is a function argument.
       ''' </summary>
       FunctionArgType

       ''' <summary>
       ''' Indicates that the symbol is the end location of the function's prologue code.
       ''' </summary>
       FuncDebugStart

       ''' <summary>
       ''' Indicates that the symbol is the beginning location of the function's epilogue code.
       ''' </summary>
       FuncDebugEnd

       ''' <summary>
       ''' Indicates that the symbol is a namespace name, active in the current scope.
       ''' </summary>
       UsingNamespace

       ''' <summary>
       ''' Indicates that the symbol is a virtual table description.
       ''' </summary>
       VTableShape

       ''' <summary>
       ''' Indicates that the symbol is a virtual table pointer.
       ''' </summary>
       VTable

       ''' <summary>
       ''' Indicates that the symbol is a custom symbol and is not interpreted by DIA.
       ''' </summary>
       Custom

       ''' <summary>
       ''' Indicates that the symbol is a thunk used for sharing data between 16 and 32 bit code.
       ''' </summary>
       Thunk

       ''' <summary>
       ''' Indicates that the symbol is a custom compiler symbol.
       ''' </summary>
       CustomType

       ''' <summary>
       ''' Indicates that the symbol is in metadata.
       ''' </summary>
       ManagedType

       ''' <summary>
       ''' Indicates that the symbol is a FORTRAN multi-dimensional array.
       ''' </summary>
       Dimension

       ''' <summary>
       ''' Indicates that the symbol represents the call site.
       ''' </summary>
       CallSite

       ''' <summary>
       ''' Indicates that the symbol represents the inline site.
       ''' </summary>
       InlineSite

       ''' <summary>
       ''' Indicates that the symbol is a base interface.
       ''' </summary>
       BaseInterface

       ''' <summary>
       ''' Indicates that the symbol is a vector type.
       ''' </summary>
       VectorType

       ''' <summary>
       ''' Indicates that the symbol is a matrix type.
       ''' </summary>
       MatrixType

       ''' <summary>
       ''' Indicates that the symbol is a High Level Shader Language type.
       ''' </summary>
       HLSLType

   End Enum

   ''' <summary>
   ''' Sets the options mask.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681366%28v=vs.85%29.aspx
   ''' </summary>
   <Description("Enum used as 'SymOptions' parameter of 'SymSetOptions' function")>
   <Flags>
   Public Enum SymOptionFlags As Integer

       ''' <summary>
       ''' Enables the use of symbols that do not have an address.
       ''' By default, DbgHelp filters out symbols that do not have an address.
       ''' </summary>
       ALLOW_ZERO_ADDRESS = &H1000000

       ''' <summary>
       ''' All symbol searches are insensitive to case.
       ''' </summary>
       CASE_INSENSITIVE = &H1

       ''' <summary>
       ''' Pass debug output through OutputDebugString or the SymRegisterCallbackProc64 callback function.
       ''' </summary>
       DEBUG = &H80000000

       ''' <summary>
       ''' Symbols are not loaded until a reference is made requiring the symbols be loaded.
       ''' This is the fastest, most efficient way to use the symbol handler.
       ''' </summary>
       DEFERRED_LOADS = &H4

       ''' <summary>
       ''' Do not load an unmatched .pdb file.
       ''' Do not load export symbols if all else fails.
       ''' </summary>
       EXACT_SYMBOLS = &H400

       ''' <summary>
       ''' Do not display system dialog boxes when there is a media failure such as no media in a drive.
       ''' Instead, the failure happens silently.
       ''' </summary>
       FAIL_CRITICAL_ERRORS = &H200

       ''' <summary>
       ''' If there is both an uncompressed and a compressed file available, favor the compressed file.
       ''' This option is good for slow connections.
       ''' </summary>
       FAVOR_COMPRESSED = &H800000

       ''' <summary>
       ''' Ignore path information in the CodeView record of the image header when loading a .pdb file.
       ''' </summary>
       IGNORE_CVREC = &H80

       ''' <summary>
       ''' When debugging on 64-bit Windows, include any 32-bit modules.
       ''' </summary>
       INCLUDE_32BIT_MODULES = &H2000

       ''' <summary>
       ''' Disable checks to ensure a file (.exe, .dbg., or .pdb) is the correct file.
       ''' Instead, load the first file located.
       ''' </summary>
       LOAD_ANYTHING = &H40

       ''' <summary>
       ''' Loads line number information.
       ''' </summary>
       LOAD_LINES = &H10

       ''' <summary>
       ''' All C++ decorated symbols containing the symbol separator "::" are replaced by "__".
       ''' This option exists for debuggers that cannot handle parsing real C++ symbol names.
       ''' </summary>
       NO_CPP = &H8

       ''' <summary>
       ''' Prevents prompting for validation from the symbol server.
       ''' </summary>
       NO_PROMPTS = &H80000

       ''' <summary>
       ''' Prevents symbols from being loaded when the caller examines symbols across multiple modules.
       ''' Examine only the module whose symbols have already been loaded.
       ''' </summary>
       NO_UNQUALIFIED_LOADS = &H100

       ''' <summary>
       ''' 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.
       ''' DbgHelp 6.0 and 6.1:  This flag can be cleared.
       ''' DbgHelp 5.1:  This value is not supported.
       ''' </summary>
       SECURE = &H40000

       ''' <summary>
       ''' All symbols are presented in undecorated form.
       ''' This option has no effect on global or local symbols because they are stored undecorated.
       ''' This option applies only to public symbols.
       ''' </summary>
       UNDNAME = &H2

   End Enum

#End Region

#Region " Delegates "

   ''' <summary>
   ''' An application-defined callback function used with the 'SymEnumSymbols', 'SymEnumTypes', and 'SymEnumTypesByName' functions.
   ''' </summary>
   ''' <param name="pSymInfo">
   ''' A pointer to a 'SYMBOL_INFO' structure that provides information about the symbol.
   ''' </param>
   ''' <param name="SymbolSize">
   ''' The size of the symbol, in bytes.
   ''' The size is calculated and is actually a guess.
   ''' In some cases, this value can be zero.
   ''' </param>
   ''' <param name="UserContext">
   ''' The user-defined value passed from the 'SymEnumSymbols' or 'SymEnumTypes' function, or NULL.
   ''' This parameter is typically used by an application to pass a pointer to a data structure
   ''' that provides context information for the callback function.</param>
   ''' <returns>
   ''' If the function returns <c>true</c>, the enumeration will continue.
   ''' If the function returns <c>false</c>, the enumeration will stop.
   ''' </returns>
   Friend Delegate Function SymEnumSymbolsProc(
          ByVal pSymInfo As IntPtr,
          ByVal SymbolSize As UInteger,
          ByVal UserContext As IntPtr
   ) As Boolean

#End Region

End Class








Eleкtro

#401
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 (vbnet) [Seleccionar]
  ' Hex To VBHex
   ' By Elektro
   '
   ' Usage Examples:
   '
   ' MsgBox(HexToVBHex("FF4"))                        ' Result: &HFF4
   ' MsgBox(HexToVBHex("0xFF4"))                      ' Result: &HFF4
   ' Dim Value As Integer = CInt(HexToVBHex("0xFF4")) ' Result: 4084
   '
   ''' <summary>
   ''' Converts an Hexadecimal value to VisualBasic Hexadecimal syntax.
   ''' </summary>
   ''' <param name="Value">The Hexadecimal value as String.</param>
   ''' <returns>System.String.</returns>
   Public Function HexToVBHex(ByVal Value As String) As String

       If (String.IsNullOrEmpty(Value) Or String.IsNullOrWhiteSpace(Value)) Then
           Throw New ArgumentNullException(Value)
       End If

       Return String.Format("&H{0}", Value.
                                     TrimStart({"0"c, "x"c, "X"c, " "c, ControlChars.NullChar}).
                                     TrimEnd({" "c, ControlChars.NullChar}))

   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 (vbnet) [Seleccionar]
   Dim Randomizer As New Random

   ' Get Random String
   ' // By Elektro
   '
   ' Usage Examples :
   ' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 10))
   ' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyz", 10, RandomizeCase:=True))
   '
   ''' <summary>
   ''' Gets a random string.
   ''' </summary>
   ''' <param name="CharacterSet">Indicates the characters to randomize.</param>
   ''' <param name="StringLength">Indicates the resulting string length.</param>
   ''' <param name="RandomizeCase">If set to <c>true</c>, lower-case and upper-case are randomized.</param>
   ''' <returns>System.String.</returns>
   ''' <exception cref="System.Exception">
   ''' CharacterSet is empty.
   ''' or
   ''' String-Length must be greater than 0.
   ''' </exception>
   Private Function GetRandomString(ByVal CharacterSet As Char(),
                                    ByVal StringLength As Integer,
                                    Optional ByVal RandomizeCase As Boolean = False) As String

       Select Case CharacterSet.Count

           Case Is = 0
               Throw New Exception("CharacterSet is empty.")

           Case Is = 1
               Return New String(CharacterSet.First, Math.Abs(StringLength))

           Case Else

               Select Case StringLength

                   Case Is < 1
                       Throw New Exception("String-Length must be greater than 0.")

                   Case Else

                       Dim CharSetLength As Integer = CharacterSet.Length
                       Dim CharSB As New System.Text.StringBuilder

                       Do Until CharSB.Length = StringLength

                           If Not RandomizeCase Then
                               CharSB.Append(CharacterSet(Randomizer.Next(0, CharSetLength)))

                           Else

                               Select Case Randomizer.Next(0, 2)

                                   Case 0 ' Lower-Case
                                       CharSB.Append(Char.ToLower(CharacterSet(Randomizer.Next(0, CharSetLength))))

                                   Case 1 ' Upper-Case
                                       CharSB.Append(Char.ToUpper(CharacterSet(Randomizer.Next(0, CharSetLength))))

                               End Select

                           End If '/ Not RandomizeCase

                       Loop '/ CharSB.Length = StringLength

                       Return CharSB.ToString

               End Select '/ StringLength

       End Select '/  CharacterSet.Count

   End Function






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

Código (vbnet) [Seleccionar]
   ' RegEx-Match IPv4
   ' By Elektro
   '
   ' expression taken from: http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
   '
   ' Usage Examples :
   ' Dim Addresses As String = "127.0.0.1 | 192.17.200.13 | 255.255.255.255 | 999.999.999.999"
   ' Dim Matches As System.Text.RegularExpressions.MatchCollection = RegExMatch_IPv4(Addresses)
   ' For Each m As System.Text.RegularExpressions.Match In Matches
   '     MessageBox.Show(m.Value)
   ' Next
   '
   ''' <summary>
   ''' Matches the IPv4 addresses contained in a String, using Regular Expressions.
   ''' </summary>
   ''' <param name="str">The string.</param>
   ''' <param name="options">The RegEx options.</param>
   ''' <returns>System.Text.RegularExpressions.MatchCollection.</returns>
   Private Function RegExMatch_IPv4(ByVal str As String,
                                    Optional ByVal options As System.Text.RegularExpressions.RegexOptions =
                                                              System.Text.RegularExpressions.RegexOptions.None
                                                              ) As System.Text.RegularExpressions.MatchCollection

       ' Match criteria:
       '
       ' ([0-255].[0-255].[0-255].[0-255])

       Dim Pattern As String =
           <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

       Return New System.Text.RegularExpressions.Regex(Pattern).Matches(str)

   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: fec0:fff::1
por lo demás todo bien.

Código (vbnet) [Seleccionar]
   ' RegEx-Match IPv6
   ' By Elektro
   '
   ' expression taken from: http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
   '
   ' Usage Examples :
   ' Dim Addresses As String = "FE80:0000:0000:0000:0202:B3FF:FE1E:8329 | FEC0:FFFF:0000:0000:0000:0000:0000:1"
   ' Dim Matches As System.Text.RegularExpressions.MatchCollection = RegExMatch_IPv6(Addresses)
   ' For Each m As System.Text.RegularExpressions.Match In Matches
   '     MessageBox.Show(m.Value)
   ' Next
   '
   ''' <summary>
   ''' Matches the IPv6 addresses (full or compressed) contained in a String, using Regular Expressions.
   ''' </summary>
   ''' <param name="str">The string.</param>
   ''' <param name="options">The RegEx options.</param>
   ''' <returns>System.Text.RegularExpressions.MatchCollection.</returns>
   Private Function RegExMatch_IPv6(ByVal str As String,
                                    Optional ByVal options As System.Text.RegularExpressions.RegexOptions =
                                                              System.Text.RegularExpressions.RegexOptions.None
                                                              ) As System.Text.RegularExpressions.MatchCollection

       Dim Pattern As String =
           <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

       Return New System.Text.RegularExpressions.Regex(Pattern).Matches(str)

   End Function








Eleкtro

Ejemplo de como usar un Proxy:

Código (vbnet) [Seleccionar]
        Dim Request As Net.HttpWebRequest = Net.HttpWebRequest.Create("http://whatismyipaddress.com/")

        With Request
            .Proxy = New Net.WebProxy(Host:="93.115.8.229", Port:=7808)
        End With

        Using StrReader As New IO.StreamReader(Request.GetResponse().GetResponseStream)

            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]?)")
            Dim IPValue As String = IPRegEx.Match(StrReader.ReadToEnd).Value

            MessageBox.Show(String.Format("Your IP Adress is: {0}", IPValue))

        End Using





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

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 08-03-2014
' ***********************************************************************
' <copyright file="WindowFlasher.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

''Flash the Button TaskBar until the window becomes active.
'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.TaskBar Or WindowFlasher.FlashFlags.Until_Foreground)

''Flash the Caption and the Button TaskBar until the "Stop" flag is set.
'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.All Or WindowFlasher.FlashFlags.Until_Stop)

''Set the "Stop" flag, to stop flashing.
'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.Stop)

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Runtime.InteropServices

#End Region

''' <summary>
''' Flashes a Window and/or it's button in the TaskBar.
''' </summary>
Public Class WindowFlasher

#Region " P/Invoke "

    ''' <summary>
    ''' Contains Native Windows API Methods.
    ''' </summary>
    Friend Class NativeMethods

#Region " Methods "

        ''' <summary>
        ''' Flashes the specified window.
        ''' It does not change the active state of the window.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms679347%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="pwfi">A pointer to a FLASHWINFO structure.</param>
        ''' <returns>
        ''' The return value specifies the window's state before the call to the FlashWindowEx function.
        ''' If the window caption was drawn as active before the call, the return value is nonzero.
        ''' Otherwise, the return value is zero.
        ''' </returns>
        <DllImport("user32.dll")>
        Friend Shared Function FlashWindowEx(
               ByRef pwfi As FLASHWINFO
        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
        End Function

#End Region

#Region " Structures "

        ''' <summary>
        ''' Contains the flash status for a window and the number of times the system should flash the window.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms679348%28v=vs.85%29.aspx
        ''' </summary>
        <StructLayout(LayoutKind.Sequential)>
        Friend Structure FLASHWINFO

            ''' <summary>
            ''' The size of the structure, in bytes.
            ''' </summary>
            Friend cbSize As UInteger

            ''' <summary>
            ''' A handle to the window to be flashed.
            ''' The window can be either opened or minimized.
            ''' </summary>
            Friend hwnd As IntPtr

            ''' <summary>
            ''' The flash status.
            ''' </summary>
            Friend dwFlags As FlashFlags

            ''' <summary>
            ''' The number of times to flash the window.
            ''' </summary>
            Friend uCount As UInteger

            ''' <summary>
            ''' The rate at which the window is to be flashed, in milliseconds.
            ''' If dwTimeout is zero, the function uses the default cursor blink rate.
            ''' </summary>
            Friend dwTimeout As UInteger

        End Structure

#End Region

    End Class

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Contains the flash status for a window.
    ''' </summary>
    <Description("Enum used as 'FlashFlags' parameter in 'FlashWindow' function.")>
    <Flags>
    Public Enum FlashFlags As Integer

        ''' <summary>
        ''' Stop flashing.
        ''' The system restores the window to its original state.
        ''' </summary>   
        [Stop] = 0I

        ''' <summary>
        ''' Flash the window caption.
        ''' </summary>
        Caption = 1I

        ''' <summary>
        ''' Flash the taskbar button.
        ''' </summary>
        TaskBar = 2I

        ''' <summary>
        ''' Flash both the window caption and taskbar button.
        ''' This is equivalent to setting the 'Caption Or TaskBar' flags.
        ''' </summary>
        All = 3I

        ''' <summary>
        ''' Flash continuously, until the 'Stop' flag is set.
        ''' </summary>
        Until_Stop = 4I

        ''' <summary>
        ''' Flash continuously until the window comes to the foreground.
        ''' </summary>
        Until_Foreground = 12I

    End Enum

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Flashes the specified window.
    ''' It does not change the active state of the window.
    ''' </summary>
    ''' <param name="Handle">
    ''' Indicates the handle to the window to flash.
    ''' </param>
    ''' <param name="FlashFlags">
    ''' Indicates the flash flags.
    ''' </param>
    ''' <param name="FlashCount">
    ''' Indicates the number of times to flash the window.
    ''' </param>
    ''' <param name="FlashDelay">
    ''' Indicates the rate at which the window is to be flashed, in milliseconds.
    ''' If dwTimeout is zero, the function uses the default cursor blink rate.
    ''' </param>
    ''' <returns>
    ''' The return value specifies the window's state before the call to the FlashWindowEx function.
    ''' If the window caption was drawn as active before the call, the return value is nonzero.
    ''' Otherwise, the return value is zero.
    ''' </returns>
    Public Shared Function Flash(ByVal [Handle] As IntPtr,
                                 ByVal FlashFlags As FlashFlags,
                                 Optional ByVal FlashCount As UInteger = UInteger.MaxValue,
                                 Optional ByVal FlashDelay As UInteger = 0UI) As Boolean

        Dim fInfo As New NativeMethods.FLASHWINFO()

        With fInfo

            .cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo))
            .hwnd = [Handle]
            .dwFlags = FlashFlags
            .uCount = FlashCount
            .dwTimeout = FlashDelay

        End With

        Return NativeMethods.FlashWindowEx(fInfo)

    End Function

#End Region

End Class








Eleкtro

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 (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 08-03-2014
' ***********************************************************************
' <copyright file="dnlibHelper.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

'Private Sub Test() Handles MyBase.Shown
'
'    Dim Assembly As ModuleDefMD =
'        dnlibHelper.LoadAssembly("C:\Application.exe")
'
'    Dim FrameworkVersion As String =
'        dnlibHelper.GetRuntimeVersion(Assembly)
'
'    Dim IsNativeCoded As Boolean =
'        dnlibHelper.AssemblyHasNativeCode(Assembly)
'
'    Dim Methods As List(Of MethodDef) =
'        dnlibHelper.GetMethods(Assembly, "Main") ' Searchs a Class named "Main"
'
'    For Each Method As MethodDef In Methods
'
'        ' If method contains instructions then...
'        If Method.HasBody Then
'
'            Dim sb As New System.Text.StringBuilder
'            With sb
'                .AppendLine(String.Format("Method Name: {0}", Method.Name))
'                .AppendLine()
'                .AppendLine(String.Format("Method Signature: {0}", Method.Signature.ToString))
'                .AppendLine()
'                .AppendLine(String.Format("Method Instructions: {0}", Environment.NewLine &
'                                          String.Join(Environment.NewLine, Method.Body.Instructions)))
'            End With
'
'            MessageBox.Show(sb.ToString)
'
'        End If ' method.HasBody
'
'    Next Method
'
'End Sub

#End Region

#Region " Imports "

Imports dnlib.DotNet
Imports dnlib.DotNet.Emit

#End Region

''' <summary>
''' Class dnlibHelper. This class cannot be inherited.
''' </summary>
Public NotInheritable Class dnlibHelper

   ''' <summary>
   ''' Loads an Assembly into a ModuleDefMD instance.
   ''' </summary>
   ''' <param name="Assembly">The assembly filepath.</param>
   ''' <returns>ModuleDefMD.</returns>
   Public Shared Function LoadAssembly(ByVal Assembly As String) As ModuleDefMD

       Return ModuleDefMD.Load(Assembly)

   End Function

   ''' <summary>
   ''' Determines whether a .Net Assembly has native code (C++/CLI).
   ''' </summary>
   ''' <param name="Assembly">The Assembly.</param>
   ''' <returns><c>true</c> if Assembly contains native code; otherwise, <c>false</c>.</returns>
   Public Shared Function AssemblyHasNativeCode(ByVal Assembly As ModuleDef) As Boolean

       If Assembly.IsILOnly Then
           ' This assembly has only IL code, and no native code (for example it's a C# or VB.NET assembly)
           Return True

       Else
           ' This assembly has native code (for example it's C++/CLI)
           Return False

       End If

   End Function

   ''' <summary>
   ''' Determines whether a .Net Assembly has native code (C++/CLI).
   ''' </summary>
   ''' <param name="Assembly">The Assembly filepath.</param>
   ''' <returns><c>true</c> if Assembly contains native code; otherwise, <c>false</c>.</returns>
   Public Shared Function AssemblyHasNativeCode(ByVal Assembly As String) As Boolean

       Using ass As ModuleDefMD = ModuleDefMD.Load(Assembly)

           Return AssemblyHasNativeCode(ass)

       End Using

   End Function

   ''' <summary>
   ''' Gets the .Net Framework runtime version of a .Net assembly.
   ''' </summary>
   ''' <param name="Assembly">The assembly.</param>
   ''' <returns>System.String.</returns>
   Public Shared Function GetRuntimeVersion(ByVal Assembly As ModuleDefMD) As String

       Return Assembly.RuntimeVersion

   End Function

   ''' <summary>
   ''' Gets the .Net Framework runtime version of a .Net assembly.
   ''' </summary>
   ''' <param name="Assembly">The assembly filepath.</param>
   ''' <returns>System.String.</returns>
   Public Shared Function GetRuntimeVersion(ByVal Assembly As String) As String

       Using ass As ModuleDefMD = ModuleDefMD.Load(Assembly)
           Return GetRuntimeVersion(ass)
       End Using

   End Function

   ''' <summary>
   ''' Gets all the Types defined (including nested Types) inside a .Net assembly.
   ''' </summary>
   ''' <param name="Assembly">The assembly.</param>
   ''' <returns>TypeDef().</returns>
   Public Shared Function GetTypes(ByVal Assembly As ModuleDefMD) As List(Of TypeDef)

       Return Assembly.GetTypes.ToList

   End Function

   ''' <summary>
   ''' Gets all the Methods defined in a existing Type inside a .Net assembly.
   ''' </summary>
   ''' <param name="Assembly">The assembly.</param>
   ''' <param name="TypeName">Name of the type to find.</param>
   ''' <returns>MethodDef().</returns>
   Public Shared Function GetMethods(ByVal Assembly As ModuleDefMD,
                                     ByVal TypeName As String) As List(Of MethodDef)

       Dim methods As List(Of MethodDef) = Nothing

       For Each t As TypeDef In Assembly.GetTypes

           If t.HasMethods AndAlso t.Name.String.Equals(TypeName, StringComparison.OrdinalIgnoreCase) Then
               methods = t.Methods.ToList
               Exit For
           End If

       Next t

       Return methods

   End Function

End Class








Eleкtro

Cita de: ivancea96 en  3 Agosto 2014, 17:33 PMYa van 30 páginas xD

Pues vamos a por las 300 :)

(triplicando mis espectativas xD)

Saludos!








Eleкtro

#405
Una Class para ayudar a implementar una lista MRU (MostRecentUsed)

( La parte gráfica sobre como implementar los items en un menú no la voy a explicar, al menos en esta publicación )





Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 08-04-2014
' ***********************************************************************
' <copyright file="MRU.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

'Public Class Form1
'
'    ' Initialize a new List of MostRecentUsed-Item
'    Dim MRUList As New List(Of MRU.Item)
'
'    Private Sub Test() Handles MyBase.Shown
'
'        ' Add some items into the collection.
'        With MRUList
'            .Add(New MRU.Item("C:\File1.ext"))
'            .Add(New MRU.Item("C:\File2.ext") With {.Date = Date.Today,
'                                                    .Icon = Bitmap.FromFile("C:\Image.ico"),
'                                                    .Tag = Nothing})
'        End With
'
'        ' Save the MRUItem collection to local file.
'        MRU.IO.Save(MRUList, ".\MRU.tmp")
'
'        ' Load the saved collection from local file.
'        For Each MRUItem As MRU.Item In MRU.IO.Load(Of List(Of MRU.Item))(".\MRU.tmp")
'            MessageBox.Show(MRUItem.FilePath)
'        Next MRUItem
'
'        ' Just another way to load the collection:
'        MRU.IO.Load(MRUList, ".\MRU.tmp")
'
'    End Sub
'
'End Class

#End Region

#Region " MostRecentUsed "

''' <summary>
''' Class MRU (MostRecentUsed).
''' Administrates the usage of a MRU item collection.
''' </summary>
Public Class MRU

#Region " Constructors "

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

#End Region

#Region " Types "

#Region "IO"

   ''' <summary>
   ''' Performs IO operations with a <see cref="MRU.Item"/> Collection.
   ''' </summary>
   Public Class [IO]

#Region " Constructors "

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

#End Region

#Region " Public Methods "

       ''' <summary>
       ''' Saves the specified MRU List to local file, using binary serialization.
       ''' </summary>
       ''' <typeparam name="T"></typeparam>
       ''' <param name="MRUItemCollection">The <see cref="MRU.Item"/> Collection.</param>
       ''' <param name="filepath">The filepath to save the <see cref="MRU.Item"/> Collection.</param>
       Public Shared Sub Save(Of T)(ByVal MRUItemCollection As T,
                                    ByVal filepath As String)

           Dim Serializer = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

           ' Serialization.
           Using Writer As New System.IO.FileStream(filepath, System.IO.FileMode.Create)
               Serializer.Serialize(Writer, MRUItemCollection)
           End Using ' Writer

       End Sub

       ''' <summary>
       ''' Loads the specified <see cref="MRU.Item"/> Collection from a local file, using binary deserialization.
       ''' </summary>
       ''' <typeparam name="T"></typeparam>
       ''' <param name="MRUItemCollection">The ByRefered <see cref="MRU.Item"/> collection.</param>
       ''' <param name="filepath">The filepath to load its <see cref="MRU.Item"/> Collection.</param>
       Public Shared Sub Load(Of T)(ByRef MRUItemCollection As T,
                                    ByVal filepath As String)

           Dim Serializer = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

           ' Deserialization.
           Using Reader As New System.IO.FileStream(filepath, System.IO.FileMode.Open)

               MRUItemCollection = Serializer.Deserialize(Reader)

           End Using ' Reader

       End Sub

       ''' <summary>
       ''' Loads the specified <see cref="MRU.Item"/> Collection from a local file, using the specified deserialization.
       ''' </summary>
       ''' <typeparam name="T"></typeparam>
       ''' <param name="filepath">The filepath to load its <see cref="MRU.Item"/> Collection.</param>
       Public Shared Function Load(Of T)(ByVal filepath As String) As T

           Dim Serializer = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

           ' Deserialization.
           Using Reader As New System.IO.FileStream(filepath, System.IO.FileMode.Open)

               Return Serializer.Deserialize(Reader)

           End Using ' Reader

       End Function

#End Region

   End Class

#End Region

#Region " Item "

   ''' <summary>
   ''' An Item for a MostRecentUsed-Item collection that stores the item filepath and optionally additional info.
   ''' This Class can be serialized.
   ''' </summary>
   <Serializable()>
   Public Class Item

#Region " Constructors "

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

       ''' <summary>
       ''' Initializes a new instance of the <see cref="MRU.Item"/> class.
       ''' </summary>
       ''' <param name="FilePath">The item filepath.</param>
       ''' <exception cref="System.ArgumentNullException">FilePath</exception>
       Public Sub New(ByVal FilePath As String)

           If FilePath Is Nothing Then
               Throw New ArgumentNullException("FilePath")
           End If

           Me._FilePath = FilePath

       End Sub

       ''' <summary>
       ''' Initializes a new instance of the <see cref="MRU.Item"/> class.
       ''' </summary>
       ''' <param name="File">The fileinfo object.</param>
       Public Sub New(ByVal File As System.IO.FileInfo)

           Me.New(File.FullName)

       End Sub

#End Region

#Region " Properties "

       ''' <summary>
       ''' Gets the item filepath.
       ''' </summary>
       ''' <value>The file path.</value>
       Public ReadOnly Property FilePath As String
           Get
               Return Me._FilePath
           End Get
       End Property
       Private _FilePath As String = String.Empty

       ''' <summary>
       ''' Gets the FileInfo object of the item.
       ''' </summary>
       ''' <value>The FileInfo object.</value>
       Public ReadOnly Property FileInfo As System.IO.FileInfo
           Get
               Return New System.IO.FileInfo(FilePath)
           End Get
       End Property

       ''' <summary>
       ''' (Optionally) Gets or sets the item last-time open date.
       ''' </summary>
       ''' <value>The index.</value>
       Public Property [Date] As Date

       ''' <summary>
       ''' (Optionally) Gets or sets the item icon.
       ''' </summary>
       ''' <value>The icon.</value>
       Public Property Icon As Bitmap

       ''' <summary>
       ''' (Optionally) Gets or sets the item tag.
       ''' </summary>
       ''' <value>The tag object.</value>
       Public Property Tag As Object

#End Region

   End Class

#End Region

#End Region

End Class

#End Region








Eleкtro

Ejemplos de uso de la librería nDDE para controlar un navegador compatible (aunque la verdad, DDE es muy limitado ...por no decir obsoleto, es preferible echar mano de UI Automation).

Nota: Aquí teneis algunos ServiceNames y Topics de DDE para IExplore por si alguien está interesado en esta librería: support.microsoft.com/kb/160957
       He probado el tópico "WWW_Exit" por curiosidad y funciona, pero ninguno de ellos funciona en Firefox (solo los que añadi a la Class de abajo).

Código (vbnet) [Seleccionar]
   ' nDDE Helper
   ' By Elektro
   '
   ' Instructions:
   ' 1. Add a reference to 'NDDE.dll' library.
   '
   ' Usage Examples:
   ' MessageBox.Show(GetFirefoxUrl())
   ' NavigateFirefox(New Uri("http://www.mozilla.org"), OpenInNewwindow:=False)

   ''' <summary>
   ''' Gets the url of the active Tab-page from a running Firefox process.
   ''' </summary>
   ''' <returns>The url of the active Tab-page.</returns>
   Public Function GetFirefoxUrl() As String

       Using dde As New DdeClient("Firefox", "WWW_GetWindowInfo")

           dde.Connect()

           Dim Url As String =
               dde.Request("URL", Integer.MaxValue).
                   Trim({ControlChars.NullChar, ControlChars.Quote, ","c})


           dde.Disconnect()

           Return Url

       End Using

   End Function

   ''' <summary>
   ''' Navigates to an URL in the running Firefox process.
   ''' </summary>
   ''' <param name="url">Indicates the URL to navigate.</param>
   ''' <param name="OpenInNewwindow">
   ''' If set to <c>true</c> the url opens in a new Firefox window, otherwise, the url opens in a new Tab.
   ''' </param>
   Public Sub NavigateFirefox(ByVal url As Uri,
                              ByVal OpenInNewwindow As Boolean)

       Dim Address As String = url.AbsoluteUri

       If OpenInNewwindow Then
           Address &= ",,0"
       End If

       Using dde As New DdeClient("Firefox", "WWW_OpenURL")

           dde.Connect()
           dde.Request(Address, Integer.MaxValue)
           dde.Disconnect()

       End Using

   End Sub









z3nth10n

#407
Muy buenas, después de estar bastante tiempo sin subir nada aquí tengo una cosita interesante :P

Creo que algunas de estas utilidades están ya presentes dentro de lo que es la super colección de Elektro, pero bueno supongo que un indentador XML nunca se ha visto por aquí así que aquí va:

Código (VBNET) [Seleccionar]
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization

Public Class XMLTools

   Public Shared Function Serialize(Of T)(value As T, Optional ByVal indented As Boolean = False) As String
       If value Is Nothing Then
           Throw New Exception("XMLSerializer - The value passed is null!")
           Return ""
       End If
       Try

           Dim xmlserializer As New XmlSerializer(GetType(T))
           Dim serializeXml As String = ""

           Using stringWriter As New StringWriter()

               Using writer As XmlWriter = XmlWriter.Create(stringWriter)
                   xmlserializer.Serialize(writer, value)
                   serializeXml = stringWriter.ToString()
               End Using

               If indented Then
                   serializeXml = Beautify(serializeXml)
               End If

           End Using

           Return serializeXml
       Catch ex As Exception
           Throw New Exception(ex.Message)
           Return ""
       End Try
   End Function

   Public Shared Function Deserialize(Of T)(value As String) As T

       Try
           Dim returnvalue As New Object()
           Dim xmlserializer As New XmlSerializer(GetType(T))
           Dim reader As TextReader = New StringReader(value)

           returnvalue = xmlserializer.Deserialize(reader)

           reader.Close()
           Return DirectCast(returnvalue, T)
       Catch ex As Exception
           Throw New Exception(ex.Message)
           Return Nothing
       End Try

   End Function

   Public Shared Sub SerializeToFile(Of T)(value As T, filePath As String, Optional ByVal indented As Boolean = False)
       If value Is Nothing Then
           Throw New Exception("XMLSerializer - The value passed is null!")
       End If
       Try
           Dim xmlserializer As New XmlSerializer(GetType(T))
           Using fileWriter As StreamWriter = New StreamWriter(filePath)
               If indented Then
                   Using stringWriter As New StringWriter()
                       Using writer As XmlWriter = XmlWriter.Create(stringWriter)
                           xmlserializer.Serialize(writer, value)
                           fileWriter.WriteLine(Beautify(stringWriter.ToString()))
                       End Using
                   End Using
               Else
                   Using writer As XmlWriter = XmlWriter.Create(fileWriter)
                       xmlserializer.Serialize(writer, value)
                   End Using
               End If
           End Using

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

   Public Shared Function DeserializeFromFile(Of T)(filePath As String) As T

       Try
           Dim returnvalue As New Object()
           Dim xmlserializer As New XmlSerializer(GetType(T))
           Using reader As TextReader = New StreamReader(filePath)
               returnvalue = xmlserializer.Deserialize(reader)
           End Using
           Return DirectCast(returnvalue, T)
       Catch ex As Exception
           Throw New Exception(ex.Message)
           Return Nothing
       End Try

   End Function

   Public Shared Function Beautify(obj As Object) As String
       Dim doc As New XmlDocument()
       If obj.[GetType]() Is GetType(String) Then
           If Not [String].IsNullOrEmpty(DirectCast(obj, String)) Then
               Try
                   doc.LoadXml(DirectCast(obj, String))
               Catch ex As Exception
                   Throw New Exception("XMLIndenter - Wrong string format! [" + ex.Message & "]")
                   Return ""
               End Try
           Else
               Throw New Exception("XMLIndenter - String is null!")
               Return ""
           End If
       ElseIf obj.[GetType]() Is GetType(XmlDocument) Then
           doc = DirectCast(obj, XmlDocument)
       Else
           Throw New Exception("XMLIndenter - Not supported type!")
           Return ""
       End If
       Dim returnValue As String = ""
       Using w As New MemoryStream()
           Using writer As New XmlTextWriter(w, Encoding.Unicode)
               writer.Formatting = Formatting.Indented
               doc.WriteContentTo(writer)

               writer.Flush()
               w.Seek(0L, SeekOrigin.Begin)

               Using reader As New StreamReader(w)
                   returnValue = reader.ReadToEnd()
               End Using
           End Using
       End Using
   End Function

End Class


Un saludo.

Interesados hablad por Discord.

Eleкtro

#408
Cita de: Ikillnukes en  8 Agosto 2014, 17:11 PM
Creo que algunas de estas utilidades están ya presentes dentro de lo que es la super colección de Elektro, pero bueno supongo que un indentador XML nunca se ha visto por aquí así que aquí va:

precisamente estoy harto de que cierta utilidad de Microsoft me genere los archivos de manifiesto sin ningún tipo de indentación, esto me sirve ;).

EDITO: en un principio iba a ahorrarme comentarios sobre posibles mejoras de código o etc, pero hay un fallo importante que se debe corregir, no estás liberando el memorystream:
Citar
Código (vbnet) [Seleccionar]
Dim w As New MemoryStream()

Ni tampoco el Writer ni el Reader xD

Por cierto la Class XMLTextWriter está obsoleta, en su defecto Microsoft recomienda el uso de XMLWriter.

EDITO 2: Me he tomado la libertad de editar el código original enfocándolo de otra manera (aunque tampoco es tan distinto):

Ejemplo de uso:

Código (vbnet) [Seleccionar]
       Dim TextEncoding As System.Text.Encoding = System.Text.Encoding.Default
       Dim UnformattedXMLDocument As String = IO.File.ReadAllText("C:\Unformatted Document.xml", TextEncoding)
       Dim FormattedXMLDocument As String = XMLBeautify(XMLText:=UnformattedXMLDocument,
                                                        IndentChars:=New String(" "c, 2),
                                                        IndentOnAttributes:=False,
                                                        TextEncoding:=TextEncoding)

       IO.File.WriteAllText("C:\Formatted Document.xml", FormattedXMLDocument, TextEncoding)



Snippet:

Código (vbnet) [Seleccionar]
   ''' <summary>
   ''' Beautifies the contents of an unindented XML document.
   ''' </summary>
   ''' <param name="XMLText">
   ''' The XML text content.
   ''' It can be an entire document or a fragment.
   ''' </param>
   ''' <param name="IndentChars">
   ''' The string that is used to indent the XML.
   ''' Default value is: <see cref="ControlChars.Tab"/>
   ''' </param>
   ''' <param name="IndentOnAttributes">
   ''' If set to <c>true</c>, attributes will be separated by newlines.
   ''' Default value is: <c>false</c>
   ''' </param>
   ''' <param name="TextEncoding">
   ''' The XML text encoding to use.
   ''' Default value is: <see cref="System.Text.Encoding.Default"/>.
   ''' </param>
   ''' <returns>The beautified XML text.</returns>
   ''' <exception cref="System.ArgumentNullException"></exception>
   Public Shared Function XMLBeautify(ByVal XMLText As String,
                                      Optional ByVal IndentChars As String = Nothing,
                                      Optional ByVal IndentOnAttributes As Boolean = False,
                                      Optional ByVal TextEncoding As System.Text.Encoding = Nothing) As String

       If String.IsNullOrEmpty(XMLText) Then
           Throw New ArgumentNullException(XMLText)
       End If

       Dim sb As New System.Text.StringBuilder
       Dim doc As New Xml.XmlDocument()
       Dim settings As New Xml.XmlWriterSettings

       With settings
           .Indent = True
           .CheckCharacters = True
           .OmitXmlDeclaration = False
           .ConformanceLevel = Xml.ConformanceLevel.Auto
           .NamespaceHandling = Xml.NamespaceHandling.Default
           .NewLineHandling = Xml.NewLineHandling.Replace
           .NewLineChars = ControlChars.NewLine
           .NewLineOnAttributes = IndentOnAttributes
           .IndentChars = If(IndentChars IsNot Nothing, IndentChars, ControlChars.Tab)
           .Encoding = If(TextEncoding IsNot Nothing, TextEncoding, System.Text.Encoding.Default)
       End With

       Using writer As Xml.XmlWriter = Xml.XmlWriter.Create(sb, settings)
           doc.LoadXml(XMLText)
           doc.WriteContentTo(writer)
           writer.Flush()
           Return sb.ToString
       End Using

   End Function

   ''' <summary>
   ''' Beautifies the contents of an unindented XML document.
   ''' </summary>
   ''' <param name="XMLFile">
   ''' An <see cref="T:IO.FileInfo"/> that contains the XML info.
   ''' It can be an entire document or a fragment.
   ''' </param>
   ''' <param name="IndentChars">
   ''' The string that is used to indent the XML.
   ''' Default value is: <see cref="ControlChars.Tab"/>
   ''' </param>
   ''' <param name="IndentOnAttributes">
   ''' If set to <c>true</c>, attributes will be separated by newlines.
   ''' Default value is: <c>false</c>
   ''' </param>
   ''' <param name="TextEncoding">
   ''' The XML text encoding to use.
   ''' Default value is: <see cref="System.Text.Encoding.Default"/>.
   ''' </param>
   ''' <returns>The beautified XML text.</returns>
   ''' <exception cref="System.ArgumentNullException"></exception>
   Public Shared Function XMLBeautify(XMLFile As IO.FileInfo,
                                      Optional ByVal IndentChars As String = Nothing,
                                      Optional ByVal IndentOnAttributes As Boolean = False,
                                      Optional ByVal TextEncoding As System.Text.Encoding = Nothing) As String

        Return XMLBeautify(IO.File.ReadAllText(XMLFile.FullName, TextEncoding), IndentChars, IndentOnAttributes, TextEncoding)

   End Function




Posibles outputs:

1º:

Código (xml) [Seleccionar]
<savedata>
 <SoftwareType>Freeware</SoftwareType>
 <SoftwareID>Moo0 FileMonitor</SoftwareID>
 <Version>1.11</Version>
 <MainWindow>
   <SoftwareType>Freeware</SoftwareType>
   <SoftwareID>Moo0 FileMonitor</SoftwareID>
   <Version>1.11</Version>
   <View F="0" E="0" D="0" RefreshFrequency="500" LogUpTo="20000" EasyDrag="1" Maximized="0" X="958" Y="453" Width="962" Height="585" KeepOnTop="0"></View>
   <ChangesColumnOrder length="6" _0="0" _1="1" _2="2" _3="3" _4="4" _5="5"></ChangesColumnOrder>
 </MainWindow>
 <Skin>Classic LG</Skin>
</savedata>



2º:
Código (xml) [Seleccionar]
<savedata>
 <SoftwareType>Freeware</SoftwareType>
 <SoftwareID>Moo0 FileMonitor</SoftwareID>
 <Version>1.11</Version>
 <MainWindow>
   <SoftwareType>Freeware</SoftwareType>
   <SoftwareID>Moo0 FileMonitor</SoftwareID>
   <Version>1.11</Version>
   <View
     F="0"
     E="0"
     D="0"
     RefreshFrequency="500"
     LogUpTo="20000"
     EasyDrag="1"
     Maximized="0"
     X="958"
     Y="453"
     Width="962"
     Height="585"
     KeepOnTop="0"></View>
   <ChangesColumnOrder
     length="6"
     _0="0"
     _1="1"
     _2="2"
     _3="3"
     _4="4"
     _5="5"></ChangesColumnOrder>
 </MainWindow>
 <Skin>Classic LG</Skin>
</savedata>


Saludos








Eleкtro

#409
Ejemplo de como implementar la interface ISerializable e IXMLSerializable:

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

Imports System.Runtime.Serialization
Imports System.Security.Permissions
Imports System.Xml.Serialization
Imports System.Xml

#End Region

''' <summary>
''' SerializableClassTest.
''' This class can be serialized.
''' </summary>
<Serializable>
<XmlRoot("SerializableClassTest")>
Public Class SerializableClassTest : Implements ISerializable : Implements IXmlSerializable

#Region "Properties"

   Public Property StrValue As String
   Public Property Int32Value As Integer

#End Region

#Region "Constructors"

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

   ''' <summary>
   ''' Initializes a new instance of the <see cref="SerializableClassTest"/> class.
   ''' </summary>
   Public Sub New(ByVal StrValue As String,
                  ByVal Int32Value As Integer)

       Me.StrValue = StrValue
       Me.Int32Value = Int32Value

   End Sub

#End Region

#Region "ISerializable implementation" ' For Binary serialization.

   ''' <summary>
   ''' Populates a <see cref="T:SerializationInfo"/> with the data needed to serialize the target object.
   ''' </summary>
   ''' <param name="info">The <see cref="T:SerializationInfo"/> to populate with data.</param>
   ''' <param name="context">The destination (see <see cref="T:StreamingContext"/>) for this serialization.</param>
   <SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.SerializationFormatter)>
   Protected Overridable Sub GetObjectData(ByVal info As SerializationInfo,
                                           ByVal context As StreamingContext) Implements ISerializable.GetObjectData

       If info Is Nothing Then
           Throw New ArgumentNullException("info")
       End If

       With info

           .AddValue("PropertyName1", Me.StrValue, Me.StrValue.GetType)
           .AddValue("PropertyName2", Me.Int32Value, Me.Int32Value.GetType)

       End With

   End Sub

   ''' <summary>
   ''' Initializes a new instance of the <see cref="SerializableClassTest"/> class.
   ''' This constructor is used to deserialize values.
   ''' </summary>
   ''' <param name="info">The information.</param>
   ''' <param name="context">The context.</param>
   Protected Sub New(ByVal info As SerializationInfo,
                     ByVal context As StreamingContext)

       If info Is Nothing Then
           Throw New ArgumentNullException("info")
       End If

       Me.StrValue = info.GetString("PropertyName1")
       Me.Int32Value = info.GetInt32("PropertyName2")

   End Sub

#End Region

#Region "IXMLSerializable implementation" ' For XML serialization.

   ''' <summary>
   ''' This method is reserved and should not be used.
   ''' When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method,
   ''' and instead, if specifying a custom schema is required, apply the <see cref="T:XmlSchemaProviderAttribute"/> to the class.
   ''' </summary>
   ''' <returns>
   ''' An <see cref="T:Xml.Schema.XmlSchema"/> that describes the XML representation of the object
   ''' that is produced by the <see cref="M:IXmlSerializable.WriteXml(Xml.XmlWriter)"/> method
   ''' and consumed by the <see cref="M:IXmlSerializable.ReadXml(Xml.XmlReader)"/> method.
   ''' </returns>
   Public Function GetSchema() As Schema.XmlSchema Implements IXmlSerializable.GetSchema

       Return Nothing

   End Function

   ''' <summary>
   ''' Converts an object into its XML representation.
   ''' </summary>
   ''' <param name="writer">The <see cref="T:Xml.XmlWriter"/> stream to which the object is serialized.</param>
   Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml

       writer.WriteElementString("PropertyName1", Me.StrValue)
       writer.WriteElementString("PropertyName2", CStr(Me.Int32Value))

   End Sub

   ''' <summary>
   ''' Generates an object from its XML representation.
   ''' </summary>
   ''' <param name="reader">The <see cref="T:Xml.XmlReader"/> stream from which the object is deserialized.</param>
   Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml

       With reader

           .ReadStartElement(MyBase.GetType.Name)

           Me.StrValue = .ReadElementContentAsString
           Me.Int32Value = .ReadElementContentAsInt

       End With

   End Sub

#End Region

End Class





Ejemplo de como usar la Class DeviceWatcher en un WinForms, sirve para detectar los eventos de inserción/extracción de los dispositivos, quizás se pueda utilizar como reemplazamiento del típico código de WMI para monitorizar USB's, pero todavía no le he podido sacar todo el jugo al asunto, poca documentación...

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


' 1. Create a new WinForms project targeting .NET Framework 4.5.


' 2. Close VisualStudio, open the 'YourProjectName.vbproj' file in a text-editor and add this property:
' *****************************************************************************************************
'<PropertyGroup>
'    ...
'    <TargetPlatformVersion>8.0</TargetPlatformVersion>
'    ...
'</PropertyGroup>


' 3. Load the project in VisualStudio, open the 'References' menu and add these references:
' *****************************************************************************************
' C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.dll
' C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.InteropServices.WindowsRuntime.dll


' 4. In the 'References' menu, go to 'Windows > Core' tab and add these references:
' *********************************************************************************
' Windows.Devices
' Windows.Foundation


#End Region

#Region " Imports "

Imports Windows.Devices.Enumeration
Imports Windows.Foundation

#End Region

Public Class DeviceWatcher_Test

   Friend WithEvents dw As DeviceWatcher = DeviceInformation.CreateWatcher

   Private Sub Test() Handles MyBase.Load

       dw.Start()

   End Sub

   ''' <summary>
   ''' Event that is raised when a device is added to the collection enumerated by the DeviceWatcher.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.added.aspx
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="DeviceInformation"/> instance containing the event data.</param>
   Private Sub dw_Added(ByVal sender As DeviceWatcher, ByVal e As DeviceInformation) _
   Handles dw.Added

       Dim sb As New System.Text.StringBuilder

       With sb
           .AppendLine("dw_added")
           .AppendLine("********")
           .AppendLine(String.Format("Interface ID.: {0}", e.Id))
           .AppendLine(String.Format("Friendly Name: {0}", e.Name))
           .AppendLine(String.Format("Is Enabled?..: {0}", e.IsEnabled))

           If e.Properties IsNot Nothing Then

               For Each item As KeyValuePair(Of String, Object) In e.Properties

                   If item.Value IsNot Nothing Then

                       .AppendLine(String.Format("TKey:{0}, TVal:{1} (TVal Type:{2})",
                                                 item.Key, item.Value.ToString, item.Value.GetType.Name))

                   End If

               Next

           End If

       End With

       Debug.WriteLine(sb.ToString)

   End Sub

   ''' <summary>
   ''' Event that is raised when a device is removed from the collection of enumerated devices.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.removed.aspx
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="DeviceInformationUpdate"/> instance containing the event data.</param>
   Private Sub dw_Removed(ByVal sender As DeviceWatcher, ByVal e As DeviceInformationUpdate) _
   Handles dw.Removed

       Dim sb As New System.Text.StringBuilder

       With sb
           .AppendLine("dw_Removed")
           .AppendLine("**********")
           .AppendLine(String.Format("Interface ID:{0}", e.Id))

           For Each item As KeyValuePair(Of String, Object) In e.Properties
               .AppendLine(String.Format("TKey:{0}, TVal:{1} (TVal Type:{2})",
                                         item.Key, item.Value.ToString, item.Value.GetType.Name))
           Next

       End With

       Debug.WriteLine(sb.ToString)

   End Sub

   ''' <summary>
   ''' Event that is raised when a device is updated in the collection of enumerated devices.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.updated.aspx
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="DeviceInformationUpdate"/> instance containing the event data.</param>
   Private Sub dw_Updated(ByVal sender As DeviceWatcher, ByVal e As DeviceInformationUpdate) _
   Handles dw.Updated

       Dim sb As New System.Text.StringBuilder

       With sb
           .AppendLine("dw_Updated")
           .AppendLine("**********")
           .AppendLine(String.Format("Interface ID: {0}", e.Id))

           For Each item As KeyValuePair(Of String, Object) In e.Properties

               If item.Key.EndsWith("InterfaceEnabled", StringComparison.OrdinalIgnoreCase) Then
                   Dim Result As Boolean = CBool(item.Value)
                   .AppendLine(String.Format("The device is accessible?:{0}", CStr(Result)))

               Else
                   .AppendLine(String.Format("TKwy:{0}, TVal:{1} (TVal Type:{2})",
                                             item.Key, item.Value.ToString, item.Value.GetType.Name))

               End If

           Next

       End With

       Debug.WriteLine(sb.ToString)

   End Sub

   ''' <summary>
   ''' Event that is raised when the enumeration operation has been stopped.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.stopped.aspx
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The object containing the event data.</param>
   Private Sub dw_Stopped(ByVal sender As DeviceWatcher, ByVal e As Object) _
   Handles dw.Stopped

       Dim sb As New System.Text.StringBuilder

       With sb
           .AppendLine("dw_Stopped")
           .AppendLine("**********")
           .AppendLine(String.Format("e:{1} (e Type:{2})",
                                     e.ToString, e.GetType.Name))

       End With

       Debug.WriteLine(sb.ToString)

   End Sub

   ''' <summary>
   ''' Event that is raised when the enumeration of devices completes.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.enumerationcompleted.aspx
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The object containing the event data.</param>
   Private Sub dw_EnumerationCompleted(ByVal sender As DeviceWatcher, ByVal e As Object) _
   Handles dw.EnumerationCompleted

       If e IsNot Nothing Then

           Dim sb As New System.Text.StringBuilder

           With sb
               .AppendLine("EnumerationCompleted")
               .AppendLine("********************")
               .AppendLine(String.Format("e:{1} (e Type:{2})",
                                         e.ToString, e.GetType.Name))

           End With

           Debug.WriteLine(sb.ToString)

       End If

   End Sub

End Class