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

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 6 Visitantes están viendo este tema.
Páginas: 1 ... 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 [38] 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 529,065 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #370 en: 21 Enero 2014, 00:57 am »

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
  1. ' [Rebex.Security] Encrypt-Decrypt File
  2. ' ( By Elektro )
  3. '
  4. ' Instructions:
  5. ' 1. Add a reference to "Rebex.Security.dll"
  6. '
  7. ' Usage Examples:
  8. ' EncryptFile("File.txt", "Encrypted.txt", "Elektro", FileEncryptionAlgorithm.AesXts, False)
  9. ' DecryptFile("Encrypted.txt", "Decrypted.txt", "Elektro", FileEncryptionAlgorithm.AesXts, False)
  10.  
  11.    ''' <summary>
  12.    ''' Encrypts the data of the specified file.
  13.    ''' </summary>
  14.    ''' <param name="InFile">
  15.    ''' Indicates the file to encrypt.
  16.    ''' </param>
  17.    ''' <param name="OutFile">
  18.    ''' Indicates the resulting encrypted output file.
  19.    ''' </param>
  20.    ''' <param name="Password">
  21.    ''' Indicates the password required to decrypt the file when needed.
  22.    ''' </param>
  23.    ''' <param name="Algorithm">
  24.    ''' Indicates the encryption algorithm.
  25.    ''' </param>
  26.    ''' <param name="OverwriteExistingFile">
  27.    ''' If set to <c>true</c> the resulting output file should overwrite any existing file.
  28.    ''' </param>
  29.    ''' <exception cref="System.Security.Cryptography.CryptographicException">
  30.    ''' Unexpected error, the data to encrypt could be corrupted.
  31.    ''' </exception>
  32.    ''' <exception cref="System.InvalidOperationException"></exception>
  33.    Private Sub EncryptFile(ByVal InFile As String,
  34.                            ByVal OutFile As String,
  35.                            ByVal Password As String,
  36.                            Optional ByVal Algorithm As Rebex.Security.FileEncryptionAlgorithm =
  37.                                                                       FileEncryptionAlgorithm.AesXts,
  38.                            Optional ByVal OverwriteExistingFile As Boolean = False)
  39.  
  40.        Dim Encryptor As New FileEncryption()
  41.  
  42.        With Encryptor
  43.  
  44.            .SetPassword(Password)
  45.            .EncryptionAlgorithm = Algorithm
  46.            .OverwriteExistingFile = OverwriteExistingFile
  47.  
  48.        End With
  49.  
  50.        Try
  51.            Encryptor.Encrypt(InFile, OutFile)
  52.  
  53.        Catch ex As Security.Cryptography.CryptographicException
  54.            Throw New Security.Cryptography.CryptographicException(
  55.                "Unexpected error, the data to encrypt could be corrupted.")
  56.  
  57.        Catch ex As InvalidOperationException
  58.            Throw New InvalidOperationException(
  59.               String.Format("The target file '{0}' already exist.", OutFile))
  60.  
  61.        End Try
  62.  
  63.    End Sub
  64.  
  65.    ''' <summary>
  66.    ''' Decrypts the data of the specified file.
  67.    ''' </summary>
  68.    ''' <param name="InFile">
  69.    ''' Indicates the file to decrypt.
  70.    ''' </param>
  71.    ''' <param name="OutFile">
  72.    ''' Indicates the resulting decrypted output file.
  73.    ''' </param>
  74.    ''' <param name="Password">
  75.    ''' Indicates the password to decrypt the File.
  76.    ''' The password should be the same used when encrypted the file.
  77.    ''' </param>
  78.    ''' <param name="Algorithm">
  79.    ''' Indicates the decryption algorithm.
  80.    ''' The algorithm should be the same used when encrypted the file.
  81.    ''' </param>
  82.    ''' <param name="OverwriteExistingFile">
  83.    ''' If set to <c>true</c> the resulting output file should overwrite any existing file.
  84.    ''' </param>
  85.    ''' <exception cref="System.Security.Cryptography.CryptographicException">
  86.    ''' The password, the data to decrypt, or the decryption algorithm are wrong.
  87.    ''' </exception>
  88.    ''' <exception cref="System.InvalidOperationException"></exception>
  89.    Private Sub DecryptFile(ByVal InFile As String,
  90.                            ByVal OutFile As String,
  91.                            ByVal Password As String,
  92.                            Optional ByVal Algorithm As Rebex.Security.FileEncryptionAlgorithm =
  93.                                                                       FileEncryptionAlgorithm.AesXts,
  94.                            Optional ByVal OverwriteExistingFile As Boolean = False)
  95.  
  96.  
  97.        Dim Decryptor As New FileEncryption()
  98.  
  99.        With Decryptor
  100.  
  101.            .SetPassword(Password)
  102.            .EncryptionAlgorithm = Algorithm
  103.            .OverwriteExistingFile = OverwriteExistingFile
  104.  
  105.        End With
  106.  
  107.        Try
  108.            Decryptor.Decrypt(InFile, OutFile)
  109.  
  110.        Catch ex As Security.Cryptography.CryptographicException
  111.            Throw New Security.Cryptography.CryptographicException(
  112.                "The password, the data to decrypt, or the decryption algorithm are wrong.")
  113.  
  114.        Catch ex As InvalidOperationException
  115.            Throw New InvalidOperationException(
  116.               String.Format("The target file '{0}' already exist.", OutFile))
  117.  
  118.        End Try
  119.  
  120.    End Sub


« Última modificación: 21 Enero 2014, 01:01 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #371 en: 22 Enero 2014, 07:03 am »

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):

Código:
' -------
' 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
  1.        Dim [ImageElement] As ImageElement = ImageElement.FromFile("C:\Image.png")
  2.        Dim [TextElement] As New TextElement With {.Text = "Hello World!"}
  3.  
  4.        ImageDrawHelper.Properties.Brightness([ImageElement], 50)
  5.        ImageDrawHelper.Properties.Contrast([ImageElement], 50)
  6.        ImageDrawHelper.Properties.Gamma([ImageElement], 50)
  7.        ImageDrawHelper.Properties.HSL([ImageElement], 50, 50, 50)
  8.        ImageDrawHelper.Properties.Hue([ImageElement], 50)
  9.        ImageDrawHelper.Properties.Opacity([ImageElement], 50)
  10.  
  11.        ImageDrawHelper.Effects.CameraView([ImageElement], 30, 25)
  12.        ImageDrawHelper.Effects.ColorSubstitution([ImageElement], Color.Black, Color.Fuchsia, 10)
  13.        ImageDrawHelper.Effects.ConvertToBlackWhite([ImageElement], DitherMethod.Threshold, 53, False)
  14.        ImageDrawHelper.Effects.ConvertToNegative([ImageElement])
  15.        ImageDrawHelper.Effects.ConvertToSepia([ImageElement])
  16.        ImageDrawHelper.Effects.Crop([ImageElement], 0, 10, 200, 160)
  17.        ImageDrawHelper.Effects.DistortCorners([ImageElement], -20, -20, 200, 0, 250, 180, -30, 200)
  18.        ImageDrawHelper.Effects.DropShadow([ImageElement], 60, Color.Lime, 270, 6, 10)
  19.        ImageDrawHelper.Effects.Fade([ImageElement], FadeShape.Oval, FillType.Gradient, GradientShape.Path)
  20.        ImageDrawHelper.Effects.Feather([ImageElement], 5, FeatherShape.Oval)
  21.        ImageDrawHelper.Effects.Filmstrip([ImageElement], FilmstripOrientation.Vertical, 150, 180, 0, Color.Yellow, 5)
  22.        ImageDrawHelper.Effects.Flip([ImageElement], FlipType.Horizontal)
  23.        ImageDrawHelper.Effects.FocalGrayscale([ImageElement], FocalShape.Oval, FillType.Gradient, GradientShape.Path, Color.FromArgb(0, 255, 255, 255), Color.FromArgb(0, 0, 0))
  24.        ImageDrawHelper.Effects.GaussianBlur([ImageElement], 5)
  25.        ImageDrawHelper.Effects.GlassTable([ImageElement], 50, 25)
  26.        ImageDrawHelper.Effects.GlassTable([ImageElement], 50, 25, ReflectionLocation.Custom, 2, 10)
  27.        ImageDrawHelper.Effects.Glow([ImageElement], Color.Red, 80, 8)
  28.        ImageDrawHelper.Effects.MakeTransparent([ImageElement])
  29.        ImageDrawHelper.Effects.PerspectiveReflection([ImageElement], 270, 50, 50, 150, 0)
  30.        ImageDrawHelper.Effects.PerspectiveView([ImageElement], 25, PerspectiveOrientation.LeftToRight)
  31.        ImageDrawHelper.Effects.Pixelate([ImageElement], 20, 0)
  32.        ImageDrawHelper.Effects.RemoveColor([ImageElement], Color.White, 10, ScanDirection.All)
  33.        ImageDrawHelper.Effects.RemoveTransparency([ImageElement])
  34.        ImageDrawHelper.Effects.Resize([ImageElement], 256, 256, LockAspectRatio.WidthBased, Drawing2D.InterpolationMode.Bicubic)
  35.        ImageDrawHelper.Effects.Rotate([ImageElement], 90, Drawing2D.InterpolationMode.Bicubic)
  36.        ImageDrawHelper.Effects.RoundCorners([ImageElement], Corners.All, 120)
  37.        ImageDrawHelper.Effects.RoundCorners([ImageElement], Corners.All, 20, 10, Color.Red)
  38.        ImageDrawHelper.Effects.Scale([ImageElement], 50, 50, Drawing2D.InterpolationMode.Bicubic)
  39.        ImageDrawHelper.Effects.Sharpen([ImageElement])
  40.        ImageDrawHelper.Effects.Silhouette([ImageElement], Color.RoyalBlue)
  41.        ImageDrawHelper.Effects.Skew([ImageElement], SkewType.Parallelogram, -10, SkewOrientation.Horizontal, True)
  42.        ImageDrawHelper.Effects.Solarize([ImageElement])
  43.        ImageDrawHelper.Effects.Stretch([ImageElement], 90, 150)
  44.        ImageDrawHelper.Effects.Tint([ImageElement], Color.Orange)
  45.  
  46.        PictureBox1.BackgroundImage = [ImageElement].GetOutputImage


« Última modificación: 22 Enero 2014, 07:12 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #372 en: 23 Enero 2014, 00:46 am »

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
  1. ' [Thresher IRC] Bot example
  2. ' (By Elektro)
  3. '
  4. ' Instructions
  5. ' 1. Add a reference to 'Sharkbite.Thresher.dll'.
  6. '
  7. ' Usage Examples:
  8. ' Public  BOT As New IRCBot("irc.freenode.net", "#ircehn", "ElektroBot")
  9.  
  10. #Region " Imports "
  11.  
  12. Imports Sharkbite.Irc
  13.  
  14. #End Region
  15.  
  16. Public Class IRCBot
  17.  
  18. #Region " Members "
  19.  
  20. #Region " Properties "
  21.  
  22.    ''' <summary>
  23.    ''' Indicates the IRC server to connect.
  24.    ''' </summary>
  25.    Private Property Server As String = String.Empty
  26.  
  27.    ''' <summary>
  28.    ''' Indicates the IRC channel to join.
  29.    ''' </summary>
  30.    Private Property Channel As String = String.Empty
  31.  
  32.    ''' <summary>
  33.    ''' Indicates the nickname to use.
  34.    ''' </summary>
  35.    Private Property Nick As String = String.Empty
  36.  
  37. #End Region
  38.  
  39. #Region " Others "
  40.  
  41.    ''' <summary>
  42.    ''' Performs the avaliable Bot commands.
  43.    ''' </summary>
  44.    Public WithEvents BotConnection As Connection
  45.  
  46.    ''' <summary>
  47.    ''' Handles the Bot events.
  48.    ''' </summary>
  49.    Public WithEvents BotListener As Listener
  50.  
  51.    ''' <summary>
  52.    ''' Stores a list of the current users on a channel room.
  53.    ''' </summary>
  54.    Private RoomUserNames As New List(Of String)
  55.  
  56.    ''' <summary>
  57.    ''' Indicates the invoked command arguments.
  58.    ''' </summary>
  59.    Private CommandParts As String() = {String.Empty}
  60.  
  61. #End Region
  62.  
  63. #End Region
  64.  
  65. #Region " Constructor "
  66.  
  67.    ''' <summary>
  68.    ''' Initializes a new instance of the <see cref="IRCBot"/> class.
  69.    ''' </summary>
  70.    ''' <param name="Server">Indicates the IRC server to connect.</param>
  71.    ''' <param name="Channel">Indicates the IRC channel to join.</param>
  72.    ''' <param name="Nick">Indicates the nickname to use.</param>
  73.    Public Sub New(ByVal Server As String,
  74.                   ByVal Channel As String,
  75.                   ByVal Nick As String)
  76.  
  77.        Me.Server = Server
  78.        Me.Channel = Channel
  79.        Me.Nick = Nick
  80.  
  81.        CreateConnection()
  82.  
  83.    End Sub
  84.  
  85. #End Region
  86.  
  87. #Region " Private Methods "
  88.  
  89.    ''' <summary>
  90.    ''' Establishes the first connection to the server.
  91.    ''' </summary>
  92.    Public Sub CreateConnection()
  93.  
  94.        Console.WriteLine(String.Format("[+] Bot started........: '{0}'", DateTime.Now.ToString))
  95.  
  96.        Identd.Start(Me.Nick)
  97.        BotConnection = New Connection(New ConnectionArgs(Me.Nick, Me.Server), False, False)
  98.        BotListener = BotConnection.Listener
  99.  
  100.        Try
  101.            BotConnection.Connect()
  102.            Console.WriteLine(String.Format("[+] Connected to server: '{0}'", Me.Server))
  103.  
  104.        Catch e As Exception
  105.            Console.WriteLine(String.Format("[X] Error during connection process: {0}", e.ToString))
  106.            Identd.Stop()
  107.  
  108.        End Try
  109.  
  110.    End Sub
  111.  
  112.  
  113.    ''' <summary>
  114.    ''' Kicks everybody from the channel room unless the user who invoked the command.
  115.    ''' </summary>
  116.    ''' <param name="UserInvoked">Indicates the user who invoked the command.</param>
  117.    ''' <param name="CommandMessage">Indicates the command message to retrieve the command arguments.</param>
  118.    Private Sub KickEverybody(ByVal UserInvoked As String,
  119.                              ByVal CommandMessage As String)
  120.  
  121.        ' Renew the current nicknames on the channel room.
  122.        BotConnection.Sender.AllNames()
  123.  
  124.        ' Get the Kick Reason from the CommandMessage.
  125.        CommandParts = CommandMessage.Split
  126.  
  127.        Select Case CommandParts.Length
  128.  
  129.            Case Is > 1
  130.                CommandParts = CommandParts.Skip(1).ToArray
  131.  
  132.            Case Else
  133.                BotConnection.Sender.PublicMessage(Me.Channel, String.Format(
  134.                    "[X] Can't process the invoked command, 'KickReason' parameter expected."))
  135.  
  136.                BotConnection.Sender.PublicMessage(Me.Channel, String.Format(
  137.                    "[i] Command Syntax: !KickAll ""Kick Reason"""))
  138.  
  139.                Exit Sub
  140.  
  141.        End Select
  142.  
  143.        ' Kick each users one by one.
  144.        For Each User As String In (From Nick As String
  145.                                    In RoomUserNames
  146.                                    Where Not Nick = UserInvoked _
  147.                                          AndAlso Not Nick = Me.Nick)
  148.  
  149.            BotConnection.Sender.Kick(Me.Channel, String.Join(" ", CommandParts), User)
  150.  
  151.        Next User
  152.  
  153.    End Sub
  154.  
  155.    ''' <summary>
  156.    ''' Kicks the specified user from the channel.
  157.    ''' </summary>
  158.    ''' <param name="CommandMessage">Indicates the command message to retrieve the command arguments.</param>
  159.    Private Sub Kick(ByVal CommandMessage As String)
  160.  
  161.        ' Renew the current nicknames on the channel room.
  162.        BotConnection.Sender.AllNames()
  163.  
  164.        ' Get the user to Kick and the Kick Reason.
  165.        CommandParts = CommandMessage.Split
  166.        Select Case CommandParts.Length
  167.  
  168.            Case Is > 2
  169.                CommandParts = CommandParts.Skip(1).ToArray
  170.  
  171.            Case Is < 2
  172.                BotConnection.Sender.PublicMessage(Me.Channel, String.Format(
  173.                    "[X] Can't process the invoked command, 'NickName' parameter expected."))
  174.  
  175.                BotConnection.Sender.PublicMessage(Me.Channel, String.Format(
  176.                    "[X] Command Syntax: !Kick ""NickName"" ""Kick Reason"""))
  177.  
  178.                Exit Sub
  179.  
  180.        End Select
  181.  
  182.        BotConnection.Sender.Kick(Me.Channel, String.Join(" ", CommandParts.Skip(1)), CommandParts(0))
  183.  
  184.    End Sub
  185.  
  186.  
  187. #End Region
  188.  
  189. #Region " Event Handlers "
  190.  
  191.    ''' <summary>
  192.    ''' Occurs when the Bot joins to a channel.
  193.    ''' </summary>
  194.    Private Sub OnRegistered() Handles BotListener.OnRegistered
  195.  
  196.        Try
  197.            Identd.Stop()
  198.            BotConnection.Sender.Join(Me.Channel)
  199.            Console.WriteLine(String.Format("[+] Channel joined.....: '{0}'", Me.Channel))
  200.  
  201.        Catch e As Exception
  202.            Console.WriteLine(String.Format("[X] Error in 'OnRegistered' Event: {0}", e.Message))
  203.  
  204.        End Try
  205.  
  206.    End Sub
  207.  
  208.    ''' <summary>
  209.    ''' Occurs when an unexpected Bot error happens.
  210.    ''' </summary>
  211.    ''' <param name="code">Indicates the ReplyCode.</param>
  212.    ''' <param name="message">Contains the error message information.</param>
  213.    Private Sub OnError(ByVal code As ReplyCode,
  214.                        ByVal message As String) Handles BotListener.OnError
  215.  
  216.        BotConnection.Sender.PublicMessage(Me.Channel, String.Format("[X] Unexpected Error: {0}", message))
  217.        Console.WriteLine(String.Format("[X] Unexpected Error: {0}", message))
  218.        Debug.WriteLine(String.Format("[X] Unexpected Error: {0}", message))
  219.  
  220.    End Sub
  221.  
  222.    ''' <summary>
  223.    ''' Occurs when a user sends a public message in a channel room.
  224.    ''' </summary>
  225.    ''' <param name="user">Indicates the user who sent the public message.</param>
  226.    ''' <param name="channel">Indicates the channel where the public message was sent.</param>
  227.    ''' <param name="message">Indicates the content of the public message.</param>
  228.    Public Sub OnPublic(ByVal User As UserInfo,
  229.                        ByVal Channel As String,
  230.                        ByVal Message As String) Handles BotListener.OnPublic
  231.  
  232.  
  233.        Select Case True
  234.  
  235.            Case Message.Trim.StartsWith("!KickAll ", StringComparison.OrdinalIgnoreCase)
  236.                KickEverybody(User.Nick, Message)
  237.  
  238.            Case message.Trim.StartsWith("!Kick ", StringComparison.OrdinalIgnoreCase)
  239.                Kick(Message)
  240.  
  241.        End Select
  242.  
  243.    End Sub
  244.  
  245.    ''' <summary>
  246.    ''' Occurs when the Bot invokes one of the methods to retrieve the nicks of a channel.
  247.    ''' For example, the 'Sender.AllNames' method.
  248.    ''' </summary>
  249.    ''' <param name="Channel">Indicates the channel to list the nicks.</param>
  250.    ''' <param name="Nicks">Indicates the nicks of the channel.</param>
  251.    ''' <param name="LastError">Indicates the last command error.</param>
  252.    Private Sub OnNames(ByVal Channel As String,
  253.                        ByVal Nicks() As String,
  254.                        ByVal LastError As Boolean) Handles BotListener.OnNames
  255.  
  256.        If Channel = Me.Channel AndAlso Not RoomUserNames.Count <> 0 Then
  257.  
  258.            RoomUserNames.Clear()
  259.            RoomUserNames.AddRange((From Name As String In Nicks
  260.                                    Select If(Name.StartsWith("@"), Name.Substring(1), Name)).
  261.                                    ToArray)
  262.  
  263.        End If
  264.  
  265.    End Sub
  266.  
  267.    ''' <summary>
  268.    ''' Occurs when the bot invokes the Kick command.
  269.    ''' </summary>
  270.    ''' <param name="user">Indicates the user who invoked the Kick command.</param>
  271.    ''' <param name="channel">Indicates the channel where the user was kicked.</param>
  272.    ''' <param name="kickee">Indicates the kickee.</param>
  273.    ''' <param name="reason">Indicates the kick reason.</param>
  274.    Private Sub OnKick(ByVal user As UserInfo,
  275.                       ByVal channel As String,
  276.                       ByVal kickee As String,
  277.                       ByVal reason As String) Handles BotListener.OnKick
  278.  
  279.        Console.WriteLine(String.Format("[+]: User kicked: '{0}' From channel: '{1}' With reason: '{2}'.",
  280.                                        user.Nick,
  281.                                        channel,
  282.                                        reason))
  283.  
  284.    End Sub
  285.  
  286. #End Region
  287.  
  288. End Class
« Última modificación: 23 Enero 2014, 01:25 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #373 en: 28 Enero 2014, 18:49 pm »

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

Código
  1. ' ***********************************************************************
  2. ' Assembly : Reg2Bat
  3. ' Author   : Elektro
  4. ' Modified : 01-28-2014
  5. ' ***********************************************************************
  6. ' <copyright file="Reg2Bat.vb" company="Elektro Studios">
  7. '     Copyright (c) Elektro Studios. All rights reserved.
  8. ' </copyright>
  9. ' ***********************************************************************
  10.  
  11. #Region " Usage Examples "
  12.  
  13. ' Dim BatchScript As String = Reg2Bat.Convert("C:\RegistryFile.reg")
  14.  
  15. ' IO.File.WriteAllText("Converted.bat", Reg2Bat.Convert("C:\RegistryFile.reg"), System.Text.Encoding.Default)
  16.  
  17. #End Region
  18.  
  19. #Region " Imports "
  20.  
  21. Imports System.ComponentModel
  22. Imports System.IO
  23. Imports System.Text
  24. Imports System.Text.RegularExpressions
  25.  
  26. #End Region
  27.  
  28. ''' <summary>
  29. ''' Converts a Registry Script to a Batch Script.
  30. ''' </summary>
  31. Public Class Reg2Bat
  32.  
  33. #Region " ReadOnly Strings "
  34.  
  35.    ''' <summary>
  36.    ''' Indicates the resulting Batch-Script Header.
  37.    ''' </summary>
  38.    Private Shared ReadOnly BatchHeader As String =
  39.    <a>:: Converted with Reg2Bat by Elektro
  40.  
  41. @Echo OFF
  42. </a>.Value
  43.  
  44.    ''' <summary>
  45.    ''' Indicates the resulting Batch-Script Footer.
  46.    ''' </summary>
  47.    Private Shared ReadOnly BatchFooter As String =
  48.    <a>
  49. Pause&amp;Exit</a>.Value
  50.  
  51.    ''' <summary>
  52.    ''' Indicates the Batch syntax StringFormat of a Comment-Line command.
  53.    ''' </summary>
  54.    Private Shared ReadOnly BatchStringFormat_Comment As String =
  55.    <a>REM {0}</a>.Value
  56.  
  57.    ''' <summary>
  58.    ''' Indicates the Batch syntax StringFormat of a REG Key-Add command.
  59.    ''' </summary>
  60.    Private Shared ReadOnly BatchStringFormat_KeyAdd As String =
  61.    <a>REG ADD "{0}" /F</a>.Value
  62.  
  63.    ''' <summary>
  64.    ''' Indicates the Batch syntax StringFormat of a REG Key-Delete command.
  65.    ''' </summary>
  66.    Private Shared ReadOnly BatchStringFormat_KeyDelete As String =
  67.    <a>REG DELETE "{0}" /F</a>.Value
  68.  
  69.    ''' <summary>
  70.    ''' Indicates the Batch syntax StringFormat of a REG DefaultValue-Add command.
  71.    ''' </summary>
  72.    Private Shared ReadOnly BatchStringFormat_DefaultValueAdd As String =
  73.    <a>REG ADD "{0}" /V "" /D {1} /F</a>.Value
  74.  
  75.    ''' <summary>
  76.    ''' Indicates the Batch syntax StringFormat of a REG Value-Add REG_SZ command.
  77.    ''' </summary>
  78.    Private Shared ReadOnly BatchStringFormat_ValueAdd_REGSZ As String =
  79.    <a>REG ADD "{0}" /V "{1}" /T "REG_SZ" /D "{2}" /F</a>.Value
  80.  
  81.    ''' <summary>
  82.    ''' Indicates the Batch command StringFormat of a REG Value-Add BINARY command.
  83.    ''' </summary>
  84.    Private Shared ReadOnly BatchStringFormat_ValueAdd_BINARY As String =
  85.    <a>REG ADD "{0}" /V "{1}" /T "REG_BINARY" /D "{2}" /F</a>.Value
  86.  
  87.    ''' <summary>
  88.    ''' Indicates the Batch syntax StringFormat of a REG Value-Add DWORD command.
  89.    ''' </summary>
  90.    Private Shared ReadOnly BatchStringFormat_ValueAdd_DWORD As String =
  91.    <a>REG ADD "{0}" /V "{1}" /T "REG_DWORD" /D "{2}" /F</a>.Value
  92.  
  93.    ''' <summary>
  94.    ''' Indicates the Batch syntax StringFormat of a REG Value-Add QWORD command.
  95.    ''' </summary>
  96.    Private Shared ReadOnly BatchStringFormat_ValueAdd_QWORD As String =
  97.    <a>REG ADD "{0}" /V "{1}" /T "REG_QWORD" /D "{2}" /F</a>.Value
  98.  
  99.    ''' <summary>
  100.    ''' Indicates the Batch syntax StringFormat of a REG Value-Add EXPAND_SZ command.
  101.    ''' </summary>
  102.    Private Shared ReadOnly BatchStringFormat_ValueAdd_EXPANDSZ As String =
  103.    <a>REG ADD "{0}" /V "{1}" /T "REG_EXPAND_SZ" /D "{2}" /F</a>.Value
  104.  
  105.    ''' <summary>
  106.    ''' Indicates the Batch syntax StringFormat of a REG Value-Add MULTI_SZ command.
  107.    ''' </summary>
  108.    Private Shared ReadOnly BatchStringFormat_ValueAdd_MULTISZ As String =
  109.    <a>REG ADD "{0}" /V "{1}" /T "REG_MULTI_SZ" /D "{2}" /F</a>.Value
  110.  
  111.    ''' <summary>
  112.    ''' Indicates the Batch syntax StringFormat of a REG Value-Delete command.
  113.    ''' </summary>
  114.    Private Shared ReadOnly BatchStringFormat_ValueDelete As String =
  115.    <a>REG DELETE "{0}" /V "{1}" /F</a>.Value
  116.  
  117.    ''' <summary>
  118.    ''' Indicates the string to split a BINARY registry line.
  119.    ''' </summary>
  120.    Private Shared ReadOnly RegistryValueSplitter_BINARY As String =
  121.    <a>=HEX</a>.Value
  122.  
  123.    ''' <summary>
  124.    ''' Indicates the string to split a DWORD registry line.
  125.    ''' </summary>
  126.    Private Shared ReadOnly RegistryValueSplitter_DWORD As String =
  127.    <a>=DWORD:</a>.Value
  128.  
  129.    ''' <summary>
  130.    ''' Indicates the string to split a QWORD registry line.
  131.    ''' </summary>
  132.    Private Shared ReadOnly RegistryValueSplitter_QWORD As String =
  133.    <a>=HEX\(b\):</a>.Value
  134.  
  135.    ''' <summary>
  136.    ''' Indicates the string to split a EXPAND_SZ registry line.
  137.    ''' </summary>
  138.    Private Shared ReadOnly RegistryValueSplitter_EXPANDSZ As String =
  139.    <a>=HEX\(2\):</a>.Value
  140.  
  141.    ''' <summary>
  142.    ''' Indicates the string to split a MULTI_SZ registry line.
  143.    ''' </summary>
  144.    Private Shared ReadOnly RegistryValueSplitter_MULTISZ As String =
  145.    <a>=HEX\(7\):</a>.Value
  146.  
  147.    ''' <summary>
  148.    ''' Indicates the string to split a REG_SZ registry line.
  149.    ''' </summary>
  150.    Private Shared ReadOnly RegistryValueSplitter_REGSZ As String =
  151.    <a>"="</a>.Value
  152.  
  153. #End Region
  154.  
  155. #Region " Enumerations "
  156.  
  157.    ''' <summary>
  158.    ''' Indicates the data type of a registry value.
  159.    ''' </summary>
  160.    Public Enum RegistryValueType As Integer
  161.  
  162.        ''' <summary>
  163.        ''' A null-terminated string.
  164.        ''' This will be either a Unicode or an ANSI string.
  165.        ''' </summary>
  166.        REG_SZ = 0
  167.  
  168.        ''' <summary>
  169.        ''' Binary data.
  170.        ''' </summary>
  171.        BINARY = 1
  172.  
  173.        ''' <summary>
  174.        ''' A 32-bit number.
  175.        ''' </summary>
  176.        DWORD = 2
  177.  
  178.        ''' <summary>
  179.        ''' A 64-bit number.
  180.        ''' </summary>
  181.        QWORD = 3
  182.  
  183.        ''' <summary>
  184.        ''' A null-terminated string that contains unexpanded references to environment variables
  185.        ''' (for example, "%WinDir%").
  186.        ''' </summary>
  187.        EXPAND_SZ = 4
  188.  
  189.        ''' <summary>
  190.        ''' A sequence of null-terminated strings, terminated by an empty string (\0).
  191.        '''
  192.        ''' The following is an example:
  193.        ''' String1\0String2\0String3\0LastString\0\0
  194.        ''' The first \0 terminates the first string,
  195.        ''' the second to the last \0 terminates the last string,
  196.        ''' and the final \0 terminates the sequence.
  197.        ''' Note that the final terminator must be factored into the length of the string.
  198.        ''' </summary>
  199.        MULTI_SZ = 5
  200.  
  201.    End Enum
  202.  
  203. #End Region
  204.  
  205. #Region " Public Methods "
  206.  
  207.    ''' <summary>
  208.    ''' Converts a Registry Script to a Batch Script.
  209.    ''' </summary>
  210.    ''' <param name="RegistryFile">Indicates the registry file to convert.</param>
  211.    ''' <returns>System.String.</returns>
  212.    Public Shared Function Convert(ByVal RegistryFile As String) As String
  213.  
  214.        ' Split the Registry content.
  215.        Dim RegistryContent As String() =
  216.            String.Join("@@@Reg2Bat@@@", File.ReadAllLines(RegistryFile)).
  217.                   Replace("\@@@Reg2Bat@@@  ", Nothing).
  218.                   Replace("@@@Reg2Bat@@@", Environment.NewLine).
  219.                   Split(Environment.NewLine)
  220.  
  221.        ' Where the registry line to convert will be stored.
  222.        Dim RegLine As String = String.Empty
  223.  
  224.        ' Where the registry key to convert will be stored.
  225.        Dim RegKey As String = String.Empty
  226.  
  227.        ' Where the registry value to convert will be stored.
  228.        Dim RegVal As String = String.Empty
  229.  
  230.        ' Where the registry data to convert will be stored.
  231.        Dim RegData As String = String.Empty
  232.  
  233.        ' Where the decoded registry strings will be stored.
  234.        Dim BatchCommands As New StringBuilder
  235.  
  236.        ' Writes the specified Batch-Script Header.
  237.        BatchCommands.AppendLine(BatchHeader)
  238.  
  239.        ' Start reading the Registry File.
  240.        For X As Long = 0 To RegistryContent.LongLength - 1
  241.  
  242.            RegLine = RegistryContent(X).Trim
  243.  
  244.            Select Case True
  245.  
  246.                Case RegLine.StartsWith(";"), RegLine.StartsWith("#")  ' It's a comment line.
  247.  
  248.                    BatchCommands.AppendLine(
  249.                        String.Format(BatchStringFormat_Comment, RegLine.Substring(1, RegLine.Length - 1).Trim))
  250.  
  251.                Case RegLine.StartsWith("[-") ' It's a key to delete.
  252.  
  253.                    RegKey = RegLine.Substring(2, RegLine.Length - 3).Trim
  254.                    BatchCommands.AppendLine(String.Format(BatchStringFormat_KeyDelete, RegKey))
  255.  
  256.                Case RegLine.StartsWith("[") ' It's a key to add.
  257.  
  258.                    RegKey = RegLine.Substring(1, RegLine.Length - 2).Trim
  259.                    BatchCommands.AppendLine(String.Format(BatchStringFormat_KeyAdd, RegKey))
  260.  
  261.                Case RegLine.StartsWith("@=") ' It's a default value to add.
  262.  
  263.                    RegData = RegLine.Split("@=").Last
  264.                    BatchCommands.AppendLine(String.Format(BatchStringFormat_DefaultValueAdd, RegKey, RegData))
  265.  
  266.                Case RegLine.StartsWith("""") _
  267.                AndAlso RegLine.Split("=").Last = "-" ' It's a value to delete.
  268.  
  269.                    RegVal = RegLine.Substring(1, RegLine.Length - 4)
  270.                    BatchCommands.AppendLine(String.Format(BatchStringFormat_ValueDelete, RegKey, RegVal))
  271.  
  272.                Case RegLine.StartsWith("""") ' It's a value to add.
  273.  
  274.                    Select Case RegLine.Split("=")(1).Split(":").First.ToUpper
  275.  
  276.                        Case "HEX" ' It's a Binary value.
  277.                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.BINARY))
  278.                            RegData = GetRegistryData(RegLine, RegistryValueType.BINARY)
  279.                            BatchCommands.AppendLine(
  280.                                String.Format(BatchStringFormat_ValueAdd_BINARY, RegKey, RegVal, RegData))
  281.  
  282.                        Case "DWORD" ' It's a DWORD value.
  283.                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.DWORD))
  284.                            RegData = GetRegistryData(RegLine, RegistryValueType.DWORD)
  285.                            BatchCommands.AppendLine(
  286.                                String.Format(BatchStringFormat_ValueAdd_DWORD, RegKey, RegVal, RegData))
  287.  
  288.                        Case "HEX(B)" ' It's a QWORD value.
  289.                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.QWORD))
  290.                            RegData = GetRegistryData(RegLine, RegistryValueType.QWORD)
  291.                            BatchCommands.AppendLine(
  292.                                String.Format(BatchStringFormat_ValueAdd_QWORD, RegKey, RegVal, RegData))
  293.  
  294.                        Case "HEX(2)"  ' It's a EXPAND_SZ value.
  295.                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.EXPAND_SZ))
  296.                            RegData = FormatRegistryString(GetRegistryData(RegLine, RegistryValueType.EXPAND_SZ))
  297.                            BatchCommands.AppendLine(
  298.                                String.Format(BatchStringFormat_ValueAdd_EXPANDSZ, RegKey, RegVal, RegData))
  299.  
  300.                        Case "HEX(7)" ' It's a MULTI_SZ value.
  301.                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.MULTI_SZ))
  302.                            RegData = FormatRegistryString(GetRegistryData(RegLine, RegistryValueType.MULTI_SZ))
  303.                            BatchCommands.AppendLine(
  304.                                String.Format(BatchStringFormat_ValueAdd_MULTISZ, RegKey, RegVal, RegData))
  305.  
  306.                        Case Else ' It's a REG_SZ value.
  307.                            RegVal = FormatRegistryString(GetRegistryValue(RegLine, RegistryValueType.REG_SZ))
  308.                            RegData = FormatRegistryString(GetRegistryData(RegLine, RegistryValueType.REG_SZ))
  309.                            BatchCommands.AppendLine(
  310.                                String.Format(BatchStringFormat_ValueAdd_REGSZ, RegKey, RegVal, RegData))
  311.  
  312.                    End Select ' RegLine.Split("=")(1).Split(":").First.ToUpper
  313.  
  314.            End Select ' RegLine.StartsWith("""")
  315.  
  316.        Next X ' RegLine
  317.  
  318.        ' Writes the specified Batch-Script Footer.
  319.        BatchCommands.AppendLine(BatchFooter)
  320.  
  321.        Return BatchCommands.ToString
  322.  
  323.    End Function
  324.  
  325. #End Region
  326.  
  327. #Region " Private Methods "
  328.  
  329.    ''' <summary>
  330.    ''' Gets the registry value of a registry line.
  331.    ''' </summary>
  332.    ''' <param name="RegistryLine">Indicates the registry line.</param>
  333.    ''' <param name="RegistryValueType">Indicates the type of the registry value.</param>
  334.    ''' <returns>System.String.</returns>
  335.    Private Shared Function GetRegistryValue(ByVal RegistryLine As String,
  336.                                             ByVal RegistryValueType As RegistryValueType) As String
  337.  
  338.        Dim Value As String = String.Empty
  339.  
  340.        Select Case RegistryValueType
  341.  
  342.            Case RegistryValueType.BINARY
  343.                Value = Regex.Split(RegistryLine,
  344.                                    RegistryValueSplitter_BINARY,
  345.                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()
  346.  
  347.            Case RegistryValueType.DWORD
  348.                Value = Regex.Split(RegistryLine,
  349.                                    RegistryValueSplitter_DWORD,
  350.                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()
  351.  
  352.            Case RegistryValueType.QWORD
  353.                Value = Regex.Split(RegistryLine,
  354.                                    RegistryValueSplitter_QWORD,
  355.                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()
  356.  
  357.            Case RegistryValueType.EXPAND_SZ
  358.                Value = Regex.Split(RegistryLine,
  359.                                    RegistryValueSplitter_EXPANDSZ,
  360.                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()
  361.  
  362.            Case RegistryValueType.MULTI_SZ
  363.                Value = Regex.Split(RegistryLine,
  364.                                    RegistryValueSplitter_MULTISZ,
  365.                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()
  366.  
  367.            Case RegistryValueType.REG_SZ
  368.                Value = Regex.Split(RegistryLine,
  369.                                    RegistryValueSplitter_REGSZ,
  370.                                    RegexOptions.IgnoreCase Or RegexOptions.Singleline).First()
  371.  
  372.        End Select
  373.  
  374.        If Value.StartsWith("""") Then
  375.            Value = Value.Substring(1, Value.Length - 1)
  376.        End If
  377.  
  378.        If Value.EndsWith("""") Then
  379.            Value = Value.Substring(0, Value.Length - 1)
  380.        End If
  381.  
  382.        Return Value
  383.  
  384.    End Function
  385.  
  386.    ''' <summary>
  387.    ''' Gets the registry data of a registry line.
  388.    ''' </summary>
  389.    ''' <param name="RegistryLine">Indicates the registry line.</param>
  390.    ''' <param name="RegistryValueType">Indicates the type of the registry value.</param>
  391.    ''' <returns>System.String.</returns>
  392.    Private Shared Function GetRegistryData(ByVal RegistryLine As String,
  393.                                            ByVal RegistryValueType As RegistryValueType) As String
  394.  
  395.        Dim Data As String = String.Empty
  396.  
  397.        Select Case RegistryValueType
  398.  
  399.            Case RegistryValueType.BINARY
  400.  
  401.                Data = Regex.Split(RegistryLine,
  402.                                   Regex.Split(RegistryLine,
  403.                                               RegistryValueSplitter_BINARY, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
  404.                                               RegistryValueSplitter_BINARY,
  405.                                   RegexOptions.IgnoreCase Or RegexOptions.Singleline).
  406.                                   Last.
  407.                                   Replace(",", Nothing)
  408.  
  409.            Case RegistryValueType.DWORD
  410.  
  411.                Data = Regex.Split(RegistryLine,
  412.                                   Regex.Split(RegistryLine,
  413.                                               RegistryValueSplitter_DWORD, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
  414.                                               RegistryValueSplitter_DWORD,
  415.                                   RegexOptions.IgnoreCase Or RegexOptions.Singleline).
  416.                                   Last.
  417.                                   Replace(",", Nothing)
  418.  
  419.                Data = "0x" & Data
  420.  
  421.            Case RegistryValueType.QWORD
  422.  
  423.                RegistryLine =
  424.                    String.Join(Nothing,
  425.                                Regex.Split(RegistryLine,
  426.                                            Regex.Split(RegistryLine,
  427.                                                        RegistryValueSplitter_QWORD, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
  428.                                                        RegistryValueSplitter_QWORD,
  429.                                            RegexOptions.IgnoreCase Or RegexOptions.Singleline).
  430.                                            Last.
  431.                                            Reverse)
  432.  
  433.                For Each [Byte] As String In RegistryLine.Split(",")
  434.                    Data &= String.Join(Nothing, [Byte].Reverse)
  435.                Next [Byte]
  436.  
  437.                Data = "0x" & Data
  438.  
  439.            Case RegistryValueType.EXPAND_SZ
  440.  
  441.                RegistryLine = Regex.Split(RegistryLine,
  442.                                            Regex.Split(RegistryLine,
  443.                                                        RegistryValueSplitter_EXPANDSZ, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
  444.                                                        RegistryValueSplitter_EXPANDSZ,
  445.                                            RegexOptions.IgnoreCase Or RegexOptions.Singleline).
  446.                                            Last.
  447.                                            Replace(",00", "").
  448.                                            Replace("00,", "")
  449.  
  450.                For Each [Byte] As String In RegistryLine.Split(",")
  451.                    Data &= Chr(Val("&H" & [Byte]))
  452.                Next [Byte]
  453.  
  454.                Data = Data.Replace("""", "\""")
  455.  
  456.            Case RegistryValueType.MULTI_SZ
  457.  
  458.                RegistryLine = Regex.Split(RegistryLine,
  459.                                            Regex.Split(RegistryLine,
  460.                                                        RegistryValueSplitter_MULTISZ, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
  461.                                                        RegistryValueSplitter_MULTISZ,
  462.                                            RegexOptions.IgnoreCase Or RegexOptions.Singleline).
  463.                                            Last.
  464.                                            Replace(",00,00,00", ",\0").
  465.                                            Replace(",00", "").
  466.                                            Replace("00,", "")
  467.  
  468.                For Each [Byte] In RegistryLine.Split(",")
  469.  
  470.                    If [Byte] = "\0" Then
  471.                        Data &= "\0" ' Multiline separator.
  472.                    Else
  473.                        Data &= Chr(Val("&H" & [Byte]))
  474.                    End If
  475.  
  476.                Next
  477.  
  478.                Return Data.Replace("""", "\""")
  479.  
  480.            Case RegistryValueType.REG_SZ
  481.  
  482.                Data = Regex.Split(RegistryLine,
  483.                                   Regex.Split(RegistryLine,
  484.                                               RegistryValueSplitter_REGSZ, RegexOptions.IgnoreCase Or RegexOptions.Singleline).First &
  485.                                               RegistryValueSplitter_REGSZ,
  486.                                   RegexOptions.IgnoreCase Or RegexOptions.Singleline).
  487.                                   Last
  488.  
  489.                Data = Data.Substring(0, Data.Length - 1).Replace("\\", "\")
  490.  
  491.        End Select
  492.  
  493.        Return Data
  494.  
  495.    End Function
  496.  
  497.    ''' <summary>
  498.    ''' Properly formats a registry string to insert it in a Batch command string.
  499.    ''' </summary>
  500.    ''' <param name="RegistryString">Indicates the Reg Batch command string.</param>
  501.    ''' <returns>System.String.</returns>
  502.    Private Shared Function FormatRegistryString(ByVal RegistryString As String) As String
  503.  
  504.        RegistryString = RegistryString.Replace("%", "%%")
  505.        If Not RegistryString.Contains("""") Then
  506.            Return RegistryString
  507.        End If
  508.  
  509.        RegistryString = RegistryString.Replace("\""", """")
  510.  
  511.        Dim strArray() As String = RegistryString.Split("""")
  512.  
  513.        For X As Long = 1 To strArray.Length - 1 Step 2
  514.  
  515.            strArray(X) = strArray(X).Replace("^", "^^") ' This replacement need to be THE FIRST.
  516.            strArray(X) = strArray(X).Replace("<", "^<")
  517.            strArray(X) = strArray(X).Replace(">", "^>")
  518.            strArray(X) = strArray(X).Replace("|", "^|")
  519.            strArray(X) = strArray(X).Replace("&", "^&")
  520.            ' strArray(X) = strArray(X).Replace("\", "\\")
  521.  
  522.        Next X
  523.  
  524.        Return String.Join("\""", strArray)
  525.  
  526.    End Function
  527.  
  528. #End Region
  529.  
  530. #Region " Hidden methods "
  531.  
  532.    ' These methods are purposely hidden from Intellisense just to look better without unneeded methods.
  533.    ' NOTE: The methods can be re-enabled at any-time if needed.
  534.  
  535.    <EditorBrowsable(EditorBrowsableState.Never)>
  536.    Public Shadows Sub Equals()
  537.    End Sub
  538.  
  539.    <EditorBrowsable(EditorBrowsableState.Never)>
  540.    Public Shadows Sub ReferenceEquals()
  541.    End Sub
  542.  
  543. #End Region
  544.  
  545. End Class
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #374 en: 5 Febrero 2014, 16:59 pm »

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

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-05-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DocumentConverter.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Example Usages "
  11.  
  12. 'MsgBox(DocumentConverter.Html2Rtf("Hello World!"))
  13. '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!}}"))
  14.  
  15. 'Dim HtmlText As String = DocumentConverter.Rtf2Html(IO.File.ReadAllText("C:\File.rtf"), TextEncoding:=Nothing)
  16. 'Dim RtfText As String = DocumentConverter.Html2Rtf(IO.File.ReadAllText("C:\File.html"), TextEncoding:=Nothing)
  17. 'Dim PlainTextFromRtf As String = DocumentConverter.Rtf2Txt(IO.File.ReadAllText("C:\File.rtf"), TextEncoding:=Nothing)
  18. 'Dim PlainTextFromHtml As String = DocumentConverter.Html2Txt(IO.File.ReadAllText("C:\File.html"), TextEncoding:=Nothing)
  19.  
  20. #End Region
  21.  
  22. #Region " Imports "
  23.  
  24. Imports Nasosoft.Documents.Transform
  25. Imports System.IO
  26. Imports System.Text
  27.  
  28. #End Region
  29.  
  30. ''' <summary>
  31. ''' Performs document conversion operations.
  32. ''' </summary>
  33. Public Class DocumentConverter
  34.  
  35. #Region " Public Methods "
  36.  
  37.    ''' <summary>
  38.    ''' Converts RTF text to HTML.
  39.    ''' </summary>
  40.    ''' <param name="RtfText">Indicates the RTF text.</param>
  41.    ''' <param name="TextEncoding">Indicates the text encoding.</param>
  42.    ''' <returns>System.String.</returns>
  43.    Public Shared Function Rtf2Html(ByVal RtfText As String,
  44.                                    Optional ByVal TextEncoding As Encoding = Nothing) As String
  45.  
  46.        TextEncoding = If(TextEncoding Is Nothing, Encoding.Default, TextEncoding)
  47.  
  48.        Dim RtfStream As New MemoryStream(TextEncoding.GetBytes(RtfText))
  49.        Dim HtmlStream As New MemoryStream
  50.        Dim HtmlText As String = String.Empty
  51.  
  52.        Using Converter As New RtfToHtmlTransform()
  53.            Converter.Load(RtfStream)
  54.            Converter.Transform(HtmlStream)
  55.        End Using
  56.  
  57.        HtmlStream.Position = 0
  58.  
  59.        Using StrReader As New StreamReader(HtmlStream)
  60.            HtmlText = StrReader.ReadToEnd
  61.        End Using
  62.  
  63.        RtfStream.Close()
  64.        HtmlStream.Close()
  65.  
  66.        Return HtmlText
  67.  
  68.    End Function
  69.  
  70.    ''' <summary>
  71.    ''' Converts RTF text to TXT (Plain text).
  72.    ''' </summary>
  73.    ''' <param name="RtfText">Indicates the RTF text.</param>
  74.    ''' <param name="TextEncoding">Indicates the text encoding.</param>
  75.    ''' <returns>System.String.</returns>
  76.    Public Shared Function Rtf2Txt(ByVal RtfText As String,
  77.                                    Optional ByVal TextEncoding As Encoding = Nothing) As String
  78.  
  79.        TextEncoding = If(TextEncoding Is Nothing, Encoding.Default, TextEncoding)
  80.  
  81.        Dim RtfStream As New MemoryStream(TextEncoding.GetBytes(RtfText))
  82.        Dim TextStream As New MemoryStream
  83.        Dim PlainText As String = String.Empty
  84.  
  85.        Using Converter As New RtfToTextTransform()
  86.            Converter.Load(RtfStream)
  87.            Converter.Transform(TextStream)
  88.        End Using
  89.  
  90.        TextStream.Position = 0
  91.  
  92.        Using StrReader As New StreamReader(TextStream)
  93.            PlainText = StrReader.ReadToEnd
  94.        End Using
  95.  
  96.        RtfStream.Close()
  97.        TextStream.Close()
  98.  
  99.        Return PlainText
  100.  
  101.    End Function
  102.  
  103.    ''' <summary>
  104.    ''' Converts HTML text to RTF.
  105.    ''' </summary>
  106.    ''' <param name="HtmlText">Indicates the HTML text.</param>
  107.    ''' <param name="TextEncoding">Indicates the text encoding.</param>
  108.    ''' <returns>System.String.</returns>
  109.    Public Shared Function Html2Rtf(ByVal HtmlText As String,
  110.                                    Optional ByVal TextEncoding As Encoding = Nothing) As String
  111.  
  112.        TextEncoding = If(TextEncoding Is Nothing, Encoding.Default, TextEncoding)
  113.  
  114.        Dim HtmlStream As New MemoryStream(TextEncoding.GetBytes(HtmlText))
  115.        Dim RtfStream As New MemoryStream
  116.        Dim RtfText As String = String.Empty
  117.  
  118.        Using Converter As New HtmlToRtfTransform()
  119.            Converter.Load(HtmlStream)
  120.            Converter.Transform(RtfStream)
  121.        End Using
  122.  
  123.        RtfStream.Position = 0
  124.  
  125.        Using StrReader As New StreamReader(RtfStream)
  126.            RtfText = StrReader.ReadToEnd
  127.        End Using
  128.  
  129.        HtmlStream.Close()
  130.        RtfStream.Close()
  131.  
  132.        Return RtfText
  133.  
  134.    End Function
  135.  
  136.    ''' <summary>
  137.    ''' Converts HTML text to TXT (Plain text).
  138.    ''' </summary>
  139.    ''' <param name="HtmlText">Indicates the HTML text.</param>
  140.    ''' <param name="TextEncoding">Indicates the text encoding.</param>
  141.    ''' <returns>System.String.</returns>
  142.    Public Shared Function Html2Txt(ByVal HtmlText As String,
  143.                                    Optional ByVal TextEncoding As Encoding = Nothing) As String
  144.  
  145.        TextEncoding = If(TextEncoding Is Nothing, Encoding.Default, TextEncoding)
  146.  
  147.        Dim HtmlStream As New MemoryStream(TextEncoding.GetBytes(HtmlText))
  148.        Dim TextStream As New MemoryStream
  149.        Dim PlainText As String = String.Empty
  150.  
  151.        Using Converter As New HtmlToTextTransform()
  152.            Converter.Load(HtmlStream)
  153.            Converter.Transform(TextStream)
  154.        End Using
  155.  
  156.        TextStream.Position = 0
  157.  
  158.        Using StrReader As New StreamReader(TextStream)
  159.            PlainText = StrReader.ReadToEnd
  160.        End Using
  161.  
  162.        HtmlStream.Close()
  163.        TextStream.Close()
  164.  
  165.        Return PlainText
  166.  
  167.    End Function
  168.  
  169. #End Region
  170.  
  171. End Class
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #375 en: 8 Febrero 2014, 11:50 am »

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

Código
  1. Public Class Form1
  2.  
  3.    Private WithEvents ProcessStartWatcher As ManagementEventWatcher =
  4.        New ManagementEventWatcher(
  5.            New WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"))
  6.  
  7.    Private WithEvents ProcessStopWatcher As ManagementEventWatcher =
  8.        New System.Management.ManagementEventWatcher(
  9.            New WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"))
  10.  
  11.    Private Shadows Sub Load() Handles MyBase.Load
  12.        ProcessStartWatcher.Start()
  13.        ProcessStopWatcher.Start()
  14.    End Sub
  15.  
  16.    Private Shadows Sub Closing() Handles MyBase.Closing
  17.        ProcessStartWatcher.Stop()
  18.        ProcessStopWatcher.Stop()
  19.    End Sub
  20.  
  21.    Public Sub ProcessStartWatcher_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs) _
  22.    Handles ProcessStartWatcher.EventArrived
  23.  
  24.        MsgBox(String.Format("Process started: {0}",
  25.                             e.NewEvent.Properties("ProcessName").Value))
  26.  
  27.    End Sub
  28.  
  29.    Private Sub ProcessStopWatcher_Stopped(ByVal sender As Object, ByVal e As EventArrivedEventArgs) _
  30.    Handles ProcessStopWatcher.EventArrived
  31.  
  32.        MsgBox(String.Format("Process stopped: {0}",
  33.                             e.NewEvent.Properties("ProcessName").Value))
  34.  
  35.    End Sub
  36.  
  37. End Class



Modificar el proxy de un GeckoFX Webbrowser:

Código
  1.  
  2.  
  3. ' By Elektro
  4.  
  5.  
  6.    ''' <summary>
  7.    ''' ProxyTypes of Gecko webbrowser.
  8.    ''' </summary>
  9.    Public Enum ProxyType
  10.  
  11.        ''' <summary>
  12.        ''' Direct connection, no proxy.
  13.        ''' (Default in Windows and Mac previous to 1.9.2.4 /Firefox 3.6.4)
  14.        ''' </summary>
  15.        DirectConnection = 0
  16.  
  17.        ''' <summary>
  18.        ''' Manual proxy configuration.
  19.        ''' </summary>
  20.        Manual = 1
  21.  
  22.        ''' <summary>
  23.        ''' Proxy auto-configuration (PAC).
  24.        ''' </summary>
  25.        AutoConfiguration = 2
  26.  
  27.        ''' <summary>
  28.        ''' Auto-detect proxy settings.
  29.        ''' </summary>
  30.        AutoDetect = 4
  31.  
  32.        ''' <summary>
  33.        ''' Use system proxy settings.
  34.        ''' (Default in Linux; default for all platforms, starting in 1.9.2.4 /Firefox 3.6.4)
  35.        ''' </summary>
  36.        System = 5
  37.  
  38.    End Enum
  39.  
  40.    ''' <summary>
  41.    ''' Sets the proxy type of a Gecko Webbrowser.
  42.    ''' </summary>
  43.    ''' <param name="ProxyType">Indicates the type of proxy.</param>
  44.    Private Sub SetGeckoProxyType(ByVal ProxyType As ProxyType)
  45.  
  46.        GeckoPreferences.Default("network.proxy.type") = ProxyType
  47.  
  48.    End Sub
  49.  
  50.    ''' <summary>
  51.    ''' Sets the proxy of a Gecko Webbrowser.
  52.    ''' </summary>
  53.    ''' <param name="Host">Indicates the proxy host.</param>
  54.    ''' <param name="Port">Indicates the proxy port.</param>
  55.    Private Sub SetGeckoProxy(ByVal Host As String,
  56.                              ByVal Port As Integer)
  57.  
  58.        ' Set the ProxyType to manual configuration.
  59.        GeckoPreferences.Default("network.proxy.type") = ProxyType.Manual
  60.  
  61.        ' Set the HTP proxy Host and Port.
  62.        GeckoPreferences.Default("network.proxy.http") = Host
  63.        GeckoPreferences.Default("network.proxy.http_port") = Port
  64.  
  65.        ' Set the SSL proxy Host and Port.
  66.        GeckoPreferences.Default("network.proxy.ssl") = Host
  67.        GeckoPreferences.Default("network.proxy.ssl_port") = Port
  68.  
  69.    End Sub



Devuelve un String con el source de una página

Código
  1.    ' Get SourcePage String
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetSourcePageString("http://www.elhacker.net"))
  6.    '
  7.    ''' <summary>
  8.    ''' Gets a web source page.
  9.    ''' </summary>
  10.    ''' <param name="URL">Indicates the source page URL to get.</param>
  11.    ''' <returns>System.String.</returns>
  12.    ''' <exception cref="Exception"></exception>
  13.    Private Function GetSourcePageString(ByVal URL As String) As String
  14.  
  15.        Try
  16.  
  17.            Using StrReader As New IO.StreamReader(Net.HttpWebRequest.Create(URL).GetResponse().GetResponseStream)
  18.                Return StrReader.ReadToEnd
  19.            End Using
  20.  
  21.        Catch ex As Exception
  22.            Throw New Exception(ex.Message)
  23.            Return Nothing
  24.  
  25.        End Try
  26.  
  27.    End Function



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

Código
  1.    ' Get SourcePage Array
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' Dim SourceLines As String() = GetSourcePageArray("http://www.ElHacker.net", TrimLines:=True)
  6.    ' For Each Line As String In SourceLines : MsgBox(Line) : Next Line
  7.    '
  8.    ''' <summary>
  9.    ''' Gets a web source page.
  10.    ''' </summary>
  11.    ''' <param name="URL">Indicates the source page URL to get.</param>
  12.    ''' <param name="TrimLines">Indicates whether to trim the lines.</param>
  13.    ''' <param name="SplitOptions">Indicates the split options.</param>
  14.    ''' <returns>System.String[][].</returns>
  15.    ''' <exception cref="Exception"></exception>
  16.    Private Function GetSourcePageArray(ByVal URL As String,
  17.                                        Optional ByVal TrimLines As Boolean = False,
  18.                                        Optional ByVal SplitOptions As StringSplitOptions =
  19.                                                       StringSplitOptions.None) As String()
  20.  
  21.        Try
  22.  
  23.            Using StrReader As New IO.StreamReader(Net.HttpWebRequest.Create(URL).GetResponse().GetResponseStream)
  24.  
  25.                If TrimLines Then
  26.  
  27.                    Return (From Line As String
  28.                           In StrReader.ReadToEnd.Split({Environment.NewLine}, SplitOptions)
  29.                           Select Line.Trim).ToArray
  30.  
  31.                Else
  32.                    Return StrReader.ReadToEnd.Split({Environment.NewLine}, SplitOptions)
  33.  
  34.                End If
  35.  
  36.            End Using
  37.  
  38.        Catch ex As Exception
  39.            Throw New Exception(ex.Message)
  40.            Return Nothing
  41.  
  42.        End Try
  43.  
  44.    End Function



Devuelve el directorio de un proceso en ejecución

Código
  1.    ' Get Process Path
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetProcessPath("notepad.exe").First)
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the absolute path of a running process.
  9.    ''' </summary>
  10.    ''' <param name="ProcessName">Indicates the name of the process.</param>
  11.    ''' <returns>System.String[][].</returns>
  12.    ''' <exception cref="Exception">ProcessName parametter can't be Null.</exception>
  13.    Public Function GetProcessPath(ByVal ProcessName As String) As String()
  14.  
  15.        If ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
  16.            ProcessName = ProcessName.Remove(ProcessName.Length - 4)
  17.        End If
  18.  
  19.        Return (From p As Process In Process.GetProcesses
  20.                Where p.ProcessName.Equals(ProcessName, StringComparison.OrdinalIgnoreCase)
  21.                Select p.MainModule.FileName).ToArray
  22.  
  23.    End Function



Desordena un archivo de texto y devuelve un String

Código
  1.    ' Randomize TextFile String
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(RandomizeTextFileString("C:\File.txt", Encoding:=Nothing)))
  6.    '
  7.    ''' <summary>
  8.    ''' Randomizes the contents of a text file.
  9.    ''' </summary>
  10.    ''' <param name="TextFile">Indicates the text file to randomize.</param>
  11.    ''' <param name="Encoding">Indicates the text encoding to use.</param>
  12.    ''' <returns>System.String.</returns>
  13.    Public Function RandomizeTextFileString(ByVal TextFile As String,
  14.                                            Optional ByVal Encoding As System.Text.Encoding = Nothing) As String
  15.  
  16.        Dim Randomizer As New Random
  17.  
  18.        Return String.Join(Environment.NewLine,
  19.                           (From Item As String
  20.                            In IO.File.ReadAllLines(TextFile,
  21.                                                    If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding))
  22.                            Order By Randomizer.Next))
  23.  
  24.    End Function



Desordena un archivo d etexto y devuelve un Array:

Código
  1.    ' Randomize TextFile Array
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(RandomizeTextFileArray("C:\File.txt", Encoding:=Nothing).First))
  6.    '
  7.    ''' <summary>
  8.    ''' Randomizes the contents of a text file.
  9.    ''' </summary>
  10.    ''' <param name="TextFile">Indicates the text file to randomize.</param>
  11.    ''' <param name="Encoding">Indicates the text encoding to use.</param>
  12.    ''' <returns>System.String[].</returns>
  13.    Public Function RandomizeTextFileArray(ByVal TextFile As String,
  14.                                           Optional ByVal Encoding As System.Text.Encoding = Nothing) As String()
  15.  
  16.        Dim Randomizer As New Random
  17.  
  18.        Return (From Item As String
  19.                In IO.File.ReadAllLines(TextFile,
  20.                                        If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding))
  21.                Order By Randomizer.Next).ToArray
  22.  
  23.    End Function
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #376 en: 15 Febrero 2014, 02:38 am »

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
  1. Sub Test()
  2.  
  3.    ' Restart the current computer in 30 seconds and wait for applications to close.
  4.    ' Specify that the restart operation is planned because a consecuence of an installation.
  5.    Dim Success =
  6.    SystemRestarter.Restart(Nothing, 30, "System is gonna be restarted quickly, save all your data...!",
  7.                            SystemRestarter.Enums.InitiateShutdown_Force.Wait,
  8.                            SystemRestarter.Enums.ShutdownReason.MajorOperatingSystem Or
  9.                            SystemRestarter.Enums.ShutdownReason.MinorInstallation,
  10.                            SystemRestarter.Enums.ShutdownPlanning.Planned)
  11.  
  12.    Console.WriteLine(String.Format("Restart operation initiated successfully?: {0}", CStr(Success)))
  13.  
  14.    ' Abort the current operation.
  15.    If Success Then
  16.        Dim IsAborted = SystemRestarter.Abort()
  17.        Console.WriteLine(String.Format("Restart operation aborted   successfully?: {0}", CStr(IsAborted)))
  18.    Else
  19.        Console.WriteLine("There is any restart operation to abort.")
  20.    End If
  21.    Console.ReadKey()
  22.  
  23.    ' Shutdown the current computer instantlly and force applications to close.
  24.    ' ( When timeout is '0' the operation can't be aborted )
  25.    SystemRestarter.Shutdown(Nothing, 0, Nothing, SystemRestarter.Enums.InitiateShutdown_Force.ForceSelf)
  26.  
  27.    ' LogOffs the current user.
  28.    SystemRestarter.LogOff(SystemRestarter.Enums.ExitwindowsEx_Force.Wait)
  29.  
  30. End Sub
« Última modificación: 15 Febrero 2014, 02:41 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #377 en: 17 Febrero 2014, 22:16 pm »

obtener los dispositivos extraibles que están conectados al sistema

Código
  1.        ' GetDrivesOfType
  2.       ' ( By Elektro )
  3.       '
  4.       ' Usage Examples:
  5.       '
  6.       ' Dim Drives As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Fixed)
  7.       '
  8.       ' For Each Drive As IO.DriveInfo In GetDrivesOfType(IO.DriveType.Removable)
  9.       '     MsgBox(Drive.Name)
  10.       ' Next Drive
  11.       '
  12.       ''' <summary>
  13.       ''' Get all the connected drives of the given type.
  14.       ''' </summary>
  15.       ''' <param name="DriveType">Indicates the type of the drive.</param>
  16.       ''' <returns>System.IO.DriveInfo[].</returns>
  17.       Public Function GetDrivesOfType(ByVal DriveType As IO.DriveType) As IO.DriveInfo()
  18.  
  19.           Return (From Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
  20.                   Where Drive.DriveType = DriveType).ToArray
  21.  
  22.       End Function



monitorizar la inserción/extracción de dispositivos

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-17-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DriveWatcher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ' ''' <summary>
  13. ' ''' The DriveWatcher instance to monitor USB devices.
  14. ' ''' </summary>
  15. 'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me)
  16.  
  17. ' ''' <summary>
  18. ' ''' Handles the DriveInserted event of the USBMonitor object.
  19. ' ''' </summary>
  20. ' ''' <param name="sender">The source of the event.</param>
  21. ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  22. 'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted
  23.  
  24. '    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
  25.  
  26. '        Dim sb As New System.Text.StringBuilder
  27.  
  28. '        sb.AppendLine("DRIVE CONNECTED!")
  29. '        sb.AppendLine()
  30. '        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
  31. '        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
  32. '        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
  33. '        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
  34. '        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
  35. '        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
  36. '        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
  37. '        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
  38. '        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
  39.  
  40. '        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
  41.  
  42. '    End If
  43.  
  44. 'End Sub
  45.  
  46. ' ''' <summary>
  47. ' ''' Handles the DriveRemoved event of the USBMonitor object.
  48. ' ''' </summary>
  49. ' ''' <param name="sender">The source of the event.</param>
  50. ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  51. 'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved
  52.  
  53. '    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
  54.  
  55. '        Dim sb As New System.Text.StringBuilder
  56.  
  57. '        sb.AppendLine("DRIVE DISCONNECTED!")
  58. '        sb.AppendLine()
  59. '        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
  60. '        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
  61. '        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
  62. '        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
  63. '        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
  64. '        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
  65. '        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
  66. '        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
  67. '        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
  68.  
  69. '        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
  70.  
  71. '    End If
  72.  
  73. 'End Sub
  74.  
  75. #End Region
  76.  
  77. #Region " Imports "
  78.  
  79. Imports System.IO
  80. Imports System.Runtime.InteropServices
  81. Imports System.ComponentModel
  82.  
  83. #End Region
  84.  
  85. ''' <summary>
  86. ''' Device insertion/removal monitor.
  87. ''' </summary>
  88. Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
  89.  
  90. #Region " Objects "
  91.  
  92.    ''' <summary>
  93.    ''' The current connected drives.
  94.    ''' </summary>
  95.    Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo)
  96.  
  97.    ''' <summary>
  98.    ''' Indicates the drive letter of the current device.
  99.    ''' </summary>
  100.    Private DriveLetter As Char = Nothing
  101.  
  102.    ''' <summary>
  103.    ''' Indicates the current Drive information.
  104.    ''' </summary>
  105.    Private CurrentDrive As DriveWatcherInfo = Nothing
  106.  
  107.    ''' <summary>
  108.    ''' The form to manage their Windows Messages.
  109.    ''' </summary>
  110.    Private WithEvents form As Form = Nothing
  111.  
  112. #End Region
  113.  
  114. #Region " Events "
  115.  
  116.    ''' <summary>
  117.    ''' Occurs when a drive is inserted.
  118.    ''' </summary>
  119.    Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo)
  120.  
  121.    ''' <summary>
  122.    ''' Occurs when a drive is removed.
  123.    ''' </summary>
  124.    Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo)
  125.  
  126. #End Region
  127.  
  128. #Region " Enumerations "
  129.  
  130.    ''' <summary>
  131.    ''' Notifies an application of a change to the hardware configuration of a device or the computer.
  132.    ''' A window receives this message through its WindowProc function.
  133.    ''' For more info, see here:
  134.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx
  135.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx
  136.    ''' </summary>
  137.    Private Enum DeviceEvents As Integer
  138.  
  139.        ''' <summary>
  140.        ''' The current configuration has changed, due to a dock or undock.
  141.        ''' </summary>
  142.        Change = &H219
  143.  
  144.        ''' <summary>
  145.        ''' A device or piece of media has been inserted and becomes available.
  146.        ''' </summary>
  147.        Arrival = &H8000
  148.  
  149.        ''' <summary>
  150.        ''' Request permission to remove a device or piece of media.
  151.        ''' This message is the last chance for applications and drivers to prepare for this removal.
  152.        ''' However, any application can deny this request and cancel the operation.
  153.        ''' </summary>
  154.        QueryRemove = &H8001
  155.  
  156.        ''' <summary>
  157.        ''' A request to remove a device or piece of media has been canceled.
  158.        ''' </summary>
  159.        QueryRemoveFailed = &H8002
  160.  
  161.        ''' <summary>
  162.        ''' A device or piece of media is being removed and is no longer available for use.
  163.        ''' </summary>
  164.        RemovePending = &H8003
  165.  
  166.        ''' <summary>
  167.        ''' A device or piece of media has been removed.
  168.        ''' </summary>
  169.        RemoveComplete = &H8004
  170.  
  171.        ''' <summary>
  172.        ''' The type volume
  173.        ''' </summary>
  174.        TypeVolume = &H2
  175.  
  176.    End Enum
  177.  
  178. #End Region
  179.  
  180. #Region " Structures "
  181.  
  182.    ''' <summary>
  183.    ''' Indicates information related of a Device.
  184.    ''' ( Replic of System.IO.DriveInfo )
  185.    ''' </summary>
  186.    Public Structure DriveWatcherInfo
  187.  
  188.        ''' <summary>
  189.        ''' Indicates the name of a drive, such as 'C:\'.
  190.        ''' </summary>
  191.        Public Name As String
  192.  
  193.        ''' <summary>
  194.        ''' Indicates the amount of available free space on a drive, in bytes.
  195.        ''' </summary>
  196.        Public AvailableFreeSpace As Long
  197.  
  198.        ''' <summary>
  199.        ''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc...
  200.        ''' </summary>
  201.        Public DriveFormat As String
  202.  
  203.        ''' <summary>
  204.        ''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc...
  205.        ''' </summary>
  206.        Public DriveType As DriveType
  207.  
  208.        ''' <summary>
  209.        ''' Indicates whether a drive is ready.
  210.        ''' </summary>
  211.        Public IsReady As Boolean
  212.  
  213.        ''' <summary>
  214.        ''' Indicates the root directory of a drive.
  215.        ''' </summary>
  216.        Public RootDirectory As String
  217.  
  218.        ''' <summary>
  219.        ''' Indicates the total amount of free space available on a drive, in bytes.
  220.        ''' </summary>
  221.        Public TotalFreeSpace As Long
  222.  
  223.        ''' <summary>
  224.        ''' Indicates the total size of storage space on a drive, in bytes.
  225.        ''' </summary>
  226.        Public TotalSize As Long
  227.  
  228.        ''' <summary>
  229.        ''' Indicates the volume label of a drive.
  230.        ''' </summary>
  231.        Public VolumeLabel As String
  232.  
  233.        ''' <summary>
  234.        ''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct.
  235.        ''' </summary>
  236.        ''' <param name="e">The e.</param>
  237.        Public Sub New(ByVal e As DriveInfo)
  238.  
  239.            Name = e.Name
  240.  
  241.            Select Case e.IsReady
  242.  
  243.                Case True ' Drive is formatted and ready.
  244.                    IsReady = True
  245.                    DriveFormat = e.DriveFormat
  246.                    DriveType = e.DriveType
  247.                    RootDirectory = e.RootDirectory.FullName
  248.                    VolumeLabel = e.VolumeLabel
  249.                    TotalSize = e.TotalSize
  250.                    TotalFreeSpace = e.TotalFreeSpace
  251.                    AvailableFreeSpace = e.AvailableFreeSpace
  252.  
  253.                Case False ' Drive is not formatted so can't retrieve data.
  254.                    IsReady = False
  255.                    DriveFormat = Nothing
  256.                    DriveType = e.DriveType
  257.                    RootDirectory = e.RootDirectory.FullName
  258.                    VolumeLabel = Nothing
  259.                    TotalSize = 0
  260.                    TotalFreeSpace = 0
  261.                    AvailableFreeSpace = 0
  262.  
  263.            End Select ' e.IsReady
  264.  
  265.        End Sub
  266.  
  267.    End Structure
  268.  
  269.    ''' <summary>
  270.    ''' Contains information about a logical volume.
  271.    ''' For more info, see here:
  272.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx
  273.    ''' </summary>
  274.    <StructLayout(LayoutKind.Sequential)>
  275.    Private Structure DEV_BROADCAST_VOLUME
  276.  
  277.        ''' <summary>
  278.        ''' The size of this structure, in bytes.
  279.        ''' </summary>
  280.        Public Size As UInteger
  281.  
  282.        ''' <summary>
  283.        ''' Set to DBT_DEVTYP_VOLUME (2).
  284.        ''' </summary>
  285.        Public Type As UInteger
  286.  
  287.        ''' <summary>
  288.        ''' Reserved parameter; do not use this.
  289.        ''' </summary>
  290.        Public Reserved As UInteger
  291.  
  292.        ''' <summary>
  293.        ''' The logical unit mask identifying one or more logical units.
  294.        ''' Each bit in the mask corresponds to one logical drive.
  295.        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
  296.        ''' </summary>
  297.        Public Mask As UInteger
  298.  
  299.        ''' <summary>
  300.        ''' This parameter can be one of the following values:
  301.        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
  302.        ''' '0x0002': Indicated logical volume is a network volume.
  303.        ''' </summary>
  304.        Public Flags As UShort
  305.  
  306.    End Structure
  307.  
  308. #End Region
  309.  
  310. #Region " Constructor "
  311.  
  312.    ''' <summary>
  313.    ''' Initializes a new instance of this class.
  314.    ''' </summary>
  315.    ''' <param name="form">The form to assign.</param>
  316.    Public Sub New(ByVal form As Form)
  317.  
  318.        ' Assign the Formulary.
  319.        Me.form = form
  320.  
  321.    End Sub
  322.  
  323. #End Region
  324.  
  325. #Region " Event Handlers "
  326.  
  327.    ''' <summary>
  328.    ''' Assign the handle of the target Form to this NativeWindow,
  329.    ''' necessary to override target Form's WndProc.
  330.    ''' </summary>
  331.    Private Sub SetFormHandle() _
  332.    Handles form.HandleCreated, form.Load, form.Shown
  333.  
  334.        If Not MyBase.Handle.Equals(Me.form.Handle) Then
  335.            MyBase.AssignHandle(Me.form.Handle)
  336.        End If
  337.  
  338.    End Sub
  339.  
  340.    ''' <summary>
  341.    ''' Releases the Handle.
  342.    ''' </summary>
  343.    Private Sub OnHandleDestroyed() _
  344.    Handles form.HandleDestroyed
  345.  
  346.        MyBase.ReleaseHandle()
  347.  
  348.    End Sub
  349.  
  350. #End Region
  351.  
  352. #Region " Private Methods "
  353.  
  354.    ''' <summary>
  355.    ''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object.
  356.    ''' </summary>
  357.    ''' <param name="Device">
  358.    ''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask.
  359.    ''' </param>
  360.    ''' <returns>System.Char.</returns>
  361.    Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char
  362.  
  363.        Dim DriveLetters As Char() =
  364.            {
  365.            "A", "B", "C", "D", "E", "F", "G", "H", "I",
  366.            "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  367.            "S", "T", "U", "V", "W", "X", "Y", "Z"
  368.            }
  369.  
  370.        Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask))
  371.  
  372.        For X As Integer = 0 To DeviceID.Length
  373.  
  374.            If DeviceID(X) Then
  375.                Return DriveLetters(X)
  376.            End If
  377.  
  378.        Next X
  379.  
  380.        Return Nothing
  381.  
  382.    End Function
  383.  
  384. #End Region
  385.  
  386. #Region " WndProc"
  387.  
  388.    ''' <summary>
  389.    ''' Invokes the default window procedure associated with this window to process messages for this Window.
  390.    ''' </summary>
  391.    ''' <param name="m">
  392.    ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
  393.    ''' </param>
  394.    Protected Overrides Sub WndProc(ByRef m As Message)
  395.  
  396.        Select Case m.Msg
  397.  
  398.            Case DeviceEvents.Change ' The hardware has changed.
  399.  
  400.                ' Transform the LParam pointer into the data structure.
  401.                Dim CurrentWDrive As DEV_BROADCAST_VOLUME =
  402.                    CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)
  403.  
  404.                Select Case m.WParam.ToInt32
  405.  
  406.                    Case DeviceEvents.Arrival ' The device is connected.
  407.  
  408.                        ' Get the drive letter of the connected device.
  409.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  410.  
  411.                        ' Get the drive information of the connected device.
  412.                        CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
  413.  
  414.                        ' If it's an storage device then...
  415.                        If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then
  416.  
  417.                            ' Inform that the device is connected by raising the 'DriveConnected' event.
  418.                            RaiseEvent DriveInserted(Me, CurrentDrive)
  419.  
  420.                            ' Add the connected device to the dictionary, to retrieve info.
  421.                            If Not CurrentDrives.ContainsKey(DriveLetter) Then
  422.  
  423.                                CurrentDrives.Add(DriveLetter, CurrentDrive)
  424.  
  425.                            End If ' Not CurrentDrives.ContainsKey(DriveLetter)
  426.  
  427.                        End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume
  428.  
  429.                    Case DeviceEvents.QueryRemove ' The device is preparing to be removed.
  430.  
  431.                        ' Get the letter of the current device being removed.
  432.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  433.  
  434.                        ' If the current device being removed is not in the dictionary then...
  435.                        If Not CurrentDrives.ContainsKey(DriveLetter) Then
  436.  
  437.                            ' Get the device information of the current device being removed.
  438.                            CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
  439.  
  440.                            ' Add the current device to the dictionary,
  441.                            ' to retrieve info before lost it after fully-removal.
  442.                            CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter)))
  443.  
  444.                        End If ' Not CurrentDrives.ContainsKey(DriveLetter)
  445.  
  446.                    Case DeviceEvents.RemoveComplete
  447.  
  448.                        ' Get the letter of the removed device.
  449.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  450.  
  451.                        ' Inform that the device is disconnected by raising the 'DriveDisconnected' event.
  452.                        RaiseEvent DriveRemoved(Me, CurrentDrive)
  453.  
  454.                        ' If the removed device is in the dictionary then...
  455.                        If CurrentDrives.ContainsKey(DriveLetter) Then
  456.  
  457.                            ' Remove the device from the dictionary.
  458.                            CurrentDrives.Remove(DriveLetter)
  459.  
  460.                        End If ' CurrentDrives.ContainsKey(DriveLetter)
  461.  
  462.                End Select ' m.WParam.ToInt32
  463.  
  464.        End Select ' m.Msg
  465.  
  466.        MyBase.WndProc(m) ' Return Message to base message handler.
  467.  
  468.    End Sub
  469.  
  470. #End Region
  471.  
  472. #Region " Hidden methods "
  473.  
  474.    ' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
  475.    ' NOTE: The methods can be re-enabled at any-time if needed.
  476.  
  477.    ''' <summary>
  478.    ''' Assigns a handle to this window.
  479.    ''' </summary>
  480.    <EditorBrowsable(EditorBrowsableState.Never)>
  481.    Public Shadows Sub AssignHandle()
  482.    End Sub
  483.  
  484.    ''' <summary>
  485.    ''' Creates a window and its handle with the specified creation parameters.
  486.    ''' </summary>
  487.    <EditorBrowsable(EditorBrowsableState.Never)>
  488.    Public Shadows Sub CreateHandle()
  489.    End Sub
  490.  
  491.    ''' <summary>
  492.    ''' Creates an object that contains all the relevant information required
  493.    ''' to generate a proxy used to communicate with a remote object.
  494.    ''' </summary>
  495.    <EditorBrowsable(EditorBrowsableState.Never)>
  496.    Public Shadows Sub CreateObjRef()
  497.    End Sub
  498.  
  499.    ''' <summary>
  500.    ''' Invokes the default window procedure associated with this window.
  501.    ''' </summary>
  502.    <EditorBrowsable(EditorBrowsableState.Never)>
  503.    Public Shadows Sub DefWndProc()
  504.    End Sub
  505.  
  506.    ''' <summary>
  507.    ''' Destroys the window and its handle.
  508.    ''' </summary>
  509.    <EditorBrowsable(EditorBrowsableState.Never)>
  510.    Public Shadows Sub DestroyHandle()
  511.    End Sub
  512.  
  513.    ''' <summary>
  514.    ''' Determines whether the specified object is equal to the current object.
  515.    ''' </summary>
  516.    <EditorBrowsable(EditorBrowsableState.Never)>
  517.    Public Shadows Sub Equals()
  518.    End Sub
  519.  
  520.    ''' <summary>
  521.    ''' Serves as the default hash function.
  522.    ''' </summary>
  523.    <EditorBrowsable(EditorBrowsableState.Never)>
  524.    Public Shadows Sub GetHashCode()
  525.    End Sub
  526.  
  527.    ''' <summary>
  528.    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
  529.    ''' </summary>
  530.    <EditorBrowsable(EditorBrowsableState.Never)>
  531.    Public Shadows Sub GetLifetimeService()
  532.    End Sub
  533.  
  534.    ''' <summary>
  535.    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
  536.    ''' </summary>
  537.    <EditorBrowsable(EditorBrowsableState.Never)>
  538.    Public Shadows Sub InitializeLifetimeService()
  539.    End Sub
  540.  
  541.    ''' <summary>
  542.    ''' Releases the handle associated with this window.
  543.    ''' </summary>
  544.    <EditorBrowsable(EditorBrowsableState.Never)>
  545.    Public Shadows Sub ReleaseHandle()
  546.    End Sub
  547.  
  548.    ''' <summary>
  549.    ''' Gets the handle for this window.
  550.    ''' </summary>
  551.    <EditorBrowsable(EditorBrowsableState.Never)>
  552.    Public Shadows Property Handle()
  553.  
  554. #End Region
  555.  
  556. #Region " IDisposable "
  557.  
  558.    ''' <summary>
  559.    ''' To detect redundant calls when disposing.
  560.    ''' </summary>
  561.    Private IsDisposed As Boolean = False
  562.  
  563.    ''' <summary>
  564.    ''' Prevent calls to methods after disposing.
  565.    ''' </summary>
  566.    ''' <exception cref="System.ObjectDisposedException"></exception>
  567.    Private Sub DisposedCheck()
  568.        If Me.IsDisposed Then
  569.            Throw New ObjectDisposedException(Me.GetType().FullName)
  570.        End If
  571.    End Sub
  572.  
  573.    ''' <summary>
  574.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  575.    ''' </summary>
  576.    Public Sub Dispose() Implements IDisposable.Dispose
  577.        Dispose(True)
  578.        GC.SuppressFinalize(Me)
  579.    End Sub
  580.  
  581.    ''' <summary>
  582.    ''' Releases unmanaged and - optionally - managed resources.
  583.    ''' </summary>
  584.    ''' <param name="IsDisposing">
  585.    ''' <c>true</c> to release both managed and unmanaged resources;
  586.    ''' <c>false</c> to release only unmanaged resources.
  587.    ''' </param>
  588.    Protected Sub Dispose(ByVal IsDisposing As Boolean)
  589.  
  590.        If Not Me.IsDisposed Then
  591.  
  592.            If IsDisposing Then
  593.                Me.form = Nothing
  594.                MyBase.ReleaseHandle()
  595.                MyBase.DestroyHandle()
  596.            End If
  597.  
  598.        End If
  599.  
  600.        Me.IsDisposed = True
  601.  
  602.    End Sub
  603.  
  604. #End Region
  605.  
  606. End Class
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #378 en: 19 Febrero 2014, 21:54 pm »

         [RichTextBox] Colorize Words

         Busca coincidencias de texto y las colorea.


Código
  1.    ' Colorize Words
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    ' ColorizeWord(RichTextBox1, "Hello", True,
  7.    '              Color.Red, Color.Black,
  8.    '              New Font(RichTextBox1.Font.FontFamily, RichTextBox1.Font.Size, FontStyle.Italic))
  9.    '
  10.    ' ColorizeWords(RichTextBox1, {"Hello", "[0-9]"}, IgnoreCase:=False,
  11.    '               ForeColor:=Color.Red, BackColor:=Nothing, Font:=Nothing)
  12.  
  13.    ''' <summary>
  14.    ''' Find a word on a RichTextBox and colorizes each match.
  15.    ''' </summary>
  16.    ''' <param name="RichTextBox">Indicates the RichTextBox.</param>
  17.    ''' <param name="Word">Indicates the word to colorize.</param>
  18.    ''' <param name="IgnoreCase">Indicates the ignore case.</param>
  19.    ''' <param name="ForeColor">Indicates the text color.</param>
  20.    ''' <param name="BackColor">Indicates the background color.</param>
  21.    ''' <param name="Font">Indicates the text font.</param>
  22.    ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
  23.    Private Function ColorizeWord(ByVal [RichTextBox] As RichTextBox,
  24.                                  ByVal Word As String,
  25.                                  Optional ByVal IgnoreCase As Boolean = False,
  26.                                  Optional ByVal ForeColor As Color = Nothing,
  27.                                  Optional ByVal BackColor As Color = Nothing,
  28.                                  Optional ByVal [Font] As Font = Nothing) As Boolean
  29.  
  30.        ' Find all the word matches.
  31.        Dim Matches As System.Text.RegularExpressions.MatchCollection =
  32.            System.Text.RegularExpressions.Regex.Matches([RichTextBox].Text, Word,
  33.                                                         If(IgnoreCase,
  34.                                                            System.Text.RegularExpressions.RegexOptions.IgnoreCase,
  35.                                                            System.Text.RegularExpressions.RegexOptions.None))
  36.  
  37.        ' If no matches then return.
  38.        If Not Matches.Count <> 0 Then
  39.            Return False
  40.        End If
  41.  
  42.        ' Set the passed Parameter values.
  43.        If ForeColor.Equals(Nothing) Then ForeColor = [RichTextBox].ForeColor
  44.        If BackColor.Equals(Nothing) Then BackColor = [RichTextBox].BackColor
  45.        If [Font] Is Nothing Then [Font] = [RichTextBox].Font
  46.  
  47.        ' Store the current caret position to restore it at the end.
  48.        Dim CaretPosition As Integer = [RichTextBox].SelectionStart
  49.  
  50.        ' Suspend the control layout to work quicklly.
  51.        [RichTextBox].SuspendLayout()
  52.  
  53.        ' Colorize each match.
  54.        For Each Match As System.Text.RegularExpressions.Match In Matches
  55.  
  56.            [RichTextBox].Select(Match.Index, Match.Length)
  57.            [RichTextBox].SelectionColor = ForeColor
  58.            [RichTextBox].SelectionBackColor = BackColor
  59.            [RichTextBox].SelectionFont = [Font]
  60.  
  61.        Next Match
  62.  
  63.        ' Restore the caret position.
  64.        [RichTextBox].Select(CaretPosition, 0)
  65.  
  66.        ' Restore the control layout.
  67.        [RichTextBox].ResumeLayout()
  68.  
  69.        ' Return successfully
  70.        Return True
  71.  
  72.    End Function
  73.  
  74.    ''' <summary>
  75.    ''' Find multiple words on a RichTextBox and colorizes each match.
  76.    ''' </summary>
  77.    ''' <param name="RichTextBox">Indicates the RichTextBox.</param>
  78.    ''' <param name="Words">Indicates the words to colorize.</param>
  79.    ''' <param name="IgnoreCase">Indicates the ignore case.</param>
  80.    ''' <param name="ForeColor">Indicates the text color.</param>
  81.    ''' <param name="BackColor">Indicates the background color.</param>
  82.    ''' <param name="Font">Indicates the text font.</param>
  83.    ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
  84.    Private Function ColorizeWords(ByVal [RichTextBox] As RichTextBox,
  85.                                   ByVal Words As String(),
  86.                                   Optional ByVal IgnoreCase As Boolean = False,
  87.                                   Optional ByVal ForeColor As Color = Nothing,
  88.                                   Optional ByVal BackColor As Color = Nothing,
  89.                                   Optional ByVal [Font] As Font = Nothing) As Boolean
  90.  
  91.        Dim Success As Boolean = False
  92.  
  93.        For Each Word As String In Words
  94.            Success += ColorizeWord([RichTextBox], Word, IgnoreCase, ForeColor, BackColor, [Font])
  95.        Next Word
  96.  
  97.        Return Success
  98.  
  99.    End Function



[ListView] Remove Duplicates

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

Código
  1.    ' Remove ListView Duplicates
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' Dim Items As ListView.ListViewItemCollection = New ListView.ListViewItemCollection(ListView1)
  6.    ' RemoveListViewDuplicates(Items, 0)    
  7.    '
  8.    ''' <summary>
  9.    ''' Removes duplicated items from a Listview.
  10.    ''' </summary>
  11.    ''' <param name="Items">
  12.    ''' Indicates the items collection.
  13.    ''' </param>
  14.    ''' <param name="SubitemCompare">
  15.    ''' Indicates the subitem column to compare duplicates.
  16.    ''' </param>
  17.    Private Sub RemoveListViewDuplicates(ByVal Items As ListView.ListViewItemCollection,
  18.                                         ByVal SubitemCompare As Integer)
  19.  
  20.        ' Suspend the layout on the Control that owns the Items collection.
  21.        Items.Item(0).ListView.SuspendLayout()
  22.  
  23.        ' Get the duplicated Items.
  24.        Dim Duplicates As ListViewItem() =
  25.            Items.Cast(Of ListViewItem)().
  26.            GroupBy(Function(Item As ListViewItem) Item.SubItems(SubitemCompare).Text).
  27.            Where(Function(g As IGrouping(Of String, ListViewItem)) g.Count <> 1).
  28.            SelectMany(Function(g As IGrouping(Of String, ListViewItem)) g).
  29.            Skip(1).
  30.            ToArray()
  31.  
  32.        ' Delete the duplicated Items.
  33.        For Each Item As ListViewItem In Duplicates
  34.            Items.Remove(Item)
  35.        Next Item
  36.  
  37.        ' Resume the layout on the Control that owns the Items collection.
  38.        Items.Item(0).ListView.ResumeLayout()
  39.  
  40.        Duplicates = Nothing
  41.  
  42.    End Sub
  43.  



Formatea un dispositivo

Código
  1.    ' Format Drive
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' FormatDrive("Z")
  6.    ' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False))
  7.  
  8.    ''' <summary>
  9.    ''' Indicates the possible HardDisk filesystem's for Windows OS.
  10.    ''' </summary>
  11.    Public Enum DriveFileSystem As Integer
  12.  
  13.        ' NOTE:
  14.        ' *****
  15.        ' The numeric values just indicates the max harddisk volume-label character-length for each filesystem.
  16.  
  17.        ''' <summary>
  18.        ''' NTFS FileSystem.
  19.        ''' </summary>
  20.        NTFS = 32
  21.  
  22.        ''' <summary>
  23.        ''' FAT16 FileSystem.
  24.        ''' </summary>
  25.        FAT16 = 11
  26.  
  27.        ''' <summary>
  28.        ''' FAT32 FileSystem.
  29.        ''' </summary>
  30.        FAT32 = FAT16
  31.  
  32.    End Enum
  33.  
  34.    ''' <summary>
  35.    ''' Formats a drive.
  36.    ''' For more info see here:
  37.    ''' http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx
  38.    ''' </summary>
  39.    ''' <param name="DriveLetter">
  40.    ''' Indicates the drive letter to format.
  41.    ''' </param>
  42.    ''' <param name="FileSystem">
  43.    ''' Indicates the filesystem format to use for this volume.
  44.    ''' The default is "NTFS".
  45.    ''' </param>
  46.    ''' <param name="QuickFormat">
  47.    ''' If set to <c>true</c>, formats the volume with a quick format by removing files from the disk
  48.    ''' without scanning the disk for bad sectors.
  49.    ''' Use this option only if the disk has been previously formatted,
  50.    ''' and you know that the disk is not damaged.
  51.    ''' The default is <c>true</c>.
  52.    ''' </param>
  53.    ''' <param name="ClusterSize">
  54.    ''' Disk allocation unit size—cluster size.
  55.    ''' All of the filesystems organizes the hard disk based on cluster size,
  56.    ''' which represents the smallest amount of disk space that can be allocated to hold a file.
  57.    ''' The smaller the cluster size you use, the more efficiently your disk stores information.
  58.    ''' If no cluster size is specified during format, Windows picks defaults based on the size of the volume.
  59.    ''' These defaults have been selected to reduce the amount of space lost and to reduce fragmentation.
  60.    ''' For general use, the default settings are strongly recommended.
  61.    ''' </param>
  62.    ''' <param name="VolumeLabel">
  63.    ''' Indicates the Label to use for the new volume.
  64.    ''' The volume label can contain up to 11 characters for FAT16 and FAT32 volumes,
  65.    ''' and up to 32 characters for NTFS filesystem volumes.
  66.    ''' </param>
  67.    ''' <param name="EnableCompression">Not implemented.</param>
  68.    ''' <returns>
  69.    ''' 0  = Success.
  70.    ''' 1  = Unsupported file system.
  71.    ''' 2  = Incompatible media in drive.
  72.    ''' 3  = Access denied.
  73.    ''' 4  = Call canceled.
  74.    ''' 5  = Call cancellation request too late.
  75.    ''' 6  = Volume write protected.
  76.    ''' 7  = Volume lock failed.
  77.    ''' 8  = Unable to quick format.
  78.    ''' 9  = Input/Output (I/O) error.
  79.    ''' 10 = Invalid volume label.
  80.    ''' 11 = No media in drive.
  81.    ''' 12 = Volume is too small.
  82.    ''' 13 = Volume is too large.
  83.    ''' 14 = Volume is not mounted.
  84.    ''' 15 = Cluster size is too small.
  85.    ''' 16 = Cluster size is too large.
  86.    ''' 17 = Cluster size is beyond 32 bits.
  87.    ''' 18 = Unknown error.
  88.    ''' </returns>
  89.    Public Function FormatDrive(ByVal DriveLetter As Char,
  90.                                Optional ByVal FileSystem As DriveFileSystem = DriveFileSystem.NTFS,
  91.                                Optional ByVal QuickFormat As Boolean = True,
  92.                                Optional ByVal ClusterSize As Integer = Nothing,
  93.                                Optional ByVal VolumeLabel As String = Nothing,
  94.                                Optional ByVal EnableCompression As Boolean = False) As Integer
  95.  
  96.        ' Volume-label error check.
  97.        If Not String.IsNullOrEmpty(VolumeLabel) Then
  98.  
  99.            If VolumeLabel.Length > FileSystem Then
  100.                Throw New Exception(String.Format("Volume label for '{0}' filesystem can't be larger than '{1}' characters.",
  101.                                                  FileSystem.ToString, CStr(FileSystem)))
  102.            End If
  103.  
  104.        End If
  105.  
  106.        Dim Query As String = String.Format("select * from Win32_Volume WHERE DriveLetter = '{0}:'",
  107.                                            Convert.ToString(DriveLetter))
  108.  
  109.        Using WMI As New ManagementObjectSearcher(Query)
  110.  
  111.            Return CInt(WMI.[Get].Cast(Of ManagementObject).First.
  112.                        InvokeMethod("Format",
  113.                                     New Object() {FileSystem, QuickFormat, ClusterSize, VolumeLabel, EnableCompression}))
  114.  
  115.        End Using
  116.  
  117.        Return 18 ' Unknown error.
  118.  
  119.    End Function
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #379 en: 20 Febrero 2014, 06:06 am »

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
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-20-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DocumentConverter.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Example Usages "
  11.  
  12. ' ' HTML 2 RTF
  13. ' RichTextBox1.Rtf = HTMLConverter.Html2Rtf(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
  14. '                                           SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  15. '                                           DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  16. '                                           "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  17. '                                           DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  18. '                                           SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
  19.  
  20.  
  21. ' ' HTML 2 TXT
  22. ' RichTextBox1.Text = HTMLConverter.Html2Txt(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
  23. '                                            SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  24. '                                            DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  25. '                                            "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  26. '                                            DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  27. '                                            SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
  28.  
  29.  
  30. ' ' HTML 2 DOC
  31. ' Dim MSDocText As String = HTMLConverter.Html2Doc(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
  32. '                                                  SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  33. '                                                  DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  34. '                                                  "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  35. '                                                  DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  36. '                                                  SautinSoft.HtmlToRtf.eImageCompatible.MSWord)
  37. ' IO.File.WriteAllText("C:\DocFile.doc", MSDocText, System.Text.Encoding.Default)
  38.  
  39.  
  40. ' ' TXT 2 RTF
  41. ' RichTextBox1.Rtf = DocumentConverter.Txt2Rtf("Hello World!",
  42. '                                              SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  43. '                                              DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  44. '                                              "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  45. '                                              DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  46. '                                              SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
  47.  
  48.  
  49. ' ' TXT 2 DOC
  50. ' Dim MSDocText As String = DocumentConverter.Txt2Doc("Hello World!",
  51. '                                                     SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  52. '                                                     DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  53. '                                                     "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  54. '                                                     DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  55. '                                                     SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
  56. ' IO.File.WriteAllText("C:\DocFile.doc", MSDocText, System.Text.Encoding.Default)
  57.  
  58.  
  59. ' ' RTF 2 HTML
  60. ' Dim HTMLString As String =
  61. '     DocumentConverter.Rtf2Html(IO.File.ReadAllText("C:\File.rtf"),
  62. '                                SautinSoft.RtfToHtml.eOutputFormat.XHTML_10,
  63. '                                SautinSoft.RtfToHtml.eEncoding.UTF_8,
  64. '                                True, "C:\")
  65. '
  66. ' IO.File.WriteAllText("C:\File.html", HTMLString)
  67. ' Process.Start("C:\File.html")
  68.  
  69. #End Region
  70.  
  71. #Region " Imports "
  72.  
  73. Imports SautinSoft
  74. Imports System.Reflection
  75.  
  76. #End Region
  77.  
  78. ''' <summary>
  79. ''' Performs HTML document convertions to other document formats.
  80. ''' </summary>
  81. Public Class DocumentConverter
  82.  
  83. #Region " Enumerations "
  84.  
  85.    ''' <summary>
  86.    ''' Indicates the resulting PageSize.
  87.    ''' </summary>
  88.    Public Enum PageSize
  89.        Auto
  90.        A3
  91.        A4
  92.        A5
  93.        A6
  94.        B5Iso
  95.        B5Jis
  96.        B6
  97.        Executive
  98.        Folio
  99.        Legal
  100.        Letter
  101.        Oficio2
  102.        Statement
  103.    End Enum
  104.  
  105.    ''' <summary>
  106.    ''' Indicates the resulting PageOrientation.
  107.    ''' </summary>
  108.    Public Enum PageOrientation
  109.        Auto
  110.        Landscape
  111.        Portrait
  112.    End Enum
  113.  
  114. #End Region
  115.  
  116. #Region " Private Methods "
  117.  
  118.    ''' <summary>
  119.    ''' Converts a document using 'SautinSoft.HtmlToRtf' library.
  120.    ''' </summary>
  121.    ''' <param name="Text">
  122.    ''' Indicates the text to convert.
  123.    ''' </param>
  124.    ''' <param name="OutputFormat">
  125.    ''' Indicates the output document format.
  126.    ''' </param>
  127.    ''' <param name="TextEncoding">
  128.    ''' Indicates the text encoding.
  129.    ''' </param>
  130.    ''' <param name="PreservePageBreaks">
  131.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  132.    ''' </param>
  133.    ''' <param name="PageSize">
  134.    ''' Indicates the page size.
  135.    ''' </param>
  136.    ''' <param name="Pagenumbers">
  137.    ''' Indicates the page numbers.
  138.    ''' </param>
  139.    ''' <param name="PagenumbersFormat">
  140.    ''' Indicates the page numbers format.
  141.    ''' </param>
  142.    ''' <param name="PageAlignment">
  143.    ''' Indicates the page alignment.
  144.    ''' </param>
  145.    ''' <param name="PageOrientation">
  146.    ''' Indicates the page orientation.
  147.    ''' </param>
  148.    ''' <param name="PageHeader">
  149.    ''' Indicates the page header text.
  150.    ''' </param>
  151.    ''' <param name="PageFooter">
  152.    ''' Indicates the page footer text.
  153.    ''' </param>
  154.    ''' <param name="ImageCompatibility">
  155.    ''' Indicates the image compatibility if the document contains images.
  156.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  157.    ''' Microsoft Word can show images in jpeg, png, etc.
  158.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  159.    ''' </param>
  160.    ''' <returns>System.String.</returns>
  161.    Private Shared Function HtmlToRtfConvert(ByVal [Text] As String,
  162.                                             ByVal InputFormat As HtmlToRtf.eInputFormat,
  163.                                             ByVal OutputFormat As HtmlToRtf.eOutputFormat,
  164.                                             Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  165.                                             Optional ByVal PreservePageBreaks As Boolean = False,
  166.                                             Optional ByVal PageSize As PageSize = PageSize.Auto,
  167.                                             Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  168.                                             Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  169.                                             Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  170.                                             Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  171.                                             Optional ByVal PageHeader As String = Nothing,
  172.                                             Optional ByVal PageFooter As String = Nothing,
  173.                                             Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad) As String
  174.  
  175.        ' Set the PageSize.
  176.        Dim PerformPageSize As New HtmlToRtf.CPageStyle.CPageSize()
  177.        Dim PageSizeMethod As MethodInfo = PerformPageSize.GetType().GetMethod(PageSize.ToString())
  178.  
  179.        ' Set the PageOrientation.
  180.        Dim PerformPageOrientation As New HtmlToRtf.CPageStyle.CPageOrientation
  181.        Dim PageOrientationMethod As MethodInfo = PerformPageOrientation.GetType().GetMethod(PageOrientation.ToString())
  182.  
  183.        ' Call the PageSize method.
  184.        If Not PageSizeMethod Is Nothing Then
  185.            PageSizeMethod.Invoke(PerformPageSize, Nothing)
  186.        Else
  187.            Throw New Exception(String.Format("PageSize method {0} not found.", PageSize.ToString))
  188.        End If
  189.  
  190.        ' Call the PageOrientation method.
  191.        If Not PageOrientationMethod Is Nothing Then
  192.            PageOrientationMethod.Invoke(PerformPageOrientation, Nothing)
  193.        Else
  194.            Throw New Exception(String.Format("PageOrientation method {0} not found.", PageOrientation.ToString))
  195.        End If
  196.  
  197.        ' Instance a new document converter.
  198.        Dim Converter As New HtmlToRtf
  199.  
  200.        ' Customize the conversion options.
  201.        With Converter
  202.  
  203.            .Serial = "123456789012"
  204.  
  205.            .InputFormat = InputFormat
  206.            .OutputFormat = OutputFormat
  207.            .Encoding = TextEncoding
  208.            .PreservePageBreaks = PreservePageBreaks
  209.            .ImageCompatible = ImageCompatibility
  210.            .PageAlignment = PageAlignment
  211.            .PageNumbers = Pagenumbers
  212.            .PageNumbersFormat = PagenumbersFormat
  213.            .PageStyle.PageSize = PerformPageSize
  214.            .PageStyle.PageOrientation = PerformPageOrientation
  215.            If Not String.IsNullOrEmpty(PageHeader) Then .PageStyle.PageHeader.Text(PageHeader)
  216.            If Not String.IsNullOrEmpty(PageFooter) Then .PageStyle.PageFooter.Text(PageFooter)
  217.  
  218.        End With
  219.  
  220.        ' Convert it.
  221.        Return Converter.ConvertString([Text])
  222.  
  223.    End Function
  224.  
  225.    ''' <summary>
  226.    ''' Converts a document using 'SautinSoft.RtfToHtml' library.
  227.    ''' </summary>
  228.    ''' <param name="Text">
  229.    ''' Indicates the text to convert.
  230.    ''' </param>
  231.    ''' <param name="OutputFormat">
  232.    ''' Indicates the output HTML format.
  233.    ''' </param>
  234.    ''' <param name="TextEncoding">
  235.    ''' Indicates the text encoding.
  236.    ''' </param>
  237.    ''' <param name="SaveImagesToDisk">
  238.    ''' If set to <c>true</c>, converted images are saved to a directory on hard drive.
  239.    ''' </param>
  240.    ''' <param name="ImageFolder">
  241.    ''' If 'SaveImagesToDisk' parameter is set to 'True', indicates the image directory to save the images.
  242.    ''' The directory must exist.
  243.    ''' </param>
  244.    ''' <returns>System.String.</returns>
  245.    Private Shared Function RtfToHtmlConvert(ByVal [Text] As String,
  246.                                             Optional ByVal OutputFormat As RtfToHtml.eOutputFormat = RtfToHtml.eOutputFormat.XHTML_10,
  247.                                             Optional ByVal TextEncoding As RtfToHtml.eEncoding = RtfToHtml.eEncoding.UTF_8,
  248.                                             Optional ByVal SaveImagesToDisk As Boolean = False,
  249.                                             Optional ByVal ImageFolder As String = "C:\") As String
  250.  
  251.  
  252.        ' Instance a new document converter.
  253.        Dim Converter As New RtfToHtml
  254.  
  255.        ' Customize the conversion options.
  256.        With Converter
  257.  
  258.            .Serial = "123456789012"
  259.  
  260.            .OutputFormat = OutputFormat
  261.            .Encoding = TextEncoding
  262.            .ImageStyle.IncludeImageInHtml = Not SaveImagesToDisk
  263.            .ImageStyle.ImageFolder = ImageFolder ' This folder must exist to save the converted images.
  264.            .ImageStyle.ImageSubFolder = "Pictures" ' This subfolder will be created by the component to save the images.
  265.            .ImageStyle.ImageFileName = "picture" ' Pattern name for converted images. (Ex: 'Picture1.png')
  266.  
  267.        End With
  268.  
  269.        ' Convert it.
  270.        Return Converter.ConvertString([Text])
  271.  
  272.    End Function
  273.  
  274. #End Region
  275.  
  276. #Region " Public Methods "
  277.  
  278.    ''' <summary>
  279.    ''' Converts HTML text to DOC (Microsoft Word).
  280.    ''' </summary>
  281.    ''' <param name="HtmlText">
  282.    ''' Indicates the HTML text to convert.
  283.    ''' </param>
  284.    ''' <param name="TextEncoding">
  285.    ''' Indicates the text encoding.
  286.    ''' </param>
  287.    ''' <param name="PreservePageBreaks">
  288.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  289.    ''' </param>
  290.    ''' <param name="PageSize">
  291.    ''' Indicates the page size.
  292.    ''' </param>
  293.    ''' <param name="Pagenumbers">
  294.    ''' Indicates the page numbers.
  295.    ''' </param>
  296.    ''' <param name="PagenumbersFormat">
  297.    ''' Indicates the page numbers format.
  298.    ''' </param>
  299.    ''' <param name="PageAlignment">
  300.    ''' Indicates the page alignment.
  301.    ''' </param>
  302.    ''' <param name="PageOrientation">
  303.    ''' Indicates the page orientation.
  304.    ''' </param>
  305.    ''' <param name="PageHeader">
  306.    ''' Indicates the page header text.
  307.    ''' </param>
  308.    ''' <param name="PageFooter">
  309.    ''' Indicates the page footer text.
  310.    ''' </param>
  311.    ''' <param name="ImageCompatibility">
  312.    ''' Indicates the image compatibility if the document contains images.
  313.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  314.    ''' Microsoft Word can show images in jpeg, png, etc.
  315.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  316.    ''' </param>
  317.    ''' <returns>System.String.</returns>
  318.    Public Shared Function Html2Doc(ByVal HtmlText As String,
  319.                                    Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  320.                                    Optional ByVal PreservePageBreaks As Boolean = False,
  321.                                    Optional ByVal PageSize As PageSize = PageSize.Auto,
  322.                                    Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  323.                                    Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  324.                                    Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  325.                                    Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  326.                                    Optional ByVal PageHeader As String = Nothing,
  327.                                    Optional ByVal PageFooter As String = Nothing,
  328.                                    Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  329.                                    ) As String
  330.  
  331.        Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.Doc, TextEncoding,
  332.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  333.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  334.  
  335.    End Function
  336.  
  337.    ''' <summary>
  338.    ''' Converts HTML text to RTF (Rich Text).
  339.    ''' </summary>
  340.    ''' <param name="HtmlText">
  341.    ''' Indicates the HTML text to convert.
  342.    ''' </param>
  343.    ''' <param name="TextEncoding">
  344.    ''' Indicates the text encoding.
  345.    ''' </param>
  346.    ''' <param name="PreservePageBreaks">
  347.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  348.    ''' </param>
  349.    ''' <param name="PageSize">
  350.    ''' Indicates the page size.
  351.    ''' </param>
  352.    ''' <param name="Pagenumbers">
  353.    ''' Indicates the page numbers.
  354.    ''' </param>
  355.    ''' <param name="PagenumbersFormat">
  356.    ''' Indicates the page numbers format.
  357.    ''' </param>
  358.    ''' <param name="PageAlignment">
  359.    ''' Indicates the page alignment.
  360.    ''' </param>
  361.    ''' <param name="PageOrientation">
  362.    ''' Indicates the page orientation.
  363.    ''' </param>
  364.    ''' <param name="PageHeader">
  365.    ''' Indicates the page header text.
  366.    ''' </param>
  367.    ''' <param name="PageFooter">
  368.    ''' Indicates the page footer text.
  369.    ''' </param>
  370.    ''' <param name="ImageCompatibility">
  371.    ''' Indicates the image compatibility if the document contains images.
  372.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  373.    ''' Microsoft Word can show images in jpeg, png, etc.
  374.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  375.    ''' </param>
  376.    ''' <returns>System.String.</returns>
  377.    Public Shared Function Html2Rtf(ByVal HtmlText As String,
  378.                                    Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  379.                                    Optional ByVal PreservePageBreaks As Boolean = False,
  380.                                    Optional ByVal PageSize As PageSize = PageSize.Auto,
  381.                                    Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  382.                                    Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  383.                                    Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  384.                                    Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  385.                                    Optional ByVal PageHeader As String = Nothing,
  386.                                    Optional ByVal PageFooter As String = Nothing,
  387.                                    Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  388.                                    ) As String
  389.  
  390.        Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.Rtf, TextEncoding,
  391.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  392.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  393.  
  394.    End Function
  395.  
  396.    ''' <summary>
  397.    ''' Converts HTML text to TXT (Plain Text).
  398.    ''' </summary>
  399.    ''' <param name="HtmlText">
  400.    ''' Indicates the HTML text to convert.
  401.    ''' </param>
  402.    ''' <param name="TextEncoding">
  403.    ''' Indicates the text encoding.
  404.    ''' </param>
  405.    ''' <param name="PreservePageBreaks">
  406.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  407.    ''' </param>
  408.    ''' <param name="PageSize">
  409.    ''' Indicates the page size.
  410.    ''' </param>
  411.    ''' <param name="Pagenumbers">
  412.    ''' Indicates the page numbers.
  413.    ''' </param>
  414.    ''' <param name="PagenumbersFormat">
  415.    ''' Indicates the page numbers format.
  416.    ''' </param>
  417.    ''' <param name="PageAlignment">
  418.    ''' Indicates the page alignment.
  419.    ''' </param>
  420.    ''' <param name="PageOrientation">
  421.    ''' Indicates the page orientation.
  422.    ''' </param>
  423.    ''' <param name="PageHeader">
  424.    ''' Indicates the page header text.
  425.    ''' </param>
  426.    ''' <param name="PageFooter">
  427.    ''' Indicates the page footer text.
  428.    ''' </param>
  429.    ''' <param name="ImageCompatibility">
  430.    ''' Indicates the image compatibility if the document contains images.
  431.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  432.    ''' Microsoft Word can show images in jpeg, png, etc.
  433.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  434.    ''' </param>
  435.    ''' <returns>System.String.</returns>
  436.    Public Shared Function Html2Txt(ByVal HtmlText As String,
  437.                                    Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  438.                                    Optional ByVal PreservePageBreaks As Boolean = False,
  439.                                    Optional ByVal PageSize As PageSize = PageSize.Auto,
  440.                                    Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  441.                                    Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  442.                                    Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  443.                                    Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  444.                                    Optional ByVal PageHeader As String = Nothing,
  445.                                    Optional ByVal PageFooter As String = Nothing,
  446.                                    Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  447.                                    ) As String
  448.  
  449.        Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.TextAnsi, TextEncoding,
  450.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  451.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  452.  
  453.    End Function
  454.  
  455.    ''' <summary>
  456.    ''' Converts TXT to DOC (Microsoft Word).
  457.    ''' </summary>
  458.    ''' <param name="Text">
  459.    ''' Indicates the plain text to convert.
  460.    ''' </param>
  461.    ''' <param name="TextEncoding">
  462.    ''' Indicates the text encoding.
  463.    ''' </param>
  464.    ''' <param name="PreservePageBreaks">
  465.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  466.    ''' </param>
  467.    ''' <param name="PageSize">
  468.    ''' Indicates the page size.
  469.    ''' </param>
  470.    ''' <param name="Pagenumbers">
  471.    ''' Indicates the page numbers.
  472.    ''' </param>
  473.    ''' <param name="PagenumbersFormat">
  474.    ''' Indicates the page numbers format.
  475.    ''' </param>
  476.    ''' <param name="PageAlignment">
  477.    ''' Indicates the page alignment.
  478.    ''' </param>
  479.    ''' <param name="PageOrientation">
  480.    ''' Indicates the page orientation.
  481.    ''' </param>
  482.    ''' <param name="PageHeader">
  483.    ''' Indicates the page header text.
  484.    ''' </param>
  485.    ''' <param name="PageFooter">
  486.    ''' Indicates the page footer text.
  487.    ''' </param>
  488.    ''' <param name="ImageCompatibility">
  489.    ''' Indicates the image compatibility if the document contains images.
  490.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  491.    ''' Microsoft Word can show images in jpeg, png, etc.
  492.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  493.    ''' </param>
  494.    ''' <returns>System.String.</returns>
  495.    Public Shared Function Txt2Doc(ByVal [Text] As String,
  496.                                   Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  497.                                   Optional ByVal PreservePageBreaks As Boolean = False,
  498.                                   Optional ByVal PageSize As PageSize = PageSize.Auto,
  499.                                   Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  500.                                   Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  501.                                   Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  502.                                   Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  503.                                   Optional ByVal PageHeader As String = Nothing,
  504.                                   Optional ByVal PageFooter As String = Nothing,
  505.                                   Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  506.                                   ) As String
  507.  
  508.        Return HtmlToRtfConvert([Text], HtmlToRtf.eInputFormat.Text, HtmlToRtf.eOutputFormat.Doc, TextEncoding,
  509.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  510.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  511.  
  512.    End Function
  513.  
  514.    ''' <summary>
  515.    ''' Converts TXT to RTF (Rich Text).
  516.    ''' </summary>
  517.    ''' <param name="Text">
  518.    ''' Indicates the plain text to convert.
  519.    ''' </param>
  520.    ''' <param name="TextEncoding">
  521.    ''' Indicates the text encoding.
  522.    ''' </param>
  523.    ''' <param name="PreservePageBreaks">
  524.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  525.    ''' </param>
  526.    ''' <param name="PageSize">
  527.    ''' Indicates the page size.
  528.    ''' </param>
  529.    ''' <param name="Pagenumbers">
  530.    ''' Indicates the page numbers.
  531.    ''' </param>
  532.    ''' <param name="PagenumbersFormat">
  533.    ''' Indicates the page numbers format.
  534.    ''' </param>
  535.    ''' <param name="PageAlignment">
  536.    ''' Indicates the page alignment.
  537.    ''' </param>
  538.    ''' <param name="PageOrientation">
  539.    ''' Indicates the page orientation.
  540.    ''' </param>
  541.    ''' <param name="PageHeader">
  542.    ''' Indicates the page header text.
  543.    ''' </param>
  544.    ''' <param name="PageFooter">
  545.    ''' Indicates the page footer text.
  546.    ''' </param>
  547.    ''' <param name="ImageCompatibility">
  548.    ''' Indicates the image compatibility if the document contains images.
  549.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  550.    ''' Microsoft Word can show images in jpeg, png, etc.
  551.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  552.    ''' </param>
  553.    ''' <returns>System.String.</returns>
  554.    Public Shared Function Txt2Rtf(ByVal [Text] As String,
  555.                                   Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  556.                                   Optional ByVal PreservePageBreaks As Boolean = False,
  557.                                   Optional ByVal PageSize As PageSize = PageSize.Auto,
  558.                                   Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  559.                                   Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  560.                                   Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  561.                                   Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  562.                                   Optional ByVal PageHeader As String = Nothing,
  563.                                   Optional ByVal PageFooter As String = Nothing,
  564.                                   Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  565.                                   ) As String
  566.  
  567.        Return HtmlToRtfConvert([Text], HtmlToRtf.eInputFormat.Text, HtmlToRtf.eOutputFormat.Rtf, TextEncoding,
  568.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  569.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  570.  
  571.    End Function
  572.  
  573.    ''' <summary>
  574.    ''' Converts RtF to HtML.
  575.    ''' </summary>
  576.    ''' <param name="RtfText">
  577.    ''' Indicates the rich text to convert.
  578.    ''' </param>
  579.    ''' <param name="OutputFormat">
  580.    ''' Indicates the output HTML format.
  581.    ''' </param>
  582.    ''' <param name="TextEncoding">
  583.    ''' Indicates the text encoding.
  584.    ''' </param>
  585.    ''' <param name="SaveImagesToDisk">
  586.    ''' If set to <c>true</c>, converted images are saved to a directory on hard drive.
  587.    ''' </param>
  588.    ''' <param name="ImageFolder">
  589.    ''' If 'SaveImagesToDisk' parameter is set to 'True', indicates the image directory to save the images.
  590.    ''' The directory must exist.
  591.    ''' </param>
  592.    ''' <returns>System.String.</returns>
  593.    Public Shared Function Rtf2Html(ByVal RtfText As String,
  594.                                    Optional ByVal OutputFormat As RtfToHtml.eOutputFormat = RtfToHtml.eOutputFormat.XHTML_10,
  595.                                    Optional ByVal TextEncoding As RtfToHtml.eEncoding = RtfToHtml.eEncoding.UTF_8,
  596.                                    Optional ByVal SaveImagesToDisk As Boolean = False,
  597.                                    Optional ByVal ImageFolder As String = "C:\") As String
  598.  
  599.        Return RtfToHtmlConvert(RtFText, OutputFormat, TextEncoding, SaveImagesToDisk, ImageFolder)
  600.  
  601.    End Function
  602.  
  603. #End Region
  604.  
  605. End Class
« Última modificación: 20 Febrero 2014, 06:10 am por Eleкtro » En línea



Páginas: 1 ... 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 [38] 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ... 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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