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

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

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

Eleкtro

#370
Unos métodos de uso genérico para cifrar y descifrar archivos (reálmente el manejo es muy simple xD) usando la librería de pago ReBex ~> http://www.rebex.net/total-pack/default.aspx

Código (vbnet) [Seleccionar]
' [Rebex.Security] Encrypt-Decrypt File
' ( By Elektro )
'
' Instructions:
' 1. Add a reference to "Rebex.Security.dll"
'
' Usage Examples:
' EncryptFile("File.txt", "Encrypted.txt", "Elektro", FileEncryptionAlgorithm.AesXts, False)
' DecryptFile("Encrypted.txt", "Decrypted.txt", "Elektro", FileEncryptionAlgorithm.AesXts, False)

    ''' <summary>
    ''' Encrypts the data of the specified file.
    ''' </summary>
    ''' <param name="InFile">
    ''' Indicates the file to encrypt.
    ''' </param>
    ''' <param name="OutFile">
    ''' Indicates the resulting encrypted output file.
    ''' </param>
    ''' <param name="Password">
    ''' Indicates the password required to decrypt the file when needed.
    ''' </param>
    ''' <param name="Algorithm">
    ''' Indicates the encryption algorithm.
    ''' </param>
    ''' <param name="OverwriteExistingFile">
    ''' If set to <c>true</c> the resulting output file should overwrite any existing file.
    ''' </param>
    ''' <exception cref="System.Security.Cryptography.CryptographicException">
    ''' Unexpected error, the data to encrypt could be corrupted.
    ''' </exception>
    ''' <exception cref="System.InvalidOperationException"></exception>
    Private Sub EncryptFile(ByVal InFile As String,
                            ByVal OutFile As String,
                            ByVal Password As String,
                            Optional ByVal Algorithm As Rebex.Security.FileEncryptionAlgorithm =
                                                                       FileEncryptionAlgorithm.AesXts,
                            Optional ByVal OverwriteExistingFile As Boolean = False)

        Dim Encryptor As New FileEncryption()

        With Encryptor

            .SetPassword(Password)
            .EncryptionAlgorithm = Algorithm
            .OverwriteExistingFile = OverwriteExistingFile

        End With

        Try
            Encryptor.Encrypt(InFile, OutFile)

        Catch ex As Security.Cryptography.CryptographicException
            Throw New Security.Cryptography.CryptographicException(
                "Unexpected error, the data to encrypt could be corrupted.")

        Catch ex As InvalidOperationException
            Throw New InvalidOperationException(
               String.Format("The target file '{0}' already exist.", OutFile))

        End Try

    End Sub

    ''' <summary>
    ''' Decrypts the data of the specified file.
    ''' </summary>
    ''' <param name="InFile">
    ''' Indicates the file to decrypt.
    ''' </param>
    ''' <param name="OutFile">
    ''' Indicates the resulting decrypted output file.
    ''' </param>
    ''' <param name="Password">
    ''' Indicates the password to decrypt the File.
    ''' The password should be the same used when encrypted the file.
    ''' </param>
    ''' <param name="Algorithm">
    ''' Indicates the decryption algorithm.
    ''' The algorithm should be the same used when encrypted the file.
    ''' </param>
    ''' <param name="OverwriteExistingFile">
    ''' If set to <c>true</c> the resulting output file should overwrite any existing file.
    ''' </param>
    ''' <exception cref="System.Security.Cryptography.CryptographicException">
    ''' The password, the data to decrypt, or the decryption algorithm are wrong.
    ''' </exception>
    ''' <exception cref="System.InvalidOperationException"></exception>
    Private Sub DecryptFile(ByVal InFile As String,
                            ByVal OutFile As String,
                            ByVal Password As String,
                            Optional ByVal Algorithm As Rebex.Security.FileEncryptionAlgorithm =
                                                                       FileEncryptionAlgorithm.AesXts,
                            Optional ByVal OverwriteExistingFile As Boolean = False)


        Dim Decryptor As New FileEncryption()

        With Decryptor

            .SetPassword(Password)
            .EncryptionAlgorithm = Algorithm
            .OverwriteExistingFile = OverwriteExistingFile

        End With

        Try
            Decryptor.Decrypt(InFile, OutFile)

        Catch ex As Security.Cryptography.CryptographicException
            Throw New Security.Cryptography.CryptographicException(
                "The password, the data to decrypt, or the decryption algorithm are wrong.")

        Catch ex As InvalidOperationException
            Throw New InvalidOperationException(
               String.Format("The target file '{0}' already exist.", OutFile))

        End Try

    End Sub








Eleкtro

#371
Me puse a jugar con el efecto de Pixelado de la librería de pago ImageDraw ~> http://www.neodynamic.com/products/image-draw/sdk-vb-net-csharp/ ...y al final acabé escribiendo un ayudante de casi 2.000 lineas.

Aquí pueden ver el código completo ~> http://pastebin.com/Ha8tG3cA

Le añadí métodos de uso genérico para realizar las siguientes acciones (no están todos los efectos):

' -------
' Methods
' -------
'
' Properties.Brightness
' Properties.Contrast
' Properties.Gamma
' Properties.HSL
' Properties.Hue
' Properties.Opacity
'
' Effects.CameraView
' Effects.ColorSubstitution
' Effects.ConvertToBlackWhite
' Effects.ConvertToNegative
' Effects.ConvertToSepia
' Effects.Crop
' Effects.DistortCorners
' Effects.DropShadow
' Effects.Fade
' Effects.Feather
' Effects.Filmstrip
' Effects.Flip
' Effects.FocalGrayscale
' Effects.GaussianBlur
' Effects.GlassTable
' Effects.Glow
' Effects.MakeTransparent
' Effects.PerspectiveReflection
' Effects.PerspectiveView
' Effects.Pixelate
' Effects.RemoveColor
' Effects.RemoveTransparency
' Effects.Resize
' Effects.Rotate
' Effects.RoundCorners
' Effects.Scale
' Effects.Sharpen
' Effects.Silhouette
' Effects.Skew
' Effects.Solarize
' Effects.Stretch
' Effects.Tint

Ejemplos de uso:
Código (vbnet) [Seleccionar]
       Dim [ImageElement] As ImageElement = ImageElement.FromFile("C:\Image.png")
       Dim [TextElement] As New TextElement With {.Text = "Hello World!"}

       ImageDrawHelper.Properties.Brightness([ImageElement], 50)
       ImageDrawHelper.Properties.Contrast([ImageElement], 50)
       ImageDrawHelper.Properties.Gamma([ImageElement], 50)
       ImageDrawHelper.Properties.HSL([ImageElement], 50, 50, 50)
       ImageDrawHelper.Properties.Hue([ImageElement], 50)
       ImageDrawHelper.Properties.Opacity([ImageElement], 50)

       ImageDrawHelper.Effects.CameraView([ImageElement], 30, 25)
       ImageDrawHelper.Effects.ColorSubstitution([ImageElement], Color.Black, Color.Fuchsia, 10)
       ImageDrawHelper.Effects.ConvertToBlackWhite([ImageElement], DitherMethod.Threshold, 53, False)
       ImageDrawHelper.Effects.ConvertToNegative([ImageElement])
       ImageDrawHelper.Effects.ConvertToSepia([ImageElement])
       ImageDrawHelper.Effects.Crop([ImageElement], 0, 10, 200, 160)
       ImageDrawHelper.Effects.DistortCorners([ImageElement], -20, -20, 200, 0, 250, 180, -30, 200)
       ImageDrawHelper.Effects.DropShadow([ImageElement], 60, Color.Lime, 270, 6, 10)
       ImageDrawHelper.Effects.Fade([ImageElement], FadeShape.Oval, FillType.Gradient, GradientShape.Path)
       ImageDrawHelper.Effects.Feather([ImageElement], 5, FeatherShape.Oval)
       ImageDrawHelper.Effects.Filmstrip([ImageElement], FilmstripOrientation.Vertical, 150, 180, 0, Color.Yellow, 5)
       ImageDrawHelper.Effects.Flip([ImageElement], FlipType.Horizontal)
       ImageDrawHelper.Effects.FocalGrayscale([ImageElement], FocalShape.Oval, FillType.Gradient, GradientShape.Path, Color.FromArgb(0, 255, 255, 255), Color.FromArgb(0, 0, 0))
       ImageDrawHelper.Effects.GaussianBlur([ImageElement], 5)
       ImageDrawHelper.Effects.GlassTable([ImageElement], 50, 25)
       ImageDrawHelper.Effects.GlassTable([ImageElement], 50, 25, ReflectionLocation.Custom, 2, 10)
       ImageDrawHelper.Effects.Glow([ImageElement], Color.Red, 80, 8)
       ImageDrawHelper.Effects.MakeTransparent([ImageElement])
       ImageDrawHelper.Effects.PerspectiveReflection([ImageElement], 270, 50, 50, 150, 0)
       ImageDrawHelper.Effects.PerspectiveView([ImageElement], 25, PerspectiveOrientation.LeftToRight)
       ImageDrawHelper.Effects.Pixelate([ImageElement], 20, 0)
       ImageDrawHelper.Effects.RemoveColor([ImageElement], Color.White, 10, ScanDirection.All)
       ImageDrawHelper.Effects.RemoveTransparency([ImageElement])
       ImageDrawHelper.Effects.Resize([ImageElement], 256, 256, LockAspectRatio.WidthBased, Drawing2D.InterpolationMode.Bicubic)
       ImageDrawHelper.Effects.Rotate([ImageElement], 90, Drawing2D.InterpolationMode.Bicubic)
       ImageDrawHelper.Effects.RoundCorners([ImageElement], Corners.All, 120)
       ImageDrawHelper.Effects.RoundCorners([ImageElement], Corners.All, 20, 10, Color.Red)
       ImageDrawHelper.Effects.Scale([ImageElement], 50, 50, Drawing2D.InterpolationMode.Bicubic)
       ImageDrawHelper.Effects.Sharpen([ImageElement])
       ImageDrawHelper.Effects.Silhouette([ImageElement], Color.RoyalBlue)
       ImageDrawHelper.Effects.Skew([ImageElement], SkewType.Parallelogram, -10, SkewOrientation.Horizontal, True)
       ImageDrawHelper.Effects.Solarize([ImageElement])
       ImageDrawHelper.Effects.Stretch([ImageElement], 90, 150)
       ImageDrawHelper.Effects.Tint([ImageElement], Color.Orange)

       PictureBox1.BackgroundImage = [ImageElement].GetOutputImage








Eleкtro

#372
Un mini bot para IRC usando la librería Thesher IRC.

Y digo mini bot, porque sólamente le implementé dos funciones muy básicas, !Kick y !KickAll.

El código está bastante hardcodeado.

Código (vbnet) [Seleccionar]
' [Thresher IRC] Bot example
' (By Elektro)
'
' Instructions
' 1. Add a reference to 'Sharkbite.Thresher.dll'.
'
' Usage Examples:
' Public  BOT As New IRCBot("irc.freenode.net", "#ircehn", "ElektroBot")

#Region " Imports "

Imports Sharkbite.Irc

#End Region

Public Class IRCBot

#Region " Members "

#Region " Properties "

   ''' <summary>
   ''' Indicates the IRC server to connect.
   ''' </summary>
   Private Property Server As String = String.Empty

   ''' <summary>
   ''' Indicates the IRC channel to join.
   ''' </summary>
   Private Property Channel As String = String.Empty

   ''' <summary>
   ''' Indicates the nickname to use.
   ''' </summary>
   Private Property Nick As String = String.Empty

#End Region

#Region " Others "

   ''' <summary>
   ''' Performs the avaliable Bot commands.
   ''' </summary>
   Public WithEvents BotConnection As Connection

   ''' <summary>
   ''' Handles the Bot events.
   ''' </summary>
   Public WithEvents BotListener As Listener

   ''' <summary>
   ''' Stores a list of the current users on a channel room.
   ''' </summary>
   Private RoomUserNames As New List(Of String)

   ''' <summary>
   ''' Indicates the invoked command arguments.
   ''' </summary>
   Private CommandParts As String() = {String.Empty}

#End Region

#End Region

#Region " Constructor "

   ''' <summary>
   ''' Initializes a new instance of the <see cref="IRCBot"/> class.
   ''' </summary>
   ''' <param name="Server">Indicates the IRC server to connect.</param>
   ''' <param name="Channel">Indicates the IRC channel to join.</param>
   ''' <param name="Nick">Indicates the nickname to use.</param>
   Public Sub New(ByVal Server As String,
                  ByVal Channel As String,
                  ByVal Nick As String)

       Me.Server = Server
       Me.Channel = Channel
       Me.Nick = Nick

       CreateConnection()

   End Sub

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Establishes the first connection to the server.
   ''' </summary>
   Public Sub CreateConnection()

       Console.WriteLine(String.Format("[+] Bot started........: '{0}'", DateTime.Now.ToString))

       Identd.Start(Me.Nick)
       BotConnection = New Connection(New ConnectionArgs(Me.Nick, Me.Server), False, False)
       BotListener = BotConnection.Listener

       Try
           BotConnection.Connect()
           Console.WriteLine(String.Format("[+] Connected to server: '{0}'", Me.Server))

       Catch e As Exception
           Console.WriteLine(String.Format("[X] Error during connection process: {0}", e.ToString))
           Identd.Stop()

       End Try

   End Sub


   ''' <summary>
   ''' Kicks everybody from the channel room unless the user who invoked the command.
   ''' </summary>
   ''' <param name="UserInvoked">Indicates the user who invoked the command.</param>
   ''' <param name="CommandMessage">Indicates the command message to retrieve the command arguments.</param>
   Private Sub KickEverybody(ByVal UserInvoked As String,
                             ByVal CommandMessage As String)

       ' Renew the current nicknames on the channel room.
       BotConnection.Sender.AllNames()

       ' Get the Kick Reason from the CommandMessage.
       CommandParts = CommandMessage.Split

       Select Case CommandParts.Length

           Case Is > 1
               CommandParts = CommandParts.Skip(1).ToArray

           Case Else
               BotConnection.Sender.PublicMessage(Me.Channel, String.Format(
                   "[X] Can't process the invoked command, 'KickReason' parameter expected."))

               BotConnection.Sender.PublicMessage(Me.Channel, String.Format(
                   "[i] Command Syntax: !KickAll ""Kick Reason"""))

               Exit Sub

       End Select

       ' Kick each users one by one.
       For Each User As String In (From Nick As String
                                   In RoomUserNames
                                   Where Not Nick = UserInvoked _
                                         AndAlso Not Nick = Me.Nick)

           BotConnection.Sender.Kick(Me.Channel, String.Join(" ", CommandParts), User)

       Next User

   End Sub

   ''' <summary>
   ''' Kicks the specified user from the channel.
   ''' </summary>
   ''' <param name="CommandMessage">Indicates the command message to retrieve the command arguments.</param>
   Private Sub Kick(ByVal CommandMessage As String)

       ' Renew the current nicknames on the channel room.
       BotConnection.Sender.AllNames()

       ' Get the user to Kick and the Kick Reason.
       CommandParts = CommandMessage.Split
       Select Case CommandParts.Length

           Case Is > 2
               CommandParts = CommandParts.Skip(1).ToArray

           Case Is < 2
               BotConnection.Sender.PublicMessage(Me.Channel, String.Format(
                   "[X] Can't process the invoked command, 'NickName' parameter expected."))

               BotConnection.Sender.PublicMessage(Me.Channel, String.Format(
                   "[X] Command Syntax: !Kick ""NickName"" ""Kick Reason"""))

               Exit Sub

       End Select

       BotConnection.Sender.Kick(Me.Channel, String.Join(" ", CommandParts.Skip(1)), CommandParts(0))

   End Sub


#End Region

#Region " Event Handlers "

   ''' <summary>
   ''' Occurs when the Bot joins to a channel.
   ''' </summary>
   Private Sub OnRegistered() Handles BotListener.OnRegistered

       Try
           Identd.Stop()
           BotConnection.Sender.Join(Me.Channel)
           Console.WriteLine(String.Format("[+] Channel joined.....: '{0}'", Me.Channel))

       Catch e As Exception
           Console.WriteLine(String.Format("[X] Error in 'OnRegistered' Event: {0}", e.Message))

       End Try

   End Sub

   ''' <summary>
   ''' Occurs when an unexpected Bot error happens.
   ''' </summary>
   ''' <param name="code">Indicates the ReplyCode.</param>
   ''' <param name="message">Contains the error message information.</param>
   Private Sub OnError(ByVal code As ReplyCode,
                       ByVal message As String) Handles BotListener.OnError

       BotConnection.Sender.PublicMessage(Me.Channel, String.Format("[X] Unexpected Error: {0}", message))
       Console.WriteLine(String.Format("[X] Unexpected Error: {0}", message))
       Debug.WriteLine(String.Format("[X] Unexpected Error: {0}", message))

   End Sub

   ''' <summary>
   ''' Occurs when a user sends a public message in a channel room.
   ''' </summary>
   ''' <param name="user">Indicates the user who sent the public message.</param>
   ''' <param name="channel">Indicates the channel where the public message was sent.</param>
   ''' <param name="message">Indicates the content of the public message.</param>
   Public Sub OnPublic(ByVal User As UserInfo,
                       ByVal Channel As String,
                       ByVal Message As String) Handles BotListener.OnPublic


       Select Case True

           Case Message.Trim.StartsWith("!KickAll ", StringComparison.OrdinalIgnoreCase)
               KickEverybody(User.Nick, Message)

           Case message.Trim.StartsWith("!Kick ", StringComparison.OrdinalIgnoreCase)
               Kick(Message)

       End Select

   End Sub

   ''' <summary>
   ''' Occurs when the Bot invokes one of the methods to retrieve the nicks of a channel.
   ''' For example, the 'Sender.AllNames' method.
   ''' </summary>
   ''' <param name="Channel">Indicates the channel to list the nicks.</param>
   ''' <param name="Nicks">Indicates the nicks of the channel.</param>
   ''' <param name="LastError">Indicates the last command error.</param>
   Private Sub OnNames(ByVal Channel As String,
                       ByVal Nicks() As String,
                       ByVal LastError As Boolean) Handles BotListener.OnNames

       If Channel = Me.Channel AndAlso Not RoomUserNames.Count <> 0 Then

           RoomUserNames.Clear()
           RoomUserNames.AddRange((From Name As String In Nicks
                                   Select If(Name.StartsWith("@"), Name.Substring(1), Name)).
                                   ToArray)

       End If

   End Sub

   ''' <summary>
   ''' Occurs when the bot invokes the Kick command.
   ''' </summary>
   ''' <param name="user">Indicates the user who invoked the Kick command.</param>
   ''' <param name="channel">Indicates the channel where the user was kicked.</param>
   ''' <param name="kickee">Indicates the kickee.</param>
   ''' <param name="reason">Indicates the kick reason.</param>
   Private Sub OnKick(ByVal user As UserInfo,
                      ByVal channel As String,
                      ByVal kickee As String,
                      ByVal reason As String) Handles BotListener.OnKick

       Console.WriteLine(String.Format("[+]: User kicked: '{0}' From channel: '{1}' With reason: '{2}'.",
                                       user.Nick,
                                       channel,
                                       reason))

   End Sub

#End Region

End Class








Eleкtro

Una versión pulida de mi ayudante para convertir archivos Reg a Bat

Código (vbnet) [Seleccionar]

' ***********************************************************************
' Assembly : Reg2Bat
' Author   : Elektro
' Modified : 01-28-2014
' ***********************************************************************
' <copyright file="Reg2Bat.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

' Dim BatchScript As String = Reg2Bat.Convert("C:\RegistryFile.reg")

' IO.File.WriteAllText("Converted.bat", Reg2Bat.Convert("C:\RegistryFile.reg"), System.Text.Encoding.Default)

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions

#End Region

''' <summary>
''' Converts a Registry Script to a Batch Script.
''' </summary>
Public Class Reg2Bat

#Region " ReadOnly Strings "

    ''' <summary>
    ''' Indicates the resulting Batch-Script Header.
    ''' </summary>
    Private Shared ReadOnly BatchHeader As String =
    <a>:: Converted with Reg2Bat by Elektro

@Echo OFF
</a>.Value

    ''' <summary>
    ''' Indicates the resulting Batch-Script Footer.
    ''' </summary>
    Private Shared ReadOnly BatchFooter As String =
    <a>
Pause&amp;Exit</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a Comment-Line command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_Comment As String =
    <a>REM {0}</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG Key-Add command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_KeyAdd As String =
    <a>REG ADD "{0}" /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG Key-Delete command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_KeyDelete As String =
    <a>REG DELETE "{0}" /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG DefaultValue-Add command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_DefaultValueAdd As String =
    <a>REG ADD "{0}" /V "" /D {1} /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG Value-Add REG_SZ command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_ValueAdd_REGSZ As String =
    <a>REG ADD "{0}" /V "{1}" /T "REG_SZ" /D "{2}" /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch command StringFormat of a REG Value-Add BINARY command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_ValueAdd_BINARY As String =
    <a>REG ADD "{0}" /V "{1}" /T "REG_BINARY" /D "{2}" /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG Value-Add DWORD command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_ValueAdd_DWORD As String =
    <a>REG ADD "{0}" /V "{1}" /T "REG_DWORD" /D "{2}" /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG Value-Add QWORD command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_ValueAdd_QWORD As String =
    <a>REG ADD "{0}" /V "{1}" /T "REG_QWORD" /D "{2}" /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG Value-Add EXPAND_SZ command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_ValueAdd_EXPANDSZ As String =
    <a>REG ADD "{0}" /V "{1}" /T "REG_EXPAND_SZ" /D "{2}" /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG Value-Add MULTI_SZ command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_ValueAdd_MULTISZ As String =
    <a>REG ADD "{0}" /V "{1}" /T "REG_MULTI_SZ" /D "{2}" /F</a>.Value

    ''' <summary>
    ''' Indicates the Batch syntax StringFormat of a REG Value-Delete command.
    ''' </summary>
    Private Shared ReadOnly BatchStringFormat_ValueDelete As String =
    <a>REG DELETE "{0}" /V "{1}" /F</a>.Value

    ''' <summary>
    ''' Indicates the string to split a BINARY registry line.
    ''' </summary>
    Private Shared ReadOnly RegistryValueSplitter_BINARY As String =
    <a>=HEX</a>.Value

    ''' <summary>
    ''' Indicates the string to split a DWORD registry line.
    ''' </summary>
    Private Shared ReadOnly RegistryValueSplitter_DWORD As String =
    <a>=DWORD:</a>.Value

    ''' <summary>
    ''' Indicates the string to split a QWORD registry line.
    ''' </summary>
    Private Shared ReadOnly RegistryValueSplitter_QWORD As String =
    <a>=HEX\(b\):</a>.Value

    ''' <summary>
    ''' Indicates the string to split a EXPAND_SZ registry line.
    ''' </summary>
    Private Shared ReadOnly RegistryValueSplitter_EXPANDSZ As String =
    <a>=HEX\(2\):</a>.Value

    ''' <summary>
    ''' Indicates the string to split a MULTI_SZ registry line.
    ''' </summary>
    Private Shared ReadOnly RegistryValueSplitter_MULTISZ As String =
    <a>=HEX\(7\):</a>.Value

    ''' <summary>
    ''' Indicates the string to split a REG_SZ registry line.
    ''' </summary>
    Private Shared ReadOnly RegistryValueSplitter_REGSZ As String =
    <a>"="</a>.Value

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Indicates the data type of a registry value.
    ''' </summary>
    Public Enum RegistryValueType As Integer

        ''' <summary>
        ''' A null-terminated string.
        ''' This will be either a Unicode or an ANSI string.
        ''' </summary>
        REG_SZ = 0

        ''' <summary>
        ''' Binary data.
        ''' </summary>
        BINARY = 1

        ''' <summary>
        ''' A 32-bit number.
        ''' </summary>
        DWORD = 2

        ''' <summary>
        ''' A 64-bit number.
        ''' </summary>
        QWORD = 3

        ''' <summary>
        ''' A null-terminated string that contains unexpanded references to environment variables
        ''' (for example, "%WinDir%").
        ''' </summary>
        EXPAND_SZ = 4

        ''' <summary>
        ''' A sequence of null-terminated strings, terminated by an empty string (\0).
        '''
        ''' The following is an example:
        ''' String1\0String2\0String3\0LastString\0\0
        ''' The first \0 terminates the first string,
        ''' the second to the last \0 terminates the last string,
        ''' and the final \0 terminates the sequence.
        ''' Note that the final terminator must be factored into the length of the string.
        ''' </summary>
        MULTI_SZ = 5

    End Enum

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Converts a Registry Script to a Batch Script.
    ''' </summary>
    ''' <param name="RegistryFile">Indicates the registry file to convert.</param>
    ''' <returns>System.String.</returns>
    Public Shared Function Convert(ByVal RegistryFile As String) As String

        ' Split the Registry content.
        Dim RegistryContent As String() =
            String.Join("@@@Reg2Bat@@@", File.ReadAllLines(RegistryFile)).
                   Replace("\@@@Reg2Bat@@@  ", Nothing).
                   Replace("@@@Reg2Bat@@@", Environment.NewLine).
                   Split(Environment.NewLine)

        ' Where the registry line to convert will be stored.
        Dim RegLine As String = String.Empty

        ' Where the registry key to convert will be stored.
        Dim RegKey As String = String.Empty

        ' Where the registry value to convert will be stored.
        Dim RegVal As String = String.Empty

        ' Where the registry data to convert will be stored.
        Dim RegData As String = String.Empty

        ' Where the decoded registry strings will be stored.
        Dim BatchCommands As New StringBuilder

        ' Writes the specified Batch-Script Header.
        BatchCommands.AppendLine(BatchHeader)

        ' Start reading the Registry File.
        For X As Long = 0 To RegistryContent.LongLength - 1

            RegLine = RegistryContent(X).Trim

            Select Case True

                Case RegLine.StartsWith(";"), RegLine.StartsWith("#")  ' It's a comment line.

                    BatchCommands.AppendLine(
                        String.Format(BatchStringFormat_Comment, RegLine.Substring(1, RegLine.Length - 1).Trim))

                Case RegLine.StartsWith("[-") ' It's a key to delete.

                    RegKey = RegLine.Substring(2, RegLine.Length - 3).Trim
                    BatchCommands.AppendLine(String.Format(BatchStringFormat_KeyDelete, RegKey))

                Case RegLine.StartsWith("[") ' It's a key to add.

                    RegKey = RegLine.Substring(1, RegLine.Length - 2).Trim
                    BatchCommands.AppendLine(String.Format(BatchStringFormat_KeyAdd, RegKey))

                Case RegLine.StartsWith("@=") ' It's a default value to add.

                    RegData = RegLine.Split("@=").Last
                    BatchCommands.AppendLine(String.Format(BatchStringFormat_DefaultValueAdd, RegKey, RegData))

                Case RegLine.StartsWith("""") _
                AndAlso RegLine.Split("=").Last = "-" ' It's a value to delete.

                    RegVal = RegLine.Substring(1, RegLine.Length - 4)
                    BatchCommands.AppendLine(String.Format(BatchStringFormat_ValueDelete, RegKey, RegVal))

                Case RegLine.StartsWith("""") ' It's a value to add.

                    Select Case RegLine.Split("=")(1).Split(":").First.ToUpper

                        Case "HEX" ' It's a Binary value.
                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.BINARY))
                            RegData = GetRegistryData(RegLine, RegistryValueType.BINARY)
                            BatchCommands.AppendLine(
                                String.Format(BatchStringFormat_ValueAdd_BINARY, RegKey, RegVal, RegData))

                        Case "DWORD" ' It's a DWORD value.
                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.DWORD))
                            RegData = GetRegistryData(RegLine, RegistryValueType.DWORD)
                            BatchCommands.AppendLine(
                                String.Format(BatchStringFormat_ValueAdd_DWORD, RegKey, RegVal, RegData))

                        Case "HEX(B)" ' It's a QWORD value.
                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.QWORD))
                            RegData = GetRegistryData(RegLine, RegistryValueType.QWORD)
                            BatchCommands.AppendLine(
                                String.Format(BatchStringFormat_ValueAdd_QWORD, RegKey, RegVal, RegData))

                        Case "HEX(2)"  ' It's a EXPAND_SZ value.
                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.EXPAND_SZ))
                            RegData = FormatRegistryString(GetRegistryData(RegLine, RegistryValueType.EXPAND_SZ))
                            BatchCommands.AppendLine(
                                String.Format(BatchStringFormat_ValueAdd_EXPANDSZ, RegKey, RegVal, RegData))

                        Case "HEX(7)" ' It's a MULTI_SZ value.
                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.MULTI_SZ))
                            RegData = FormatRegistryString(GetRegistryData(RegLine, RegistryValueType.MULTI_SZ))
                            BatchCommands.AppendLine(
                                String.Format(BatchStringFormat_ValueAdd_MULTISZ, RegKey, RegVal, RegData))

                        Case Else ' It's a REG_SZ value.
                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.REG_SZ))
                            RegData = FormatRegistryString(GetRegistryData(RegLine, RegistryValueType.REG_SZ))
                            BatchCommands.AppendLine(
                                String.Format(BatchStringFormat_ValueAdd_REGSZ, RegKey, RegVal, RegData))

                    End Select ' RegLine.Split("=")(1).Split(":").First.ToUpper

            End Select ' RegLine.StartsWith("""")

        Next X ' RegLine

        ' Writes the specified Batch-Script Footer.
        BatchCommands.AppendLine(BatchFooter)

        Return BatchCommands.ToString

    End Function

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Gets the registry value of a registry line.
    ''' </summary>
    ''' <param name="RegistryLine">Indicates the registry line.</param>
    ''' <param name="RegistryValueType">Indicates the type of the registry value.</param>
    ''' <returns>System.String.</returns>
    Private Shared Function GetRegistryValue(ByVal RegistryLine As String,
                                             ByVal RegistryValueType As RegistryValueType) As String

        Dim Value As String = String.Empty

        Select Case RegistryValueType

            Case RegistryValueType.BINARY
                Value = Regex.Split(RegistryLine,
                                    RegistryValueSplitter_BINARY,
                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()

            Case RegistryValueType.DWORD
                Value = Regex.Split(RegistryLine,
                                    RegistryValueSplitter_DWORD,
                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()

            Case RegistryValueType.QWORD
                Value = Regex.Split(RegistryLine,
                                    RegistryValueSplitter_QWORD,
                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()

            Case RegistryValueType.EXPAND_SZ
                Value = Regex.Split(RegistryLine,
                                    RegistryValueSplitter_EXPANDSZ,
                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()

            Case RegistryValueType.MULTI_SZ
                Value = Regex.Split(RegistryLine,
                                    RegistryValueSplitter_MULTISZ,
                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()

            Case RegistryValueType.REG_SZ
                Value = Regex.Split(RegistryLine,
                                    RegistryValueSplitter_REGSZ,
                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()

        End Select

        If Value.StartsWith("""") Then
            Value = Value.Substring(1, Value.Length - 1)
        End If

        If Value.EndsWith("""") Then
            Value = Value.Substring(0, Value.Length - 1)
        End If

        Return Value

    End Function

    ''' <summary>
    ''' Gets the registry data of a registry line.
    ''' </summary>
    ''' <param name="RegistryLine">Indicates the registry line.</param>
    ''' <param name="RegistryValueType">Indicates the type of the registry value.</param>
    ''' <returns>System.String.</returns>
    Private Shared Function GetRegistryData(ByVal RegistryLine As String,
                                            ByVal RegistryValueType As RegistryValueType) As String

        Dim Data As String = String.Empty

        Select Case RegistryValueType

            Case RegistryValueType.BINARY

                Data = Regex.Split(RegistryLine,
                                   Regex.Split(RegistryLine,
                                               RegistryValueSplitter_BINARY, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
                                               RegistryValueSplitter_BINARY,
                                   RegexOptions.IgnoreCase Or RegexOptions.Singleline).
                                   Last.
                                   Replace(",", Nothing)

            Case RegistryValueType.DWORD

                Data = Regex.Split(RegistryLine,
                                   Regex.Split(RegistryLine,
                                               RegistryValueSplitter_DWORD, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
                                               RegistryValueSplitter_DWORD,
                                   RegexOptions.IgnoreCase Or RegexOptions.Singleline).
                                   Last.
                                   Replace(",", Nothing)

                Data = "0x" & Data

            Case RegistryValueType.QWORD

                RegistryLine =
                    String.Join(Nothing,
                                Regex.Split(RegistryLine,
                                            Regex.Split(RegistryLine,
                                                        RegistryValueSplitter_QWORD, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
                                                        RegistryValueSplitter_QWORD,
                                            RegexOptions.IgnoreCase Or RegexOptions.Singleline).
                                            Last.
                                            Reverse)

                For Each [Byte] As String In RegistryLine.Split(",")
                    Data &= String.Join(Nothing, [Byte].Reverse)
                Next [Byte]

                Data = "0x" & Data

            Case RegistryValueType.EXPAND_SZ

                RegistryLine = Regex.Split(RegistryLine,
                                            Regex.Split(RegistryLine,
                                                        RegistryValueSplitter_EXPANDSZ, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
                                                        RegistryValueSplitter_EXPANDSZ,
                                            RegexOptions.IgnoreCase Or RegexOptions.Singleline).
                                            Last.
                                            Replace(",00", "").
                                            Replace("00,", "")

                For Each [Byte] As String In RegistryLine.Split(",")
                    Data &= Chr(Val("&H" & [Byte]))
                Next [Byte]

                Data = Data.Replace("""", "\""")

            Case RegistryValueType.MULTI_SZ

                RegistryLine = Regex.Split(RegistryLine,
                                            Regex.Split(RegistryLine,
                                                        RegistryValueSplitter_MULTISZ, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
                                                        RegistryValueSplitter_MULTISZ,
                                            RegexOptions.IgnoreCase Or RegexOptions.Singleline).
                                            Last.
                                            Replace(",00,00,00", ",\0").
                                            Replace(",00", "").
                                            Replace("00,", "")

                For Each [Byte] In RegistryLine.Split(",")

                    If [Byte] = "\0" Then
                        Data &= "\0" ' Multiline separator.
                    Else
                        Data &= Chr(Val("&H" & [Byte]))
                    End If

                Next

                Return Data.Replace("""", "\""")

            Case RegistryValueType.REG_SZ

                Data = Regex.Split(RegistryLine,
                                   Regex.Split(RegistryLine,
                                               RegistryValueSplitter_REGSZ, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
                                               RegistryValueSplitter_REGSZ,
                                   RegexOptions.IgnoreCase Or RegexOptions.Singleline).
                                   Last

                Data = Data.Substring(0, Data.Length - 1).Replace("\\", "\")

        End Select

        Return Data

    End Function

    ''' <summary>
    ''' Properly formats a registry string to insert it in a Batch command string.
    ''' </summary>
    ''' <param name="RegistryString">Indicates the Reg Batch command string.</param>
    ''' <returns>System.String.</returns>
    Private Shared Function FormatRegistryString(ByVal RegistryString As String) As String

        RegistryString = RegistryString.Replace("%", "%%")
        If Not RegistryString.Contains("""") Then
            Return RegistryString
        End If

        RegistryString = RegistryString.Replace("\""", """")

        Dim strArray() As String = RegistryString.Split("""")

        For X As Long = 1 To strArray.Length - 1 Step 2

            strArray(X) = strArray(X).Replace("^", "^^") ' This replacement need to be THE FIRST.
            strArray(X) = strArray(X).Replace("<", "^<")
            strArray(X) = strArray(X).Replace(">", "^>")
            strArray(X) = strArray(X).Replace("|", "^|")
            strArray(X) = strArray(X).Replace("&", "^&")
            ' strArray(X) = strArray(X).Replace("\", "\\")

        Next X

        Return String.Join("\""", strArray)

    End Function

#End Region

#Region " Hidden methods "

    ' These methods are purposely hidden from Intellisense just to look better without unneeded methods.
    ' NOTE: The methods can be re-enabled at any-time if needed.

    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub Equals()
    End Sub

    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub ReferenceEquals()
    End Sub

#End Region

End Class








Eleкtro

Una Helper Class para la librería de pago Nasosoft transform, para convertir text RTF a HTML y viceversa.

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

#Region " Example Usages "

'MsgBox(DocumentConverter.Html2Rtf("Hello World!"))
'MsgBox(DocumentConverter.Rtf2Html("{\rtf1\ansi\fbidis\ansicpg1252\deff0{\fonttbl{\f0\fswiss\fcharset0 Times New Roman;}{\f1\fswiss\fcharset2 Symbol;}}{\colortbl;\red192\green192\blue192;}\viewkind5\viewscale100{\*\bkmkstart BM_BEGIN}\pard\plain\f0{Hello World!}}"))

'Dim HtmlText As String = DocumentConverter.Rtf2Html(IO.File.ReadAllText("C:\File.rtf"), TextEncoding:=Nothing)
'Dim RtfText As String = DocumentConverter.Html2Rtf(IO.File.ReadAllText("C:\File.html"), TextEncoding:=Nothing)
'Dim PlainTextFromRtf As String = DocumentConverter.Rtf2Txt(IO.File.ReadAllText("C:\File.rtf"), TextEncoding:=Nothing)
'Dim PlainTextFromHtml As String = DocumentConverter.Html2Txt(IO.File.ReadAllText("C:\File.html"), TextEncoding:=Nothing)

#End Region

#Region " Imports "

Imports Nasosoft.Documents.Transform
Imports System.IO
Imports System.Text

#End Region

''' <summary>
''' Performs document conversion operations.
''' </summary>
Public Class DocumentConverter

#Region " Public Methods "

    ''' <summary>
    ''' Converts RTF text to HTML.
    ''' </summary>
    ''' <param name="RtfText">Indicates the RTF text.</param>
    ''' <param name="TextEncoding">Indicates the text encoding.</param>
    ''' <returns>System.String.</returns>
    Public Shared Function Rtf2Html(ByVal RtfText As String,
                                    Optional ByVal TextEncoding As Encoding = Nothing) As String

        TextEncoding = If(TextEncoding Is Nothing, Encoding.Default, TextEncoding)

        Dim RtfStream As New MemoryStream(TextEncoding.GetBytes(RtfText))
        Dim HtmlStream As New MemoryStream
        Dim HtmlText As String = String.Empty

        Using Converter As New RtfToHtmlTransform()
            Converter.Load(RtfStream)
            Converter.Transform(HtmlStream)
        End Using

        HtmlStream.Position = 0

        Using StrReader As New StreamReader(HtmlStream)
            HtmlText = StrReader.ReadToEnd
        End Using

        RtfStream.Close()
        HtmlStream.Close()

        Return HtmlText

    End Function

    ''' <summary>
    ''' Converts RTF text to TXT (Plain text).
    ''' </summary>
    ''' <param name="RtfText">Indicates the RTF text.</param>
    ''' <param name="TextEncoding">Indicates the text encoding.</param>
    ''' <returns>System.String.</returns>
    Public Shared Function Rtf2Txt(ByVal RtfText As String,
                                    Optional ByVal TextEncoding As Encoding = Nothing) As String

        TextEncoding = If(TextEncoding Is Nothing, Encoding.Default, TextEncoding)

        Dim RtfStream As New MemoryStream(TextEncoding.GetBytes(RtfText))
        Dim TextStream As New MemoryStream
        Dim PlainText As String = String.Empty

        Using Converter As New RtfToTextTransform()
            Converter.Load(RtfStream)
            Converter.Transform(TextStream)
        End Using

        TextStream.Position = 0

        Using StrReader As New StreamReader(TextStream)
            PlainText = StrReader.ReadToEnd
        End Using

        RtfStream.Close()
        TextStream.Close()

        Return PlainText

    End Function

    ''' <summary>
    ''' Converts HTML text to RTF.
    ''' </summary>
    ''' <param name="HtmlText">Indicates the HTML text.</param>
    ''' <param name="TextEncoding">Indicates the text encoding.</param>
    ''' <returns>System.String.</returns>
    Public Shared Function Html2Rtf(ByVal HtmlText As String,
                                    Optional ByVal TextEncoding As Encoding = Nothing) As String

        TextEncoding = If(TextEncoding Is Nothing, Encoding.Default, TextEncoding)

        Dim HtmlStream As New MemoryStream(TextEncoding.GetBytes(HtmlText))
        Dim RtfStream As New MemoryStream
        Dim RtfText As String = String.Empty

        Using Converter As New HtmlToRtfTransform()
            Converter.Load(HtmlStream)
            Converter.Transform(RtfStream)
        End Using

        RtfStream.Position = 0

        Using StrReader As New StreamReader(RtfStream)
            RtfText = StrReader.ReadToEnd
        End Using

        HtmlStream.Close()
        RtfStream.Close()

        Return RtfText

    End Function

    ''' <summary>
    ''' Converts HTML text to TXT (Plain text).
    ''' </summary>
    ''' <param name="HtmlText">Indicates the HTML text.</param>
    ''' <param name="TextEncoding">Indicates the text encoding.</param>
    ''' <returns>System.String.</returns>
    Public Shared Function Html2Txt(ByVal HtmlText As String,
                                    Optional ByVal TextEncoding As Encoding = Nothing) As String

        TextEncoding = If(TextEncoding Is Nothing, Encoding.Default, TextEncoding)

        Dim HtmlStream As New MemoryStream(TextEncoding.GetBytes(HtmlText))
        Dim TextStream As New MemoryStream
        Dim PlainText As String = String.Empty

        Using Converter As New HtmlToTextTransform()
            Converter.Load(HtmlStream)
            Converter.Transform(TextStream)
        End Using

        TextStream.Position = 0

        Using StrReader As New StreamReader(TextStream)
            PlainText = StrReader.ReadToEnd
        End Using

        HtmlStream.Close()
        TextStream.Close()

        Return PlainText

    End Function

#End Region

End Class








Eleкtro

Ejemplo para monitorear la ejecución de los procesos del sistema:

Código (vbnet) [Seleccionar]
Public Class Form1

    Private WithEvents ProcessStartWatcher As ManagementEventWatcher =
        New ManagementEventWatcher(
            New WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"))

    Private WithEvents ProcessStopWatcher As ManagementEventWatcher =
        New System.Management.ManagementEventWatcher(
            New WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"))

    Private Shadows Sub Load() Handles MyBase.Load
        ProcessStartWatcher.Start()
        ProcessStopWatcher.Start()
    End Sub

    Private Shadows Sub Closing() Handles MyBase.Closing
        ProcessStartWatcher.Stop()
        ProcessStopWatcher.Stop()
    End Sub

    Public Sub ProcessStartWatcher_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs) _
    Handles ProcessStartWatcher.EventArrived

        MsgBox(String.Format("Process started: {0}",
                             e.NewEvent.Properties("ProcessName").Value))

    End Sub

    Private Sub ProcessStopWatcher_Stopped(ByVal sender As Object, ByVal e As EventArrivedEventArgs) _
    Handles ProcessStopWatcher.EventArrived

        MsgBox(String.Format("Process stopped: {0}",
                             e.NewEvent.Properties("ProcessName").Value))

    End Sub

End Class





Modificar el proxy de un GeckoFX Webbrowser:

Código (vbnet) [Seleccionar]



' By Elektro


    ''' <summary>
    ''' ProxyTypes of Gecko webbrowser.
    ''' </summary>
    Public Enum ProxyType

        ''' <summary>
        ''' Direct connection, no proxy.
        ''' (Default in Windows and Mac previous to 1.9.2.4 /Firefox 3.6.4)
        ''' </summary>
        DirectConnection = 0

        ''' <summary>
        ''' Manual proxy configuration.
        ''' </summary>
        Manual = 1

        ''' <summary>
        ''' Proxy auto-configuration (PAC).
        ''' </summary>
        AutoConfiguration = 2

        ''' <summary>
        ''' Auto-detect proxy settings.
        ''' </summary>
        AutoDetect = 4

        ''' <summary>
        ''' Use system proxy settings.
        ''' (Default in Linux; default for all platforms, starting in 1.9.2.4 /Firefox 3.6.4)
        ''' </summary>
        System = 5

    End Enum

    ''' <summary>
    ''' Sets the proxy type of a Gecko Webbrowser.
    ''' </summary>
    ''' <param name="ProxyType">Indicates the type of proxy.</param>
    Private Sub SetGeckoProxyType(ByVal ProxyType As ProxyType)

        GeckoPreferences.Default("network.proxy.type") = ProxyType

    End Sub

    ''' <summary>
    ''' Sets the proxy of a Gecko Webbrowser.
    ''' </summary>
    ''' <param name="Host">Indicates the proxy host.</param>
    ''' <param name="Port">Indicates the proxy port.</param>
    Private Sub SetGeckoProxy(ByVal Host As String,
                              ByVal Port As Integer)

        ' Set the ProxyType to manual configuration.
        GeckoPreferences.Default("network.proxy.type") = ProxyType.Manual

        ' Set the HTP proxy Host and Port.
        GeckoPreferences.Default("network.proxy.http") = Host
        GeckoPreferences.Default("network.proxy.http_port") = Port

        ' Set the SSL proxy Host and Port.
        GeckoPreferences.Default("network.proxy.ssl") = Host
        GeckoPreferences.Default("network.proxy.ssl_port") = Port

    End Sub





Devuelve un String con el source de una página

Código (vbnet) [Seleccionar]
    ' Get SourcePage String
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' MsgBox(GetSourcePageString("http://www.elhacker.net"))
    '
    ''' <summary>
    ''' Gets a web source page.
    ''' </summary>
    ''' <param name="URL">Indicates the source page URL to get.</param>
    ''' <returns>System.String.</returns>
    ''' <exception cref="Exception"></exception>
    Private Function GetSourcePageString(ByVal URL As String) As String

        Try

            Using StrReader As New IO.StreamReader(Net.HttpWebRequest.Create(URL).GetResponse().GetResponseStream)
                Return StrReader.ReadToEnd
            End Using

        Catch ex As Exception
            Throw New Exception(ex.Message)
            Return Nothing

        End Try

    End Function





Devuelve un Array con el source de una página:

Código (vbnet) [Seleccionar]
    ' Get SourcePage Array
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' Dim SourceLines As String() = GetSourcePageArray("http://www.ElHacker.net", TrimLines:=True)
    ' For Each Line As String In SourceLines : MsgBox(Line) : Next Line
    '
    ''' <summary>
    ''' Gets a web source page.
    ''' </summary>
    ''' <param name="URL">Indicates the source page URL to get.</param>
    ''' <param name="TrimLines">Indicates whether to trim the lines.</param>
    ''' <param name="SplitOptions">Indicates the split options.</param>
    ''' <returns>System.String[][].</returns>
    ''' <exception cref="Exception"></exception>
    Private Function GetSourcePageArray(ByVal URL As String,
                                        Optional ByVal TrimLines As Boolean = False,
                                        Optional ByVal SplitOptions As StringSplitOptions =
                                                       StringSplitOptions.None) As String()

        Try

            Using StrReader As New IO.StreamReader(Net.HttpWebRequest.Create(URL).GetResponse().GetResponseStream)

                If TrimLines Then

                    Return (From Line As String
                           In StrReader.ReadToEnd.Split({Environment.NewLine}, SplitOptions)
                           Select Line.Trim).ToArray

                Else
                    Return StrReader.ReadToEnd.Split({Environment.NewLine}, SplitOptions)

                End If

            End Using

        Catch ex As Exception
            Throw New Exception(ex.Message)
            Return Nothing

        End Try

    End Function





Devuelve el directorio de un proceso en ejecución

Código (vbnet) [Seleccionar]
    ' Get Process Path
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' MsgBox(GetProcessPath("notepad.exe").First)
    '
    ''' <summary>
    ''' Gets the absolute path of a running process.
    ''' </summary>
    ''' <param name="ProcessName">Indicates the name of the process.</param>
    ''' <returns>System.String[][].</returns>
    ''' <exception cref="Exception">ProcessName parametter can't be Null.</exception>
    Public Function GetProcessPath(ByVal ProcessName As String) As String()

        If ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
            ProcessName = ProcessName.Remove(ProcessName.Length - 4)
        End If

        Return (From p As Process In Process.GetProcesses
                Where p.ProcessName.Equals(ProcessName, StringComparison.OrdinalIgnoreCase)
                Select p.MainModule.FileName).ToArray

    End Function





Desordena un archivo de texto y devuelve un String

Código (vbnet) [Seleccionar]
    ' Randomize TextFile String
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' MsgBox(RandomizeTextFileString("C:\File.txt", Encoding:=Nothing)))
    '
    ''' <summary>
    ''' Randomizes the contents of a text file.
    ''' </summary>
    ''' <param name="TextFile">Indicates the text file to randomize.</param>
    ''' <param name="Encoding">Indicates the text encoding to use.</param>
    ''' <returns>System.String.</returns>
    Public Function RandomizeTextFileString(ByVal TextFile As String,
                                            Optional ByVal Encoding As System.Text.Encoding = Nothing) As String

        Dim Randomizer As New Random

        Return String.Join(Environment.NewLine,
                           (From Item As String
                            In IO.File.ReadAllLines(TextFile,
                                                    If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding))
                            Order By Randomizer.Next))

    End Function





Desordena un archivo d etexto y devuelve un Array:

Código (vbnet) [Seleccionar]
    ' Randomize TextFile Array
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' MsgBox(RandomizeTextFileArray("C:\File.txt", Encoding:=Nothing).First))
    '
    ''' <summary>
    ''' Randomizes the contents of a text file.
    ''' </summary>
    ''' <param name="TextFile">Indicates the text file to randomize.</param>
    ''' <param name="Encoding">Indicates the text encoding to use.</param>
    ''' <returns>System.String[].</returns>
    Public Function RandomizeTextFileArray(ByVal TextFile As String,
                                           Optional ByVal Encoding As System.Text.Encoding = Nothing) As String()

        Dim Randomizer As New Random

        Return (From Item As String
                In IO.File.ReadAllLines(TextFile,
                                        If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding))
                Order By Randomizer.Next).ToArray

    End Function








Eleкtro

#376
He ideado este ayudante para desloguear el usuario actual, apagar o reiniciar el sistema en un pc local o remoto, o abortar una operación,
todo mediante la WinAPI (llevó bastante trabajo la investigación, y la escritura de documentación XML)  :)

~> SystemRestarter for VB.NET - by Elektro

Ejemplos de uso:

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

    ' Restart the current computer in 30 seconds and wait for applications to close.
    ' Specify that the restart operation is planned because a consecuence of an installation.
    Dim Success =
    SystemRestarter.Restart(Nothing, 30, "System is gonna be restarted quickly, save all your data...!",
                            SystemRestarter.Enums.InitiateShutdown_Force.Wait,
                            SystemRestarter.Enums.ShutdownReason.MajorOperatingSystem Or
                            SystemRestarter.Enums.ShutdownReason.MinorInstallation,
                            SystemRestarter.Enums.ShutdownPlanning.Planned)

    Console.WriteLine(String.Format("Restart operation initiated successfully?: {0}", CStr(Success)))

    ' Abort the current operation.
    If Success Then
        Dim IsAborted = SystemRestarter.Abort()
        Console.WriteLine(String.Format("Restart operation aborted   successfully?: {0}", CStr(IsAborted)))
    Else
        Console.WriteLine("There is any restart operation to abort.")
    End If
    Console.ReadKey()

    ' Shutdown the current computer instantlly and force applications to close.
    ' ( When timeout is '0' the operation can't be aborted )
    SystemRestarter.Shutdown(Nothing, 0, Nothing, SystemRestarter.Enums.InitiateShutdown_Force.ForceSelf)

    ' LogOffs the current user.
    SystemRestarter.LogOff(SystemRestarter.Enums.ExitwindowsEx_Force.Wait)

End Sub








Eleкtro

obtener los dispositivos extraibles que están conectados al sistema

Código (vbnet) [Seleccionar]
        ' GetDrivesOfType
       ' ( By Elektro )
       '
       ' Usage Examples:
       '
       ' Dim Drives As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Fixed)
       '
       ' For Each Drive As IO.DriveInfo In GetDrivesOfType(IO.DriveType.Removable)
       '     MsgBox(Drive.Name)
       ' Next Drive
       '
       ''' <summary>
       ''' Get all the connected drives of the given type.
       ''' </summary>
       ''' <param name="DriveType">Indicates the type of the drive.</param>
       ''' <returns>System.IO.DriveInfo[].</returns>
       Public Function GetDrivesOfType(ByVal DriveType As IO.DriveType) As IO.DriveInfo()
     
           Return (From Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
                   Where Drive.DriveType = DriveType).ToArray
     
       End Function





monitorizar la inserción/extracción de dispositivos

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

#Region " Usage Examples "

' ''' <summary>
' ''' The DriveWatcher instance to monitor USB devices.
' ''' </summary>
'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me)

' ''' <summary>
' ''' Handles the DriveInserted event of the USBMonitor object.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted

'    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...

'        Dim sb As New System.Text.StringBuilder

'        sb.AppendLine("DRIVE CONNECTED!")
'        sb.AppendLine()
'        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
'        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
'        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
'        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
'        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
'        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
'        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
'        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
'        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))

'        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)

'    End If

'End Sub

' ''' <summary>
' ''' Handles the DriveRemoved event of the USBMonitor object.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved

'    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...

'        Dim sb As New System.Text.StringBuilder

'        sb.AppendLine("DRIVE DISCONNECTED!")
'        sb.AppendLine()
'        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
'        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
'        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
'        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
'        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
'        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
'        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
'        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
'        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))

'        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)

'    End If

'End Sub

#End Region

#Region " Imports "

Imports System.IO
Imports System.Runtime.InteropServices
Imports System.ComponentModel

#End Region

''' <summary>
''' Device insertion/removal monitor.
''' </summary>
Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable

#Region " Objects "

    ''' <summary>
    ''' The current connected drives.
    ''' </summary>
    Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo)

    ''' <summary>
    ''' Indicates the drive letter of the current device.
    ''' </summary>
    Private DriveLetter As Char = Nothing

    ''' <summary>
    ''' Indicates the current Drive information.
    ''' </summary>
    Private CurrentDrive As DriveWatcherInfo = Nothing

    ''' <summary>
    ''' The form to manage their Windows Messages.
    ''' </summary>
    Private WithEvents form As Form = Nothing

#End Region

#Region " Events "

    ''' <summary>
    ''' Occurs when a drive is inserted.
    ''' </summary>
    Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo)

    ''' <summary>
    ''' Occurs when a drive is removed.
    ''' </summary>
    Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo)

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Notifies an application of a change to the hardware configuration of a device or the computer.
    ''' A window receives this message through its WindowProc function.
    ''' For more info, see here:
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx
    ''' </summary>
    Private Enum DeviceEvents As Integer

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

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

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

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

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

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

        ''' <summary>
        ''' The type volume
        ''' </summary>
        TypeVolume = &H2

    End Enum

#End Region

#Region " Structures "

    ''' <summary>
    ''' Indicates information related of a Device.
    ''' ( Replic of System.IO.DriveInfo )
    ''' </summary>
    Public Structure DriveWatcherInfo

        ''' <summary>
        ''' Indicates the name of a drive, such as 'C:\'.
        ''' </summary>
        Public Name As String

        ''' <summary>
        ''' Indicates the amount of available free space on a drive, in bytes.
        ''' </summary>
        Public AvailableFreeSpace As Long

        ''' <summary>
        ''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc...
        ''' </summary>
        Public DriveFormat As String

        ''' <summary>
        ''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc...
        ''' </summary>
        Public DriveType As DriveType

        ''' <summary>
        ''' Indicates whether a drive is ready.
        ''' </summary>
        Public IsReady As Boolean

        ''' <summary>
        ''' Indicates the root directory of a drive.
        ''' </summary>
        Public RootDirectory As String

        ''' <summary>
        ''' Indicates the total amount of free space available on a drive, in bytes.
        ''' </summary>
        Public TotalFreeSpace As Long

        ''' <summary>
        ''' Indicates the total size of storage space on a drive, in bytes.
        ''' </summary>
        Public TotalSize As Long

        ''' <summary>
        ''' Indicates the volume label of a drive.
        ''' </summary>
        Public VolumeLabel As String

        ''' <summary>
        ''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct.
        ''' </summary>
        ''' <param name="e">The e.</param>
        Public Sub New(ByVal e As DriveInfo)

            Name = e.Name

            Select Case e.IsReady

                Case True ' Drive is formatted and ready.
                    IsReady = True
                    DriveFormat = e.DriveFormat
                    DriveType = e.DriveType
                    RootDirectory = e.RootDirectory.FullName
                    VolumeLabel = e.VolumeLabel
                    TotalSize = e.TotalSize
                    TotalFreeSpace = e.TotalFreeSpace
                    AvailableFreeSpace = e.AvailableFreeSpace

                Case False ' Drive is not formatted so can't retrieve data.
                    IsReady = False
                    DriveFormat = Nothing
                    DriveType = e.DriveType
                    RootDirectory = e.RootDirectory.FullName
                    VolumeLabel = Nothing
                    TotalSize = 0
                    TotalFreeSpace = 0
                    AvailableFreeSpace = 0

            End Select ' e.IsReady

        End Sub

    End Structure

    ''' <summary>
    ''' Contains information about a logical volume.
    ''' For more info, see here:
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx
    ''' </summary>
    <StructLayout(LayoutKind.Sequential)>
    Private Structure DEV_BROADCAST_VOLUME

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

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

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

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

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

    End Structure

#End Region

#Region " Constructor "

    ''' <summary>
    ''' Initializes a new instance of this class.
    ''' </summary>
    ''' <param name="form">The form to assign.</param>
    Public Sub New(ByVal form As Form)

        ' Assign the Formulary.
        Me.form = form

    End Sub

#End Region

#Region " Event Handlers "

    ''' <summary>
    ''' Assign the handle of the target Form to this NativeWindow,
    ''' necessary to override target Form's WndProc.
    ''' </summary>
    Private Sub SetFormHandle() _
    Handles form.HandleCreated, form.Load, form.Shown

        If Not MyBase.Handle.Equals(Me.form.Handle) Then
            MyBase.AssignHandle(Me.form.Handle)
        End If

    End Sub

    ''' <summary>
    ''' Releases the Handle.
    ''' </summary>
    Private Sub OnHandleDestroyed() _
    Handles form.HandleDestroyed

        MyBase.ReleaseHandle()

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object.
    ''' </summary>
    ''' <param name="Device">
    ''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask.
    ''' </param>
    ''' <returns>System.Char.</returns>
    Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char

        Dim DriveLetters As Char() =
            {
            "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z"
            }

        Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask))

        For X As Integer = 0 To DeviceID.Length

            If DeviceID(X) Then
                Return DriveLetters(X)
            End If

        Next X

        Return Nothing

    End Function

#End Region

#Region " WndProc"

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

        Select Case m.Msg

            Case DeviceEvents.Change ' The hardware has changed.

                ' Transform the LParam pointer into the data structure.
                Dim CurrentWDrive As DEV_BROADCAST_VOLUME =
                    CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)

                Select Case m.WParam.ToInt32

                    Case DeviceEvents.Arrival ' The device is connected.

                        ' Get the drive letter of the connected device.
                        DriveLetter = GetDriveLetter(CurrentWDrive)

                        ' Get the drive information of the connected device.
                        CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))

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

                            ' Inform that the device is connected by raising the 'DriveConnected' event.
                            RaiseEvent DriveInserted(Me, CurrentDrive)

                            ' Add the connected device to the dictionary, to retrieve info.
                            If Not CurrentDrives.ContainsKey(DriveLetter) Then

                                CurrentDrives.Add(DriveLetter, CurrentDrive)

                            End If ' Not CurrentDrives.ContainsKey(DriveLetter)

                        End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume

                    Case DeviceEvents.QueryRemove ' The device is preparing to be removed.

                        ' Get the letter of the current device being removed.
                        DriveLetter = GetDriveLetter(CurrentWDrive)

                        ' If the current device being removed is not in the dictionary then...
                        If Not CurrentDrives.ContainsKey(DriveLetter) Then

                            ' Get the device information of the current device being removed.
                            CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))

                            ' Add the current device to the dictionary,
                            ' to retrieve info before lost it after fully-removal.
                            CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter)))

                        End If ' Not CurrentDrives.ContainsKey(DriveLetter)

                    Case DeviceEvents.RemoveComplete

                        ' Get the letter of the removed device.
                        DriveLetter = GetDriveLetter(CurrentWDrive)

                        ' Inform that the device is disconnected by raising the 'DriveDisconnected' event.
                        RaiseEvent DriveRemoved(Me, CurrentDrive)

                        ' If the removed device is in the dictionary then...
                        If CurrentDrives.ContainsKey(DriveLetter) Then

                            ' Remove the device from the dictionary.
                            CurrentDrives.Remove(DriveLetter)

                        End If ' CurrentDrives.ContainsKey(DriveLetter)

                End Select ' m.WParam.ToInt32

        End Select ' m.Msg

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

    End Sub

#End Region

#Region " Hidden methods "

    ' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
    ' NOTE: The methods can be re-enabled at any-time if needed.

    ''' <summary>
    ''' Assigns a handle to this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub AssignHandle()
    End Sub

    ''' <summary>
    ''' Creates a window and its handle with the specified creation parameters.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub CreateHandle()
    End Sub

    ''' <summary>
    ''' Creates an object that contains all the relevant information required
    ''' to generate a proxy used to communicate with a remote object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub CreateObjRef()
    End Sub

    ''' <summary>
    ''' Invokes the default window procedure associated with this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub DefWndProc()
    End Sub

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

    ''' <summary>
    ''' Determines whether the specified object is equal to the current object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub Equals()
    End Sub

    ''' <summary>
    ''' Serves as the default hash function.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub GetHashCode()
    End Sub

    ''' <summary>
    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub GetLifetimeService()
    End Sub

    ''' <summary>
    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub InitializeLifetimeService()
    End Sub

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

    ''' <summary>
    ''' Gets the handle for this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Property Handle()

#End Region

#Region " IDisposable "

    ''' <summary>
    ''' To detect redundant calls when disposing.
    ''' </summary>
    Private IsDisposed As Boolean = False

    ''' <summary>
    ''' Prevent calls to methods after disposing.
    ''' </summary>
    ''' <exception cref="System.ObjectDisposedException"></exception>
    Private Sub DisposedCheck()
        If Me.IsDisposed Then
            Throw New ObjectDisposedException(Me.GetType().FullName)
        End If
    End Sub

    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' </summary>
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    ''' <summary>
    ''' Releases unmanaged and - optionally - managed resources.
    ''' </summary>
    ''' <param name="IsDisposing">
    ''' <c>true</c> to release both managed and unmanaged resources;
    ''' <c>false</c> to release only unmanaged resources.
    ''' </param>
    Protected Sub Dispose(ByVal IsDisposing As Boolean)

        If Not Me.IsDisposed Then

            If IsDisposing Then
                Me.form = Nothing
                MyBase.ReleaseHandle()
                MyBase.DestroyHandle()
            End If

        End If

        Me.IsDisposed = True

    End Sub

#End Region

End Class








Eleкtro

         [RichTextBox] Colorize Words

         Busca coincidencias de texto y las colorea.


Código (vbnet) [Seleccionar]
    ' Colorize Words
    ' ( By Elektro )
    '
    ' Usage Examples:
    '
    ' ColorizeWord(RichTextBox1, "Hello", True,
    '              Color.Red, Color.Black,
    '              New Font(RichTextBox1.Font.FontFamily, RichTextBox1.Font.Size, FontStyle.Italic))
    '
    ' ColorizeWords(RichTextBox1, {"Hello", "[0-9]"}, IgnoreCase:=False,
    '               ForeColor:=Color.Red, BackColor:=Nothing, Font:=Nothing)

    ''' <summary>
    ''' Find a word on a RichTextBox and colorizes each match.
    ''' </summary>
    ''' <param name="RichTextBox">Indicates the RichTextBox.</param>
    ''' <param name="Word">Indicates the word to colorize.</param>
    ''' <param name="IgnoreCase">Indicates the ignore case.</param>
    ''' <param name="ForeColor">Indicates the text color.</param>
    ''' <param name="BackColor">Indicates the background color.</param>
    ''' <param name="Font">Indicates the text font.</param>
    ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
    Private Function ColorizeWord(ByVal [RichTextBox] As RichTextBox,
                                  ByVal Word As String,
                                  Optional ByVal IgnoreCase As Boolean = False,
                                  Optional ByVal ForeColor As Color = Nothing,
                                  Optional ByVal BackColor As Color = Nothing,
                                  Optional ByVal [Font] As Font = Nothing) As Boolean

        ' Find all the word matches.
        Dim Matches As System.Text.RegularExpressions.MatchCollection =
            System.Text.RegularExpressions.Regex.Matches([RichTextBox].Text, Word,
                                                         If(IgnoreCase,
                                                            System.Text.RegularExpressions.RegexOptions.IgnoreCase,
                                                            System.Text.RegularExpressions.RegexOptions.None))

        ' If no matches then return.
        If Not Matches.Count <> 0 Then
            Return False
        End If

        ' Set the passed Parameter values.
        If ForeColor.Equals(Nothing) Then ForeColor = [RichTextBox].ForeColor
        If BackColor.Equals(Nothing) Then BackColor = [RichTextBox].BackColor
        If [Font] Is Nothing Then [Font] = [RichTextBox].Font

        ' Store the current caret position to restore it at the end.
        Dim CaretPosition As Integer = [RichTextBox].SelectionStart

        ' Suspend the control layout to work quicklly.
        [RichTextBox].SuspendLayout()

        ' Colorize each match.
        For Each Match As System.Text.RegularExpressions.Match In Matches

            [RichTextBox].Select(Match.Index, Match.Length)
            [RichTextBox].SelectionColor = ForeColor
            [RichTextBox].SelectionBackColor = BackColor
            [RichTextBox].SelectionFont = [Font]

        Next Match

        ' Restore the caret position.
        [RichTextBox].Select(CaretPosition, 0)

        ' Restore the control layout.
        [RichTextBox].ResumeLayout()

        ' Return successfully
        Return True

    End Function

    ''' <summary>
    ''' Find multiple words on a RichTextBox and colorizes each match.
    ''' </summary>
    ''' <param name="RichTextBox">Indicates the RichTextBox.</param>
    ''' <param name="Words">Indicates the words to colorize.</param>
    ''' <param name="IgnoreCase">Indicates the ignore case.</param>
    ''' <param name="ForeColor">Indicates the text color.</param>
    ''' <param name="BackColor">Indicates the background color.</param>
    ''' <param name="Font">Indicates the text font.</param>
    ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
    Private Function ColorizeWords(ByVal [RichTextBox] As RichTextBox,
                                   ByVal Words As String(),
                                   Optional ByVal IgnoreCase As Boolean = False,
                                   Optional ByVal ForeColor As Color = Nothing,
                                   Optional ByVal BackColor As Color = Nothing,
                                   Optional ByVal [Font] As Font = Nothing) As Boolean

        Dim Success As Boolean = False

        For Each Word As String In Words
            Success += ColorizeWord([RichTextBox], Word, IgnoreCase, ForeColor, BackColor, [Font])
        Next Word

        Return Success

    End Function





[ListView] Remove Duplicates

Elimina Items duplicados de un Listview, comparando un índice de subitem específico.

Código (vbnet) [Seleccionar]
    ' Remove ListView Duplicates
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' Dim Items As ListView.ListViewItemCollection = New ListView.ListViewItemCollection(ListView1)
    ' RemoveListViewDuplicates(Items, 0)   
    '
    ''' <summary>
    ''' Removes duplicated items from a Listview.
    ''' </summary>
    ''' <param name="Items">
    ''' Indicates the items collection.
    ''' </param>
    ''' <param name="SubitemCompare">
    ''' Indicates the subitem column to compare duplicates.
    ''' </param>
    Private Sub RemoveListViewDuplicates(ByVal Items As ListView.ListViewItemCollection,
                                         ByVal SubitemCompare As Integer)

        ' Suspend the layout on the Control that owns the Items collection.
        Items.Item(0).ListView.SuspendLayout()

        ' Get the duplicated Items.
        Dim Duplicates As ListViewItem() =
            Items.Cast(Of ListViewItem)().
            GroupBy(Function(Item As ListViewItem) Item.SubItems(SubitemCompare).Text).
            Where(Function(g As IGrouping(Of String, ListViewItem)) g.Count <> 1).
            SelectMany(Function(g As IGrouping(Of String, ListViewItem)) g).
            Skip(1).
            ToArray()

        ' Delete the duplicated Items.
        For Each Item As ListViewItem In Duplicates
            Items.Remove(Item)
        Next Item

        ' Resume the layout on the Control that owns the Items collection.
        Items.Item(0).ListView.ResumeLayout()

        Duplicates = Nothing

    End Sub





Formatea un dispositivo

Código (vbnet) [Seleccionar]
    ' Format Drive
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' FormatDrive("Z")
    ' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False))

    ''' <summary>
    ''' Indicates the possible HardDisk filesystem's for Windows OS.
    ''' </summary>
    Public Enum DriveFileSystem As Integer

        ' NOTE:
        ' *****
        ' The numeric values just indicates the max harddisk volume-label character-length for each filesystem.

        ''' <summary>
        ''' NTFS FileSystem.
        ''' </summary>
        NTFS = 32

        ''' <summary>
        ''' FAT16 FileSystem.
        ''' </summary>
        FAT16 = 11

        ''' <summary>
        ''' FAT32 FileSystem.
        ''' </summary>
        FAT32 = FAT16

    End Enum

    ''' <summary>
    ''' Formats a drive.
    ''' For more info see here:
    ''' http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx
    ''' </summary>
    ''' <param name="DriveLetter">
    ''' Indicates the drive letter to format.
    ''' </param>
    ''' <param name="FileSystem">
    ''' Indicates the filesystem format to use for this volume.
    ''' The default is "NTFS".
    ''' </param>
    ''' <param name="QuickFormat">
    ''' If set to <c>true</c>, formats the volume with a quick format by removing files from the disk
    ''' without scanning the disk for bad sectors.
    ''' Use this option only if the disk has been previously formatted,
    ''' and you know that the disk is not damaged.
    ''' The default is <c>true</c>.
    ''' </param>
    ''' <param name="ClusterSize">
    ''' Disk allocation unit size—cluster size.
    ''' All of the filesystems organizes the hard disk based on cluster size,
    ''' which represents the smallest amount of disk space that can be allocated to hold a file.
    ''' The smaller the cluster size you use, the more efficiently your disk stores information.
    ''' If no cluster size is specified during format, Windows picks defaults based on the size of the volume.
    ''' These defaults have been selected to reduce the amount of space lost and to reduce fragmentation.
    ''' For general use, the default settings are strongly recommended.
    ''' </param>
    ''' <param name="VolumeLabel">
    ''' Indicates the Label to use for the new volume.
    ''' The volume label can contain up to 11 characters for FAT16 and FAT32 volumes,
    ''' and up to 32 characters for NTFS filesystem volumes.
    ''' </param>
    ''' <param name="EnableCompression">Not implemented.</param>
    ''' <returns>
    ''' 0  = Success.
    ''' 1  = Unsupported file system.
    ''' 2  = Incompatible media in drive.
    ''' 3  = Access denied.
    ''' 4  = Call canceled.
    ''' 5  = Call cancellation request too late.
    ''' 6  = Volume write protected.
    ''' 7  = Volume lock failed.
    ''' 8  = Unable to quick format.
    ''' 9  = Input/Output (I/O) error.
    ''' 10 = Invalid volume label.
    ''' 11 = No media in drive.
    ''' 12 = Volume is too small.
    ''' 13 = Volume is too large.
    ''' 14 = Volume is not mounted.
    ''' 15 = Cluster size is too small.
    ''' 16 = Cluster size is too large.
    ''' 17 = Cluster size is beyond 32 bits.
    ''' 18 = Unknown error.
    ''' </returns>
    Public Function FormatDrive(ByVal DriveLetter As Char,
                                Optional ByVal FileSystem As DriveFileSystem = DriveFileSystem.NTFS,
                                Optional ByVal QuickFormat As Boolean = True,
                                Optional ByVal ClusterSize As Integer = Nothing,
                                Optional ByVal VolumeLabel As String = Nothing,
                                Optional ByVal EnableCompression As Boolean = False) As Integer

        ' Volume-label error check.
        If Not String.IsNullOrEmpty(VolumeLabel) Then

            If VolumeLabel.Length > FileSystem Then
                Throw New Exception(String.Format("Volume label for '{0}' filesystem can't be larger than '{1}' characters.",
                                                  FileSystem.ToString, CStr(FileSystem)))
            End If

        End If

        Dim Query As String = String.Format("select * from Win32_Volume WHERE DriveLetter = '{0}:'",
                                            Convert.ToString(DriveLetter))

        Using WMI As New ManagementObjectSearcher(Query)

            Return CInt(WMI.[Get].Cast(Of ManagementObject).First.
                        InvokeMethod("Format",
                                     New Object() {FileSystem, QuickFormat, ClusterSize, VolumeLabel, EnableCompression}))

        End Using

        Return 18 ' Unknown error.

    End Function








Eleкtro

#379
Una helper class para las librerías 'SautinSoft.HtmlToRtf' y 'SautinSoft.RtfToHtml', como sus nombres indican, para convertir distintos documentos entre HTML, RTF, DOC y TXT.

La verdad es que se consiguen muy buenos resultados y tiene muchas opciones de customización, esta librería es mucho mejor que la que posteé hace unas semanas del cual también hice un ayudante.

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

#Region " Example Usages "

' ' HTML 2 RTF
' RichTextBox1.Rtf = HTMLConverter.Html2Rtf(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
'                                           SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
'                                           DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
'                                           "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
'                                           DocumentConverter.PageOrientation.Auto, "Header", "Footer",
'                                           SautinSoft.HtmlToRtf.eImageCompatible.WordPad)


' ' HTML 2 TXT
' RichTextBox1.Text = HTMLConverter.Html2Txt(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
'                                            SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
'                                            DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
'                                            "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
'                                            DocumentConverter.PageOrientation.Auto, "Header", "Footer",
'                                            SautinSoft.HtmlToRtf.eImageCompatible.WordPad)


' ' HTML 2 DOC
' Dim MSDocText As String = HTMLConverter.Html2Doc(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
'                                                  SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
'                                                  DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
'                                                  "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
'                                                  DocumentConverter.PageOrientation.Auto, "Header", "Footer",
'                                                  SautinSoft.HtmlToRtf.eImageCompatible.MSWord)
' IO.File.WriteAllText("C:\DocFile.doc", MSDocText, System.Text.Encoding.Default)


' ' TXT 2 RTF
' RichTextBox1.Rtf = DocumentConverter.Txt2Rtf("Hello World!",
'                                              SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
'                                              DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
'                                              "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
'                                              DocumentConverter.PageOrientation.Auto, "Header", "Footer",
'                                              SautinSoft.HtmlToRtf.eImageCompatible.WordPad)


' ' TXT 2 DOC
' Dim MSDocText As String = DocumentConverter.Txt2Doc("Hello World!",
'                                                     SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
'                                                     DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
'                                                     "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
'                                                     DocumentConverter.PageOrientation.Auto, "Header", "Footer",
'                                                     SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
' IO.File.WriteAllText("C:\DocFile.doc", MSDocText, System.Text.Encoding.Default)


' ' RTF 2 HTML
' Dim HTMLString As String =
'     DocumentConverter.Rtf2Html(IO.File.ReadAllText("C:\File.rtf"),
'                                SautinSoft.RtfToHtml.eOutputFormat.XHTML_10,
'                                SautinSoft.RtfToHtml.eEncoding.UTF_8,
'                                True, "C:\")
'
' IO.File.WriteAllText("C:\File.html", HTMLString)
' Process.Start("C:\File.html")

#End Region

#Region " Imports "

Imports SautinSoft
Imports System.Reflection

#End Region

''' <summary>
''' Performs HTML document convertions to other document formats.
''' </summary>
Public Class DocumentConverter

#Region " Enumerations "

   ''' <summary>
   ''' Indicates the resulting PageSize.
   ''' </summary>
   Public Enum PageSize
       Auto
       A3
       A4
       A5
       A6
       B5Iso
       B5Jis
       B6
       Executive
       Folio
       Legal
       Letter
       Oficio2
       Statement
   End Enum

   ''' <summary>
   ''' Indicates the resulting PageOrientation.
   ''' </summary>
   Public Enum PageOrientation
       Auto
       Landscape
       Portrait
   End Enum

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Converts a document using 'SautinSoft.HtmlToRtf' library.
   ''' </summary>
   ''' <param name="Text">
   ''' Indicates the text to convert.
   ''' </param>
   ''' <param name="OutputFormat">
   ''' Indicates the output document format.
   ''' </param>
   ''' <param name="TextEncoding">
   ''' Indicates the text encoding.
   ''' </param>
   ''' <param name="PreservePageBreaks">
   ''' If set to <c>true</c> page breaks are preserved on the conversion.
   ''' </param>
   ''' <param name="PageSize">
   ''' Indicates the page size.
   ''' </param>
   ''' <param name="Pagenumbers">
   ''' Indicates the page numbers.
   ''' </param>
   ''' <param name="PagenumbersFormat">
   ''' Indicates the page numbers format.
   ''' </param>
   ''' <param name="PageAlignment">
   ''' Indicates the page alignment.
   ''' </param>
   ''' <param name="PageOrientation">
   ''' Indicates the page orientation.
   ''' </param>
   ''' <param name="PageHeader">
   ''' Indicates the page header text.
   ''' </param>
   ''' <param name="PageFooter">
   ''' Indicates the page footer text.
   ''' </param>
   ''' <param name="ImageCompatibility">
   ''' Indicates the image compatibility if the document contains images.
   ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
   ''' Microsoft Word can show images in jpeg, png, etc.
   ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
   ''' </param>
   ''' <returns>System.String.</returns>
   Private Shared Function HtmlToRtfConvert(ByVal [Text] As String,
                                            ByVal InputFormat As HtmlToRtf.eInputFormat,
                                            ByVal OutputFormat As HtmlToRtf.eOutputFormat,
                                            Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
                                            Optional ByVal PreservePageBreaks As Boolean = False,
                                            Optional ByVal PageSize As PageSize = PageSize.Auto,
                                            Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
                                            Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
                                            Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
                                            Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
                                            Optional ByVal PageHeader As String = Nothing,
                                            Optional ByVal PageFooter As String = Nothing,
                                            Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad) As String

       ' Set the PageSize.
       Dim PerformPageSize As New HtmlToRtf.CPageStyle.CPageSize()
       Dim PageSizeMethod As MethodInfo = PerformPageSize.GetType().GetMethod(PageSize.ToString())

       ' Set the PageOrientation.
       Dim PerformPageOrientation As New HtmlToRtf.CPageStyle.CPageOrientation
       Dim PageOrientationMethod As MethodInfo = PerformPageOrientation.GetType().GetMethod(PageOrientation.ToString())

       ' Call the PageSize method.
       If Not PageSizeMethod Is Nothing Then
           PageSizeMethod.Invoke(PerformPageSize, Nothing)
       Else
           Throw New Exception(String.Format("PageSize method {0} not found.", PageSize.ToString))
       End If

       ' Call the PageOrientation method.
       If Not PageOrientationMethod Is Nothing Then
           PageOrientationMethod.Invoke(PerformPageOrientation, Nothing)
       Else
           Throw New Exception(String.Format("PageOrientation method {0} not found.", PageOrientation.ToString))
       End If

       ' Instance a new document converter.
       Dim Converter As New HtmlToRtf

       ' Customize the conversion options.
       With Converter

           .Serial = "123456789012"

           .InputFormat = InputFormat
           .OutputFormat = OutputFormat
           .Encoding = TextEncoding
           .PreservePageBreaks = PreservePageBreaks
           .ImageCompatible = ImageCompatibility
           .PageAlignment = PageAlignment
           .PageNumbers = Pagenumbers
           .PageNumbersFormat = PagenumbersFormat
           .PageStyle.PageSize = PerformPageSize
           .PageStyle.PageOrientation = PerformPageOrientation
           If Not String.IsNullOrEmpty(PageHeader) Then .PageStyle.PageHeader.Text(PageHeader)
           If Not String.IsNullOrEmpty(PageFooter) Then .PageStyle.PageFooter.Text(PageFooter)

       End With

       ' Convert it.
       Return Converter.ConvertString([Text])

   End Function

   ''' <summary>
   ''' Converts a document using 'SautinSoft.RtfToHtml' library.
   ''' </summary>
   ''' <param name="Text">
   ''' Indicates the text to convert.
   ''' </param>
   ''' <param name="OutputFormat">
   ''' Indicates the output HTML format.
   ''' </param>
   ''' <param name="TextEncoding">
   ''' Indicates the text encoding.
   ''' </param>
   ''' <param name="SaveImagesToDisk">
   ''' If set to <c>true</c>, converted images are saved to a directory on hard drive.
   ''' </param>
   ''' <param name="ImageFolder">
   ''' If 'SaveImagesToDisk' parameter is set to 'True', indicates the image directory to save the images.
   ''' The directory must exist.
   ''' </param>
   ''' <returns>System.String.</returns>
   Private Shared Function RtfToHtmlConvert(ByVal [Text] As String,
                                            Optional ByVal OutputFormat As RtfToHtml.eOutputFormat = RtfToHtml.eOutputFormat.XHTML_10,
                                            Optional ByVal TextEncoding As RtfToHtml.eEncoding = RtfToHtml.eEncoding.UTF_8,
                                            Optional ByVal SaveImagesToDisk As Boolean = False,
                                            Optional ByVal ImageFolder As String = "C:\") As String


       ' Instance a new document converter.
       Dim Converter As New RtfToHtml

       ' Customize the conversion options.
       With Converter

           .Serial = "123456789012"

           .OutputFormat = OutputFormat
           .Encoding = TextEncoding
           .ImageStyle.IncludeImageInHtml = Not SaveImagesToDisk
           .ImageStyle.ImageFolder = ImageFolder ' This folder must exist to save the converted images.
           .ImageStyle.ImageSubFolder = "Pictures" ' This subfolder will be created by the component to save the images.
           .ImageStyle.ImageFileName = "picture" ' Pattern name for converted images. (Ex: 'Picture1.png')

       End With

       ' Convert it.
       Return Converter.ConvertString([Text])

   End Function

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Converts HTML text to DOC (Microsoft Word).
   ''' </summary>
   ''' <param name="HtmlText">
   ''' Indicates the HTML text to convert.
   ''' </param>
   ''' <param name="TextEncoding">
   ''' Indicates the text encoding.
   ''' </param>
   ''' <param name="PreservePageBreaks">
   ''' If set to <c>true</c> page breaks are preserved on the conversion.
   ''' </param>
   ''' <param name="PageSize">
   ''' Indicates the page size.
   ''' </param>
   ''' <param name="Pagenumbers">
   ''' Indicates the page numbers.
   ''' </param>
   ''' <param name="PagenumbersFormat">
   ''' Indicates the page numbers format.
   ''' </param>
   ''' <param name="PageAlignment">
   ''' Indicates the page alignment.
   ''' </param>
   ''' <param name="PageOrientation">
   ''' Indicates the page orientation.
   ''' </param>
   ''' <param name="PageHeader">
   ''' Indicates the page header text.
   ''' </param>
   ''' <param name="PageFooter">
   ''' Indicates the page footer text.
   ''' </param>
   ''' <param name="ImageCompatibility">
   ''' Indicates the image compatibility if the document contains images.
   ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
   ''' Microsoft Word can show images in jpeg, png, etc.
   ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
   ''' </param>
   ''' <returns>System.String.</returns>
   Public Shared Function Html2Doc(ByVal HtmlText As String,
                                   Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
                                   Optional ByVal PreservePageBreaks As Boolean = False,
                                   Optional ByVal PageSize As PageSize = PageSize.Auto,
                                   Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
                                   Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
                                   Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
                                   Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
                                   Optional ByVal PageHeader As String = Nothing,
                                   Optional ByVal PageFooter As String = Nothing,
                                   Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
                                   ) As String

       Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.Doc, TextEncoding,
                      PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
                      PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)

   End Function

   ''' <summary>
   ''' Converts HTML text to RTF (Rich Text).
   ''' </summary>
   ''' <param name="HtmlText">
   ''' Indicates the HTML text to convert.
   ''' </param>
   ''' <param name="TextEncoding">
   ''' Indicates the text encoding.
   ''' </param>
   ''' <param name="PreservePageBreaks">
   ''' If set to <c>true</c> page breaks are preserved on the conversion.
   ''' </param>
   ''' <param name="PageSize">
   ''' Indicates the page size.
   ''' </param>
   ''' <param name="Pagenumbers">
   ''' Indicates the page numbers.
   ''' </param>
   ''' <param name="PagenumbersFormat">
   ''' Indicates the page numbers format.
   ''' </param>
   ''' <param name="PageAlignment">
   ''' Indicates the page alignment.
   ''' </param>
   ''' <param name="PageOrientation">
   ''' Indicates the page orientation.
   ''' </param>
   ''' <param name="PageHeader">
   ''' Indicates the page header text.
   ''' </param>
   ''' <param name="PageFooter">
   ''' Indicates the page footer text.
   ''' </param>
   ''' <param name="ImageCompatibility">
   ''' Indicates the image compatibility if the document contains images.
   ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
   ''' Microsoft Word can show images in jpeg, png, etc.
   ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
   ''' </param>
   ''' <returns>System.String.</returns>
   Public Shared Function Html2Rtf(ByVal HtmlText As String,
                                   Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
                                   Optional ByVal PreservePageBreaks As Boolean = False,
                                   Optional ByVal PageSize As PageSize = PageSize.Auto,
                                   Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
                                   Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
                                   Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
                                   Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
                                   Optional ByVal PageHeader As String = Nothing,
                                   Optional ByVal PageFooter As String = Nothing,
                                   Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
                                   ) As String

       Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.Rtf, TextEncoding,
                      PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
                      PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)

   End Function

   ''' <summary>
   ''' Converts HTML text to TXT (Plain Text).
   ''' </summary>
   ''' <param name="HtmlText">
   ''' Indicates the HTML text to convert.
   ''' </param>
   ''' <param name="TextEncoding">
   ''' Indicates the text encoding.
   ''' </param>
   ''' <param name="PreservePageBreaks">
   ''' If set to <c>true</c> page breaks are preserved on the conversion.
   ''' </param>
   ''' <param name="PageSize">
   ''' Indicates the page size.
   ''' </param>
   ''' <param name="Pagenumbers">
   ''' Indicates the page numbers.
   ''' </param>
   ''' <param name="PagenumbersFormat">
   ''' Indicates the page numbers format.
   ''' </param>
   ''' <param name="PageAlignment">
   ''' Indicates the page alignment.
   ''' </param>
   ''' <param name="PageOrientation">
   ''' Indicates the page orientation.
   ''' </param>
   ''' <param name="PageHeader">
   ''' Indicates the page header text.
   ''' </param>
   ''' <param name="PageFooter">
   ''' Indicates the page footer text.
   ''' </param>
   ''' <param name="ImageCompatibility">
   ''' Indicates the image compatibility if the document contains images.
   ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
   ''' Microsoft Word can show images in jpeg, png, etc.
   ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
   ''' </param>
   ''' <returns>System.String.</returns>
   Public Shared Function Html2Txt(ByVal HtmlText As String,
                                   Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
                                   Optional ByVal PreservePageBreaks As Boolean = False,
                                   Optional ByVal PageSize As PageSize = PageSize.Auto,
                                   Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
                                   Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
                                   Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
                                   Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
                                   Optional ByVal PageHeader As String = Nothing,
                                   Optional ByVal PageFooter As String = Nothing,
                                   Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
                                   ) As String

       Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.TextAnsi, TextEncoding,
                      PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
                      PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)

   End Function

   ''' <summary>
   ''' Converts TXT to DOC (Microsoft Word).
   ''' </summary>
   ''' <param name="Text">
   ''' Indicates the plain text to convert.
   ''' </param>
   ''' <param name="TextEncoding">
   ''' Indicates the text encoding.
   ''' </param>
   ''' <param name="PreservePageBreaks">
   ''' If set to <c>true</c> page breaks are preserved on the conversion.
   ''' </param>
   ''' <param name="PageSize">
   ''' Indicates the page size.
   ''' </param>
   ''' <param name="Pagenumbers">
   ''' Indicates the page numbers.
   ''' </param>
   ''' <param name="PagenumbersFormat">
   ''' Indicates the page numbers format.
   ''' </param>
   ''' <param name="PageAlignment">
   ''' Indicates the page alignment.
   ''' </param>
   ''' <param name="PageOrientation">
   ''' Indicates the page orientation.
   ''' </param>
   ''' <param name="PageHeader">
   ''' Indicates the page header text.
   ''' </param>
   ''' <param name="PageFooter">
   ''' Indicates the page footer text.
   ''' </param>
   ''' <param name="ImageCompatibility">
   ''' Indicates the image compatibility if the document contains images.
   ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
   ''' Microsoft Word can show images in jpeg, png, etc.
   ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
   ''' </param>
   ''' <returns>System.String.</returns>
   Public Shared Function Txt2Doc(ByVal [Text] As String,
                                  Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
                                  Optional ByVal PreservePageBreaks As Boolean = False,
                                  Optional ByVal PageSize As PageSize = PageSize.Auto,
                                  Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
                                  Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
                                  Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
                                  Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
                                  Optional ByVal PageHeader As String = Nothing,
                                  Optional ByVal PageFooter As String = Nothing,
                                  Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
                                  ) As String

       Return HtmlToRtfConvert([Text], HtmlToRtf.eInputFormat.Text, HtmlToRtf.eOutputFormat.Doc, TextEncoding,
                      PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
                      PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)

   End Function

   ''' <summary>
   ''' Converts TXT to RTF (Rich Text).
   ''' </summary>
   ''' <param name="Text">
   ''' Indicates the plain text to convert.
   ''' </param>
   ''' <param name="TextEncoding">
   ''' Indicates the text encoding.
   ''' </param>
   ''' <param name="PreservePageBreaks">
   ''' If set to <c>true</c> page breaks are preserved on the conversion.
   ''' </param>
   ''' <param name="PageSize">
   ''' Indicates the page size.
   ''' </param>
   ''' <param name="Pagenumbers">
   ''' Indicates the page numbers.
   ''' </param>
   ''' <param name="PagenumbersFormat">
   ''' Indicates the page numbers format.
   ''' </param>
   ''' <param name="PageAlignment">
   ''' Indicates the page alignment.
   ''' </param>
   ''' <param name="PageOrientation">
   ''' Indicates the page orientation.
   ''' </param>
   ''' <param name="PageHeader">
   ''' Indicates the page header text.
   ''' </param>
   ''' <param name="PageFooter">
   ''' Indicates the page footer text.
   ''' </param>
   ''' <param name="ImageCompatibility">
   ''' Indicates the image compatibility if the document contains images.
   ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
   ''' Microsoft Word can show images in jpeg, png, etc.
   ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
   ''' </param>
   ''' <returns>System.String.</returns>
   Public Shared Function Txt2Rtf(ByVal [Text] As String,
                                  Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
                                  Optional ByVal PreservePageBreaks As Boolean = False,
                                  Optional ByVal PageSize As PageSize = PageSize.Auto,
                                  Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
                                  Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
                                  Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
                                  Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
                                  Optional ByVal PageHeader As String = Nothing,
                                  Optional ByVal PageFooter As String = Nothing,
                                  Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
                                  ) As String

       Return HtmlToRtfConvert([Text], HtmlToRtf.eInputFormat.Text, HtmlToRtf.eOutputFormat.Rtf, TextEncoding,
                      PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
                      PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)

   End Function

   ''' <summary>
   ''' Converts RtF to HtML.
   ''' </summary>
   ''' <param name="RtfText">
   ''' Indicates the rich text to convert.
   ''' </param>
   ''' <param name="OutputFormat">
   ''' Indicates the output HTML format.
   ''' </param>
   ''' <param name="TextEncoding">
   ''' Indicates the text encoding.
   ''' </param>
   ''' <param name="SaveImagesToDisk">
   ''' If set to <c>true</c>, converted images are saved to a directory on hard drive.
   ''' </param>
   ''' <param name="ImageFolder">
   ''' If 'SaveImagesToDisk' parameter is set to 'True', indicates the image directory to save the images.
   ''' The directory must exist.
   ''' </param>
   ''' <returns>System.String.</returns>
   Public Shared Function Rtf2Html(ByVal RtfText As String,
                                   Optional ByVal OutputFormat As RtfToHtml.eOutputFormat = RtfToHtml.eOutputFormat.XHTML_10,
                                   Optional ByVal TextEncoding As RtfToHtml.eEncoding = RtfToHtml.eEncoding.UTF_8,
                                   Optional ByVal SaveImagesToDisk As Boolean = False,
                                   Optional ByVal ImageFolder As String = "C:\") As String

       Return RtfToHtmlConvert(RtFText, OutputFormat, TextEncoding, SaveImagesToDisk, ImageFolder)

   End Function

#End Region

End Class