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

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  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 3 Visitantes están viendo este tema.
Páginas: 1 ... 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 54 55 56 57 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 529,362 veces)
z3nth10n


Desconectado Desconectado

Mensajes: 1.583


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


Ver Perfil WWW
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #410 en: 8 Agosto 2014, 21:07 pm »

Bueno, como siempre se agradecen sugerencias... Acabo de editar el código y sí, ese indentador no es mio, y la verdad es que tampoco me preocupe mucho, como vi que funciono la primera vez pues no le presté mucha atención...

Ahora como verás me he pasado poniendo usings, pero bueno >:D


En línea


Interesados hablad por Discord.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #411 en: 8 Agosto 2014, 21:13 pm »

como vi que funciono la primera vez pues no le presté mucha atención...

Funciona a la primera según se mire, ya que el que escribió ese snippet definió el uso de la codificación UTF-16 (Encoding.Unicode) para todos los casos.

Ahora como verás me he pasado poniendo usings, pero bueno >:D

No te has pasado, has echo lo correcto (me refiero a corregir los fallos del código, aparte de tener que escuchar mi típico sermón xD)

Saludos


« Última modificación: 8 Agosto 2014, 21:16 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #412 en: 10 Agosto 2014, 13:40 pm »

Como partir un archivo en pequeños trozos de cualuier tamaño (no hay limite de 2 GB).

Código
  1.    ' Split File
  2.    ' By Elektro
  3.    '
  4.    ' Example Usage:
  5.    ' SplitFile(InputFile:="C:\Test.mp3", ChunkSize:=(1024L ^ 2L), ChunkName:="Test.Part", ChunkExt:="mp3", Overwrite:=True)
  6.  
  7.    ''' <summary>
  8.    ''' Splits a file into chunks.
  9.    ''' </summary>
  10.    ''' <param name="InputFile">
  11.    ''' Indicates the input file to split.
  12.    ''' </param>
  13.    ''' <param name="ChunkSize">
  14.    ''' Indicates the size of each chunk.
  15.    ''' </param>
  16.    ''' <param name="ChunkName">
  17.    ''' Indicates the chunk filename format.
  18.    ''' Default format is: 'FileName.ChunkIndex.FileExt'
  19.    ''' </param>
  20.    ''' <param name="ChunkExt">
  21.    ''' Indicates the chunk file-extension.
  22.    ''' If this value is <c>Null</c>, the input file-extension will be used.
  23.    ''' </param>
  24.    ''' <param name="Overwrite">
  25.    ''' If set to <c>true</c>, chunk files will replace any existing file;
  26.    ''' Otherwise, an exception will be thrown.
  27.    ''' </param>
  28.    ''' <exception cref="System.OverflowException">'ChunkSize' should be smaller than the Filesize.</exception>
  29.    ''' <exception cref="System.IO.IOException"></exception>
  30.    Public Sub SplitFile(ByVal InputFile As String,
  31.                         ByVal ChunkSize As Long,
  32.                         Optional ByVal ChunkName As String = Nothing,
  33.                         Optional ByVal ChunkExt As String = Nothing,
  34.                         Optional ByVal Overwrite As Boolean = False)
  35.  
  36.        ' FileInfo instance of the input file.
  37.        Dim fInfo As New IO.FileInfo(InputFile)
  38.  
  39.        ' The buffer to read data and write the chunks.
  40.        Dim Buffer As Byte() = New Byte() {}
  41.  
  42.        ' The buffer length.
  43.        Dim BufferSize As Integer = 1048576 ' 1048576 = 1 mb | 33554432 = 32 mb | 67108864 = 64 mb
  44.  
  45.        ' Counts the length of the current chunk file.
  46.        Dim BytesWritten As Long = 0L
  47.  
  48.        ' The total amount of chunks to create.
  49.        Dim ChunkCount As Integer = CInt(Math.Floor(fInfo.Length / ChunkSize))
  50.  
  51.        ' Keeps track of the current chunk.
  52.        Dim ChunkIndex As Integer = 0I
  53.  
  54.        ' A zero-filled string to enumerate the chunk files.
  55.        Dim Zeros As String = String.Empty
  56.  
  57.        ' The given filename for each chunk.
  58.        Dim ChunkFile As String = String.Empty
  59.  
  60.        ' The chunk file basename.
  61.        ChunkName = If(String.IsNullOrEmpty(ChunkName),
  62.                       IO.Path.Combine(fInfo.DirectoryName, IO.Path.GetFileNameWithoutExtension(fInfo.Name)),
  63.                       IO.Path.Combine(fInfo.DirectoryName, ChunkName))
  64.  
  65.        ' The chunk file extension.
  66.        ChunkExt = If(String.IsNullOrEmpty(ChunkExt),
  67.                      fInfo.Extension.Substring(1I),
  68.                      ChunkExt)
  69.  
  70.        ' If ChunkSize is bigger than filesize then...
  71.        If ChunkSize >= fInfo.Length Then
  72.            Throw New OverflowException("'ChunkSize' should be smaller than the Filesize.")
  73.            Exit Sub
  74.  
  75.            ' For cases where a chunksize is smaller than the buffersize.
  76.        ElseIf ChunkSize < BufferSize Then
  77.            BufferSize = CInt(ChunkSize)
  78.  
  79.        End If ' ChunkSize <>...
  80.  
  81.        ' If not file-overwritting is allowed then...
  82.        If Not Overwrite Then
  83.  
  84.            For Index As Integer = 0I To (ChunkCount)
  85.  
  86.                ' Set chunk filename.
  87.                Zeros = New String("0", CStr(ChunkCount).Length - CStr(Index + 1I).Length)
  88.                ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(Index + 1I), ChunkExt)
  89.  
  90.                ' If chunk file already exists then...
  91.                If IO.File.Exists(ChunkFile) Then
  92.  
  93.                    Throw New IO.IOException(String.Format("File already exist: {0}", ChunkFile))
  94.                    Exit Sub
  95.  
  96.                End If ' IO.File.Exists(ChunkFile)
  97.  
  98.            Next Index
  99.  
  100.            Zeros = String.Empty
  101.            ChunkFile = String.Empty
  102.  
  103.        End If ' Overwrite
  104.  
  105.        ' Open the file to start reading bytes.
  106.        Using InputStream As New IO.FileStream(fInfo.FullName, IO.FileMode.Open)
  107.  
  108.            Using BinaryReader As New IO.BinaryReader(InputStream)
  109.  
  110.                While (InputStream.Position < InputStream.Length)
  111.  
  112.                    ' Set chunk filename.
  113.                    Zeros = New String("0", CStr(ChunkCount).Length - CStr(ChunkIndex + 1I).Length)
  114.                    ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(ChunkIndex + 1I), ChunkExt)
  115.  
  116.                    ' Reset written byte-length counter.
  117.                    BytesWritten = 0L
  118.  
  119.                    ' Create the chunk file to Write the bytes.
  120.                    Using OutputStream As New IO.FileStream(ChunkFile, IO.FileMode.Create)
  121.  
  122.                        Using BinaryWriter As New IO.BinaryWriter(OutputStream)
  123.  
  124.                            ' Read until reached the end-bytes of the input file.
  125.                            While (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)
  126.  
  127.                                ' Read bytes from the original file (BufferSize byte-length).
  128.                                Buffer = BinaryReader.ReadBytes(BufferSize)
  129.  
  130.                                ' Write those bytes in the chunk file.
  131.                                BinaryWriter.Write(Buffer)
  132.  
  133.                                ' Increment the size counter.
  134.                                BytesWritten += Buffer.Count
  135.  
  136.                            End While ' (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)
  137.  
  138.                            OutputStream.Flush()
  139.  
  140.                        End Using ' BinaryWriter
  141.  
  142.                    End Using ' OutputStream
  143.  
  144.                    ChunkIndex += 1I 'Increment file counter
  145.  
  146.                End While ' InputStream.Position < InputStream.Length
  147.  
  148.            End Using ' BinaryReader
  149.  
  150.        End Using ' InputStream
  151.  
  152.    End Sub
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #413 en: 11 Agosto 2014, 18:46 pm »

una Helper-Class para procesar los pixeles de una imagen, buscar un color especifico y devolver las coordenadas, obtener un rango de píxeles, etc.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 07-11-2014
  4. ' ***********************************************************************
  5. ' <copyright file="PixelUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12.  
  13. ' **************************************************
  14. ' Count the number of Pixels that contains the image
  15. ' **************************************************
  16. '
  17. '' Create a new bitmap.
  18. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
  19. '
  20. '' Instance a PixelUtil Class.
  21. 'Dim bmpPixelUtil As New PixelUtil(bmp)
  22. '
  23. '' Display the pixel count.
  24. 'MessageBox.Show(String.Format("Total amount of Pixels: {0}", CStr(bmpPixelUtil.PixelCount)))
  25.  
  26.  
  27. ' ************************************************
  28. ' Searchs for an specific pixel color in the image
  29. ' ************************************************
  30. '
  31. '' Create a new bitmap.
  32. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
  33. '
  34. '' Instance a PixelUtil Class.
  35. 'Dim bmpPixelUtil As New PixelUtil(bmp)
  36. '
  37. '' Specify the RGB PixelColor to search.
  38. 'Dim FindColor As Color = Color.FromArgb(255, 174, 201)
  39. '
  40. '' Get the pixel data.
  41. 'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.SearchColor(FindColor)
  42. '
  43. '' Loop through each pixel.
  44. 'For Each Pixel As PixelUtil.PixelData In FoundPixels
  45. '
  46. '    Dim sb As New System.Text.StringBuilder
  47. '    With sb
  48. '
  49. '        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
  50. '        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
  51. '
  52. '        MessageBox.Show(.ToString, "Pixel-Color Search")
  53. '
  54. '        .Clear()
  55. '
  56. '    End With
  57. '
  58. 'Next Pixel
  59.  
  60.  
  61. ' *********************************************************************
  62. ' Retrieve the index, color, and coordinates of each pixel in the image
  63. ' *********************************************************************
  64. '
  65. '' Create a new bitmap.
  66. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
  67. '
  68. '' Instance a PixelUtil Class.
  69. 'Dim bmpPixelUtil As New PixelUtil(bmp)
  70. '
  71. '' Get the pixel data.
  72. 'Dim Pixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData()
  73. '
  74. '' Loop through each pixel.
  75. 'For Each Pixel As PixelUtil.PixelData In Pixels
  76. '
  77. '    Dim sb As New System.Text.StringBuilder
  78. '    With sb
  79. '
  80. '        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
  81. '        .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString))
  82. '        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
  83. '
  84. '        MessageBox.Show(.ToString, "Pixel Search")
  85. '
  86. '        .Clear()
  87. '
  88. '    End With
  89. '
  90. 'Next Pixel
  91.  
  92.  
  93. ' ****************************************************************************
  94. ' Retrieve the index, color, and coordinates of a range of pixels in the image
  95. ' ****************************************************************************
  96. '
  97. '' Create a new bitmap.
  98. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
  99. '
  100. '' Instance a PixelUtil Class.
  101. 'Dim bmpPixelUtil As New PixelUtil(bmp)
  102. '
  103. '' Specify the pixel range to retrieve.
  104. 'Dim RangeMin As Integer = 1919I
  105. 'Dim RangeMax As Integer = 1921I
  106. '
  107. '' Get the pixel data.
  108. 'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData(RangeMin, RangeMax)
  109. '
  110. '' Loop through each pixel.
  111. 'For Each Pixel As PixelUtil.PixelData In FoundPixels
  112. '
  113. '    Dim sb As New System.Text.StringBuilder
  114. '    With sb
  115. '
  116. '        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
  117. '        .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString))
  118. '        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
  119. '
  120. '        MessageBox.Show(.ToString, "Pixel-Color Search")
  121. '
  122. '        .Clear()
  123. '
  124. '    End With
  125. '
  126. 'Next Pixel
  127.  
  128.  
  129. #End Region
  130.  
  131. #Region " Imports "
  132.  
  133. Imports System.ComponentModel
  134. Imports System.Drawing.Imaging
  135. Imports System.Runtime.InteropServices
  136.  
  137. #End Region
  138.  
  139. #Region " PixelUtil "
  140.  
  141. Public Class PixelUtil
  142.  
  143. #Region " Vars, Properties "
  144.  
  145.    Private _PixelData As List(Of PixelData) = Nothing
  146.    Private _bmp As Bitmap = Nothing
  147.    Private _PixelCount As Integer = Nothing
  148.  
  149.    ''' <summary>
  150.    ''' Gets the Bitmap object.
  151.    ''' </summary>
  152.    ''' <value>The BMP.</value>
  153.    Public ReadOnly Property bmp As Bitmap
  154.        Get
  155.            Return Me._bmp
  156.        End Get
  157.    End Property
  158.  
  159.    ''' <summary>
  160.    ''' Gets the total amount of pixels that contains the Bitmap.
  161.    ''' </summary>
  162.    ''' <value>The pixel count.</value>
  163.    Public ReadOnly Property PixelCount As Integer
  164.        Get
  165.            Return Me._PixelCount
  166.        End Get
  167.    End Property
  168.  
  169. #End Region
  170.  
  171. #Region " Classes "
  172.  
  173.    ''' <summary>
  174.    ''' Stores specific pixel information of an image.
  175.    ''' </summary>
  176.    Public Class PixelData
  177.  
  178.        ''' <summary>
  179.        ''' Gets or sets the pixel index.
  180.        ''' </summary>
  181.        ''' <value>The pixel index.</value>
  182.        Public Property Index As Integer
  183.  
  184.        ''' <summary>
  185.        ''' Gets or sets the pixel color.
  186.        ''' </summary>
  187.        ''' <value>The pixel color.</value>
  188.        Public Property Color As Color
  189.  
  190.        ''' <summary>
  191.        ''' Gets or sets the pixel coordinates relative to the image.
  192.        ''' </summary>
  193.        ''' <value>The pixel coordinates.</value>
  194.        Public Property Coordinates As Point
  195.  
  196.    End Class
  197.  
  198. #End Region
  199.  
  200. #Region " Constructors "
  201.  
  202.    ''' <summary>
  203.    ''' Prevents a default instance of the <see cref="PixelUtil"/> class from being created.
  204.    ''' </summary>
  205.    Private Sub New()
  206.    End Sub
  207.  
  208.    ''' <summary>
  209.    ''' Initializes a new instance of the <see cref="PixelUtil"/> class.
  210.    ''' </summary>
  211.    ''' <param name="bmp">Indicates the Bitmap image to process it's pixels.</param>
  212.    ''' <exception cref="System.Exception">PixelFormat unsupported.</exception>
  213.    Public Sub New(ByVal bmp As Bitmap)
  214.  
  215.        If Not bmp.PixelFormat = PixelFormat.Format24bppRgb Then
  216.            Throw New Exception("PixelFormat unsupported.")
  217.        End If
  218.  
  219.        Me._bmp = bmp
  220.        Me._PixelCount = Me.[Count]
  221.  
  222.    End Sub
  223.  
  224. #End Region
  225.  
  226. #Region " Public Methods "
  227.  
  228.    ''' <summary>
  229.    ''' Returns a <c>'PixelData'</c> object containing information about each pixel in the image.
  230.    ''' </summary>
  231.    ''' <returns>List(Of PixelData).</returns>
  232.    Public Function GetPixelData() As List(Of PixelData)
  233.  
  234.        If Me._PixelData Is Nothing Then
  235.  
  236.            Me._PixelData = New List(Of PixelData)
  237.  
  238.            ' Lock the Bitmap bits.
  239.            Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height)
  240.            Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat)
  241.  
  242.            ' Get the address of the first line.
  243.            Dim Pointer As IntPtr = bmpData.Scan0
  244.  
  245.            ' Hold the bytes of the bitmap into a Byte-Array.
  246.            ' NOTE: This code is specific to a bitmap with 24 bits per pixels.
  247.            Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height)
  248.            Dim rgbData(bmpBytes - 1) As Byte
  249.  
  250.            ' Copy the RGB values into the array.
  251.            Marshal.Copy(Pointer, rgbData, 0, bmpBytes)
  252.  
  253.            ' Unlock the Bitmap bits.
  254.            Me._bmp.UnlockBits(bmpData)
  255.  
  256.            ' Loop through each 24bpp-RGB value.
  257.            For rgbIndex As Integer = 2 To rgbData.Length - 1 Step 3
  258.  
  259.                ' Set the pixel Data.
  260.                Dim Pixel As New PixelData
  261.  
  262.                With Pixel
  263.  
  264.                    .Index = rgbIndex \ 3I
  265.  
  266.                    .Color = Color.FromArgb(red:=rgbData(rgbIndex),
  267.                                            green:=rgbData(rgbIndex - 1I),
  268.                                            blue:=rgbData(rgbIndex - 2I))
  269.  
  270.                    .Coordinates = New Point(X:=(.Index Mod bmpRect.Width),
  271.                                             Y:=(.Index - (.Index Mod bmpRect.Width)) \ bmpRect.Width)
  272.  
  273.                End With
  274.  
  275.                ' Add the PixelData into the list.
  276.                Me._PixelData.Add(Pixel)
  277.  
  278.            Next rgbIndex
  279.  
  280.        End If
  281.  
  282.        Return Me._PixelData
  283.  
  284.    End Function
  285.  
  286.    ''' <summary>
  287.    ''' Returns a <c>'PixelData'</c> object containing information about a range of pixels in the image.
  288.    ''' </summary>
  289.    ''' <returns>List(Of PixelData).</returns>
  290.    ''' <exception cref="System.Exception">Pixel index is out of range</exception>
  291.    Public Function GetPixelData(ByVal RangeMin As Integer,
  292.                                 ByVal RangeMax As Integer) As List(Of PixelData)
  293.  
  294.        If Not (Me._PixelCount >= RangeMin AndAlso Me._PixelCount <= RangeMax) Then
  295.            Throw New Exception("Pixel index is out of range.")
  296.            Return Nothing
  297.        End If
  298.  
  299.        ' Return the Pixel range.
  300.        Return (From Pixel As PixelData In Me.GetPixelData()
  301.                Where (Pixel.Index >= RangeMin AndAlso Pixel.Index <= RangeMax)).ToList
  302.  
  303.    End Function
  304.  
  305.    ''' <summary>
  306.    ''' Searchs for the specified pixel-color inside the image and returns all the matches.
  307.    ''' </summary>
  308.    ''' <param name="PixelColor">Indicates the color to find.</param>
  309.    ''' <returns>List(Of PixelData).</returns>
  310.    Public Function SearchColor(ByVal PixelColor As Color) As List(Of PixelData)
  311.  
  312.        Return (From Pixel As PixelData In Me.GetPixelData
  313.                Where Pixel.Color = PixelColor).ToList
  314.  
  315.    End Function
  316.  
  317. #End Region
  318.  
  319. #Region " Private Methods "
  320.  
  321.    ''' <summary>
  322.    ''' Counts the number of pixels that contains the image.
  323.    ''' </summary>
  324.    ''' <returns>The number of pixels.</returns>
  325.    Private Function [Count]() As Integer
  326.  
  327.        ' Lock the Bitmap bits.
  328.        Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height)
  329.        Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat)
  330.  
  331.        ' Get the address of the first line.
  332.        Dim Pointer As IntPtr = bmpData.Scan0
  333.  
  334.        ' Hold the bytes of the bitmap into a Byte-Array.
  335.        ' NOTE: This code is specific to a bitmap with 24 bits per pixels.
  336.        Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height)
  337.        Dim rgbData(bmpBytes - 1) As Byte
  338.  
  339.        ' Copy the RGB values into the array.
  340.        Marshal.Copy(Pointer, rgbData, 0, bmpBytes)
  341.  
  342.        ' Unlock the Bitmap bits.
  343.        Me._bmp.UnlockBits(bmpData)
  344.  
  345.        Return rgbData.Count
  346.  
  347.    End Function
  348.  
  349. #End Region
  350.  
  351. #Region " Hidden Methods "
  352.  
  353.    ''' <summary>
  354.    ''' Serves as a hash function for a particular type.
  355.    ''' </summary>
  356.    <EditorBrowsable(EditorBrowsableState.Never)>
  357.    Public Shadows Sub GetHashCode()
  358.    End Sub
  359.  
  360.    ''' <summary>
  361.    ''' Determines whether the specified System.Object is equal to the current System.Object.
  362.    ''' </summary>
  363.    <EditorBrowsable(EditorBrowsableState.Never)>
  364.    Public Shadows Sub Equals()
  365.    End Sub
  366.  
  367.    ''' <summary>
  368.    ''' Returns a String that represents the current object.
  369.    ''' </summary>
  370.    <EditorBrowsable(EditorBrowsableState.Never)>
  371.    Public Shadows Sub ToString()
  372.    End Sub
  373.  
  374. #End Region
  375.  
  376. End Class
  377.  
  378. #End Region
  379.  
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #414 en: 11 Agosto 2014, 18:47 pm »

Una helper-class para administrar el contenido del archivo HOSTS de Windows:

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-11-2014
  4. ' ***********************************************************************
  5. ' <copyright file="HostsFile.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Public Class HostsFileTestClass
  13. '
  14. '    Private Sub HostsFileTestHandler() Handles MyBase.Shown
  15. '
  16. '        ' Instance the HostsFile Class.
  17. '        Dim Hosts As New HostsFile()
  18. '
  19. '        ' Set a new mapping.
  20. '        Dim Mapping As New HostsFile.MappingInfo
  21. '        With Mapping
  22. '            .HostName = "cuantodanio.es"
  23. '            .IP = Hosts.LOCALHOST ' "127.0.0.1"
  24. '            .Comment = "Test mapping comment."
  25. '        End With
  26. '
  27. '        With Hosts
  28. '
  29. '            ' Delete the Host file.
  30. '            If .FileExists Then
  31. '                .FileDelete()
  32. '            End If
  33. '
  34. '            ' Create a new one Hosts file.
  35. '            .FileCreate()
  36. '
  37. '            ' Add some new mappings.
  38. '            .Add(Mapping)
  39. '            .Add(HostName:="www.youtube.com", IP:=.LOCALHOST, Comment:="Test mapping comment")
  40. '
  41. '            ' Check whether a mapping exists.
  42. '            If .IsMapped(Mapping) Then
  43. '                ' Disable the mapping.
  44. '                .Disable(Mapping)
  45. '            End If
  46. '
  47. '            ' Check whether an existing mapping is disabled.
  48. '            If .IsDisabled("www.youtube.com") Then
  49. '                ' Remove the mapping.
  50. '                .Remove("www.youtube.com")
  51. '            End If
  52. '
  53. '            ' Open the HOSTS file with the specified text-editor.
  54. '            .FileOpen("C:\Program Files\Sublime Text\sublime_text.exe")
  55. '
  56. '        End With
  57. '
  58. '        ' Get the IP of a mapped Hostname.
  59. '        MessageBox.Show("cuantodanio.es: " & Hosts.GetMappingFromHostname("cuantodanio.es").IP)
  60. '
  61. '        ' Get all the hostname mappings
  62. '        Dim Mappings As List(Of HostsFile.MappingInfo) = Hosts.GetMappings()
  63. '        For Each MappingInfo As HostsFile.MappingInfo In Mappings
  64. '
  65. '            Dim sb As New System.Text.StringBuilder
  66. '            With sb
  67. '                .AppendLine(String.Format("Hostname...: {0}", MappingInfo.HostName))
  68. '                .AppendLine(String.Format("IP Address.: {0}", MappingInfo.IP))
  69. '                .AppendLine(String.Format("Comment....: {0}", MappingInfo.Comment))
  70. '                .AppendLine(String.Format("Is Enabled?: {0}", Not MappingInfo.IsDisabled))
  71. '            End With
  72. '
  73. '            MessageBox.Show(sb.ToString, "HostsFile Mappings", MessageBoxButtons.OK, MessageBoxIcon.Information)
  74. '
  75. '        Next MappingInfo
  76. '
  77. '        ' Get all the hostname mappings that matches an ip address
  78. '        Dim MappingMatches As List(Of HostsFile.MappingInfo) = Hosts.GetMappingsFromIP(Hosts.LOCALHOST)
  79. '
  80. '    End Sub
  81. '
  82. 'End Class
  83.  
  84. #End Region
  85.  
  86. #Region " Imports "
  87.  
  88. Imports System.IO
  89. Imports System.Net
  90. Imports System.Text
  91.  
  92. #End Region
  93.  
  94. #Region " Hosts File "
  95.  
  96. ''' <summary>
  97. ''' Manages the Windows HOSTS file to map Hostnames to IP addresses.
  98. ''' </summary>
  99. Public Class HostsFile
  100.  
  101. #Region " Constructors "
  102.  
  103.    ''' <summary>
  104.    ''' Initializes a new instance of the <see cref="HostsFile"/> class.
  105.    ''' </summary>
  106.    ''' <param name="HOSTSLocation">
  107.    ''' Optionaly indicates a custom Hosts file location.
  108.    ''' Default value is 'X:\Windows\System32\Drivers\etc\hosts'.
  109.    ''' </param>
  110.    Public Sub New(Optional ByVal HOSTSLocation As String = Nothing)
  111.  
  112.        If Not String.IsNullOrEmpty(HOSTSLocation) Then
  113.            Me._HOSTSLocation = HOSTSLocation
  114.        End If
  115.  
  116.    End Sub
  117.  
  118.    ''' <summary>
  119.    ''' Prevents a default instance of the <see cref="HostsFile"/> class from being created.
  120.    ''' </summary>
  121.    Private Sub New()
  122.    End Sub
  123.  
  124. #End Region
  125.  
  126. #Region " Properties "
  127.  
  128.    ''' <summary>
  129.    ''' The Hosts file location.
  130.    ''' </summary>
  131.    ''' <value>The Hosts file location.</value>
  132.    Public ReadOnly Property HOSTSLocation As String
  133.        Get
  134.            Return _HOSTSLocation
  135.        End Get
  136.    End Property
  137.    Private SysDir As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
  138.    Private _HOSTSLocation As String = Path.Combine(SysDir, "Drivers\etc\hosts")
  139.  
  140.    ''' <summary>
  141.    ''' The Hosts file encoding.
  142.    ''' The encoding must be <see cref="Encoding.Default"/> (ANSI) or <see cref="Encoding.UTF8"/> (UTF-8 without BOM),
  143.    ''' otherwise the entries will be ignored by Windows.
  144.    ''' </summary>
  145.    ''' <value>The Hosts file encoding.</value>
  146.    Public Property HOSTSEncoding As Encoding
  147.        Get
  148.            Return _HOSTSEncoding
  149.        End Get
  150.        Set(ByVal value As Encoding)
  151.            Me._HOSTSEncoding = value
  152.        End Set
  153.    End Property
  154.    Private _HOSTSEncoding As Encoding = Encoding.Default
  155.  
  156.    ''' <summary>
  157.    ''' Gets or sets the default 'LocalHost' IP address.
  158.    ''' In most computers the default address is '127.0.0.1'.
  159.    ''' </summary>
  160.    ''' <value>The default LocalHost.</value>
  161.    Public Property LOCALHOST As String
  162.        Get
  163.            Return Me._LOCALHOST
  164.        End Get
  165.        Set(ByVal value As String)
  166.            Me._LOCALHOST = value
  167.        End Set
  168.    End Property
  169.    Private _LOCALHOST As String = "127.0.0.1"
  170.  
  171.    ''' <summary>
  172.    ''' Gets the default Hosts file header.
  173.    ''' </summary>
  174.    Private ReadOnly HostsHeader As String =
  175. <a><![CDATA[
  176. # Copyright (c) 1993-2009 Microsoft Corp.
  177. #
  178. # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
  179. #
  180. # This file contains the mappings of IP addresses to host names. Each
  181. # entry should be kept on an individual line. The IP address should
  182. # be placed in the first column followed by the corresponding host name.
  183. # The IP address and the host name should be separated by at least one
  184. # space.
  185. ]]></a>.Value
  186.  
  187. #End Region
  188.  
  189. #Region " Types "
  190.  
  191. #Region " MappingInfo "
  192.  
  193.    ''' <summary>
  194.    ''' Specifies info of a HOSTS file mapping.
  195.    ''' </summary>
  196.    Public Class MappingInfo
  197.  
  198.        ''' <summary>
  199.        ''' Gets or sets the hostname.
  200.        ''' </summary>
  201.        ''' <value>The hostname.</value>
  202.        Public Property HostName As String
  203.  
  204.        ''' <summary>
  205.        ''' Gets or sets the IP address.
  206.        ''' </summary>
  207.        ''' <value>The IP address.</value>
  208.        Public Property IP As String
  209.  
  210.        ''' <summary>
  211.        ''' Gets or sets the mapping comment.
  212.        ''' </summary>
  213.        ''' <value>The mapping comment.</value>
  214.        Public Property Comment As String
  215.  
  216.        ''' <summary>
  217.        ''' This value is reserved.
  218.        ''' Gets a value indicating whether the mapping is disabled in the HOSTS file.
  219.        ''' </summary>
  220.        ''' <value><c>true</c> if the mapping is disabled, <c>false</c> otherwise.</value>
  221.        Public Property IsDisabled As Boolean
  222.  
  223.    End Class
  224.  
  225. #End Region
  226.  
  227. #End Region
  228.  
  229. #Region " Public Methods "
  230.  
  231.    ''' <summary>
  232.    ''' Adds a new mapping.
  233.    ''' </summary>
  234.    ''' <param name="HostName">Indicates the Hostname.</param>
  235.    ''' <param name="IP">Indicates the IP address.</param>
  236.    ''' <param name="Comment">Indicates a comment for this mapping.</param>
  237.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  238.    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
  239.    ''' <exception cref="System.Exception">Hostname is already mapped.</exception>
  240.    Public Sub Add(ByVal HostName As String,
  241.                   ByVal IP As String,
  242.                   Optional ByVal Comment As String = Nothing)
  243.  
  244.        If Not Me.FileExists() Then ' Hosts file does not exists.
  245.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  246.  
  247.        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
  248.            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))
  249.  
  250.        ElseIf Me.IsMapped(HostName) Then ' Hostname is already mapped.
  251.            Throw New Exception(String.Format("Hostname '{0}' is already mapped.", HostName))
  252.  
  253.        Else ' Add the entry.
  254.  
  255.            ' Fix value spacing.
  256.            Dim EntryFormat As String =
  257.                IP & HostName.Insert(0I, ControlChars.Tab) &
  258.                If(Not String.IsNullOrEmpty(Comment),
  259.                   Comment.Insert(0I, ControlChars.Tab & "#"c),
  260.                   String.Empty)
  261.  
  262.            ' Write the mapping.
  263.            File.AppendAllText(Me._HOSTSLocation, Environment.NewLine & EntryFormat, Me._HOSTSEncoding)
  264.  
  265.        End If
  266.  
  267.    End Sub
  268.  
  269.    ''' <summary>
  270.    ''' Adds a new mapping.
  271.    ''' </summary>
  272.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  273.    Public Sub Add(ByVal MappingInfo As MappingInfo)
  274.  
  275.        Me.Add(MappingInfo.HostName, MappingInfo.IP, MappingInfo.Comment)
  276.  
  277.    End Sub
  278.  
  279.    ''' <summary>
  280.    ''' Disables an existing mapping.
  281.    ''' </summary>
  282.    ''' <param name="HostName">Indicates the Hostname.</param>
  283.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  284.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  285.    ''' <exception cref="System.Exception">Hostname is already disabled.</exception>
  286.    Public Sub Disable(ByVal HostName As String)
  287.  
  288.        If Not Me.FileExists() Then ' Hosts file does not exists.
  289.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  290.  
  291.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  292.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  293.  
  294.        ElseIf Me.IsDisabled(HostName) Then ' Hostname is already disabled.
  295.            Throw New Exception(String.Format("Hostname: '{0}' is already disabled.", HostName))
  296.  
  297.        Else ' Disable the mapping.
  298.  
  299.            ' Retrieve the HOSTS file content.
  300.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  301.  
  302.            ' Iterate the mappings.
  303.            For X As Integer = 0I To (Hosts.Count - 1I)
  304.  
  305.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  306.  
  307.                    ' Retrieve the HostName of this mapping.
  308.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  309.  
  310.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  311.  
  312.                        ' Disable the mapping.
  313.                        Hosts(X) = Hosts(X).Insert(0I, "#"c)
  314.                        Exit For
  315.  
  316.                    End If ' Host.Equals(...)
  317.  
  318.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  319.  
  320.            Next X
  321.  
  322.            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)
  323.  
  324.        End If
  325.  
  326.    End Sub
  327.  
  328.    ''' <summary>
  329.    ''' Disables an existing mapping.
  330.    ''' </summary>
  331.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  332.    Public Sub Disable(ByVal MappingInfo As MappingInfo)
  333.  
  334.        Me.Disable(MappingInfo.HostName)
  335.  
  336.    End Sub
  337.  
  338.    ''' <summary>
  339.    ''' Removes a mapping.
  340.    ''' </summary>
  341.    ''' <param name="HostName">Indicates the Hostname.</param>
  342.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  343.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  344.    Public Sub Remove(ByVal HostName As String)
  345.  
  346.        If Not Me.FileExists() Then ' Hosts file does not exists.
  347.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  348.  
  349.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  350.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  351.  
  352.        Else ' Remove the mapping.
  353.  
  354.            ' Retrieve the HOSTS file content.
  355.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  356.  
  357.            ' Iterate the mappings.
  358.            For X As Integer = 0I To (Hosts.Count - 1I)
  359.  
  360.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  361.  
  362.                    ' Retrieve the HostName of this mapping.
  363.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  364.  
  365.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  366.  
  367.                        ' Remove the mapping.
  368.                        Hosts.RemoveAt(X)
  369.                        Exit For
  370.  
  371.                    End If ' Host.Equals(...)
  372.  
  373.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  374.  
  375.            Next X
  376.  
  377.            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)
  378.  
  379.        End If
  380.  
  381.    End Sub
  382.  
  383.    ''' <summary>
  384.    ''' Removes a mapping.
  385.    ''' </summary>
  386.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  387.    Public Sub Remove(ByVal MappingInfo As MappingInfo)
  388.  
  389.        Me.Remove(MappingInfo.HostName)
  390.  
  391.    End Sub
  392.  
  393.    ''' <summary>
  394.    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings.
  395.    ''' </summary>
  396.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  397.    Public Function GetMappings() As List(Of MappingInfo)
  398.  
  399.        If Not Me.FileExists() Then ' Hosts file does not exists.
  400.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  401.  
  402.        Else ' Get the mapping.
  403.  
  404.            ' Retrieve the HOSTS file content.
  405.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  406.            Dim Mappings As New List(Of MappingInfo)
  407.  
  408.            ' Iterate the mappings.
  409.            For X As Integer = 0I To (Hosts.Count - 1I)
  410.  
  411.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  412.  
  413.                    ' Retrieve the mapping parts.
  414.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  415.  
  416.                    Dim MappingInfo As New MappingInfo
  417.                    With MappingInfo
  418.                        .HostName = Parts(1I)
  419.                        .IP = Parts(0I).Replace("#"c, String.Empty)
  420.                        .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  421.                        .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  422.                    End With ' MappingInfo
  423.  
  424.                    Mappings.Add(MappingInfo)
  425.  
  426.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  427.  
  428.            Next X
  429.  
  430.            Return Mappings
  431.  
  432.        End If
  433.  
  434.    End Function
  435.  
  436.    ''' <summary>
  437.    ''' Gets a <see cref="MappingInfo"/> instance containing the mapping info of a Hostname.
  438.    ''' </summary>
  439.    ''' <param name="HostName">Indicates the Hostname.</param>
  440.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  441.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  442.    Public Function GetMappingFromHostname(ByVal Hostname As String) As MappingInfo
  443.  
  444.        If Not Me.FileExists() Then ' Hosts file does not exists.
  445.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  446.  
  447.        ElseIf Not Me.IsMapped(Hostname) Then ' Hostname is not mapped.
  448.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", Hostname))
  449.  
  450.        Else ' Get the mapping.
  451.  
  452.            ' Retrieve the HOSTS file content.
  453.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  454.            Dim MappingInfo As New MappingInfo
  455.  
  456.            ' Iterate the mappings.
  457.            For X As Integer = 0I To (Hosts.Count - 1I)
  458.  
  459.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  460.  
  461.                    ' Retrieve the mapping parts.
  462.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  463.  
  464.                    If Parts(1I).Equals(Hostname, StringComparison.OrdinalIgnoreCase) Then
  465.  
  466.                        With MappingInfo
  467.                            .HostName = Parts(1I)
  468.                            .IP = Parts(0I).Replace("#"c, String.Empty)
  469.                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  470.                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  471.                        End With ' MappingInfo
  472.  
  473.                        Exit For
  474.  
  475.                    End If ' Parts(1I).Equals(Hostname)...
  476.  
  477.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  478.  
  479.            Next X
  480.  
  481.            Return MappingInfo
  482.  
  483.        End If
  484.  
  485.    End Function
  486.  
  487.    ''' <summary>
  488.    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings
  489.    ''' matching the specified IP address.
  490.    ''' </summary>
  491.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  492.    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
  493.    Public Function GetMappingsFromIP(ByVal IP As String) As List(Of MappingInfo)
  494.  
  495.        If Not Me.FileExists() Then ' Hosts file does not exists.
  496.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  497.  
  498.        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
  499.            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))
  500.  
  501.        Else ' Get the mapping.
  502.  
  503.            ' Retrieve the HOSTS file content.
  504.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  505.            Dim Mappings As New List(Of MappingInfo)
  506.  
  507.            ' Iterate the mappings.
  508.            For X As Integer = 0I To (Hosts.Count - 1I)
  509.  
  510.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  511.  
  512.                    ' Retrieve the mapping parts.
  513.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  514.  
  515.                    If Parts(0I).Replace("#"c, String.Empty).Equals(IP) Then
  516.  
  517.                        Dim MappingInfo As New MappingInfo
  518.                        With MappingInfo
  519.                            .HostName = Parts(1I)
  520.                            .IP = Parts(0I).Replace("#"c, String.Empty)
  521.                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  522.                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  523.                        End With ' MappingInfo
  524.  
  525.                        Mappings.Add(MappingInfo)
  526.  
  527.                    End If
  528.  
  529.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  530.  
  531.            Next X
  532.  
  533.            Return Mappings
  534.  
  535.        End If
  536.  
  537.    End Function
  538.  
  539.    ''' <summary>
  540.    ''' Checks whether a HostName is already mapped.
  541.    ''' </summary>
  542.    ''' <param name="HostName">Indicates the Hostname.</param>
  543.    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
  544.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  545.    Public Function IsMapped(ByVal HostName As String) As Boolean
  546.  
  547.        If Not Me.FileExists() Then ' Hosts file does not exists.
  548.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  549.  
  550.        Else
  551.            ' Retrieve the HOSTS file content.
  552.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  553.  
  554.            ' Iterate the mappings.
  555.            For X As Integer = 0I To (Hosts.Count - 1I)
  556.  
  557.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  558.  
  559.                    ' Retrieve the HostName of this mapping.
  560.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  561.  
  562.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  563.                        Return True
  564.                    End If ' Host.Equals(HostName)...
  565.  
  566.                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...
  567.  
  568.            Next X
  569.  
  570.            Return False
  571.  
  572.        End If ' Not Me.Exists()...
  573.  
  574.    End Function
  575.  
  576.    ''' <summary>
  577.    ''' Checks whether a HostName is already mapped.
  578.    ''' </summary>
  579.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  580.    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
  581.    Public Function IsMapped(ByVal MappingInfo As MappingInfo) As Boolean
  582.  
  583.        Return Me.IsMapped(MappingInfo.HostName)
  584.  
  585.    End Function
  586.  
  587.    ''' <summary>
  588.    ''' Checks whether a HostName is already disabled.
  589.    ''' </summary>
  590.    ''' <param name="HostName">Indicates the Hostname.</param>
  591.    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
  592.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  593.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  594.    Public Function IsDisabled(ByVal HostName As String) As Boolean
  595.  
  596.        If Not Me.FileExists() Then ' Hosts file does not exists.
  597.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  598.  
  599.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  600.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  601.  
  602.        Else
  603.            ' Retrieve the HOSTS file content.
  604.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  605.            Dim Result As Boolean = False
  606.  
  607.            ' Iterate the mappings.
  608.            For X As Integer = 0I To (Hosts.Count - 1I)
  609.  
  610.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  611.  
  612.                    ' Retrieve the HostName of this mapping.
  613.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  614.  
  615.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  616.                        Result = Hosts(X).TrimStart.StartsWith("#"c)
  617.                        Exit For
  618.                    End If ' Host.Equals(HostName)...
  619.  
  620.                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...
  621.  
  622.            Next X
  623.  
  624.            Return Result
  625.  
  626.        End If
  627.  
  628.    End Function
  629.  
  630.    ''' <summary>
  631.    ''' Checks whether a HostName is already disabled.
  632.    ''' </summary>
  633.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  634.    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
  635.    Public Function IsDisabled(ByVal MappingInfo As MappingInfo) As Boolean
  636.  
  637.        Return Me.IsDisabled(MappingInfo.HostName)
  638.  
  639.    End Function
  640.  
  641.    ''' <summary>
  642.    ''' Checks whether the Hosts file exists.
  643.    ''' </summary>
  644.    ''' <returns><c>true</c> if Hosts file exists, <c>false</c> otherwise.</returns>
  645.    Public Function FileExists() As Boolean
  646.  
  647.        Return File.Exists(Me._HOSTSLocation)
  648.  
  649.    End Function
  650.  
  651.    ''' <summary>
  652.    ''' Creates the Hosts file.
  653.    ''' </summary>
  654.    Public Sub FileCreate()
  655.  
  656.        If Me.FileExists() Then
  657.            File.Delete(Me._HOSTSLocation)
  658.        End If
  659.  
  660.        File.WriteAllText(Me._HOSTSLocation, Me.HostsHeader, Me._HOSTSEncoding)
  661.  
  662.    End Sub
  663.  
  664.    ''' <summary>
  665.    ''' Deletes the Hosts file.
  666.    ''' </summary>
  667.    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
  668.    Public Sub FileDelete()
  669.  
  670.        If Not Me.FileExists() Then
  671.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  672.  
  673.        Else
  674.            File.Delete(Me._HOSTSLocation)
  675.  
  676.        End If
  677.  
  678.    End Sub
  679.  
  680.    ''' <summary>
  681.    ''' Cleans the Hosts file.
  682.    ''' This removes all the mappings and adds the default file header.
  683.    ''' </summary>
  684.    Public Sub FileClean()
  685.  
  686.        Me.FileCreate()
  687.  
  688.    End Sub
  689.  
  690.    ''' <summary>
  691.    ''' Opens the Hosts file with the specified process.
  692.    ''' </summary>
  693.    ''' <param name="Process">
  694.    ''' Indicates the process location.
  695.    ''' Default value is: "notepad.exe".
  696.    ''' </param>
  697.    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
  698.    ''' <exception cref="System.IO.FileNotFoundException">Process not found.</exception>
  699.    Public Sub FileOpen(Optional ByVal Process As String = "notepad.exe")
  700.  
  701.        If Not Me.FileExists Then
  702.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  703.  
  704.        ElseIf Not File.Exists(Process) Then
  705.            Throw New FileNotFoundException("Process not found.", Process)
  706.  
  707.        Else
  708.            Diagnostics.Process.Start(Process, ControlChars.Quote & Me._HOSTSLocation & ControlChars.Quote)
  709.  
  710.        End If
  711.  
  712.    End Sub
  713.  
  714. #End Region
  715.  
  716. #Region " Private Methods "
  717.  
  718.    ''' <summary>
  719.    ''' Validates an IP address.
  720.    ''' </summary>
  721.    ''' <param name="Address">The IP address.</param>
  722.    ''' <returns><c>true</c> if IP is in the proper format, <c>false</c> otherwise.</returns>
  723.    Private Function ValidateIP(ByVal Address As String) As Boolean
  724.  
  725.        Dim IP As IPAddress = Nothing
  726.        Return IPAddress.TryParse(Address, IP)
  727.  
  728.    End Function
  729.  
  730. #End Region
  731.  
  732. End Class
  733.  
  734. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #415 en: 15 Agosto 2014, 20:33 pm »

Una Class para cortar y unir archivos al mismo estilo que WinRAR (me refiero a la enumeración de los archivos partidos, este no comprime solo corta).

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-15-2014
  4. ' ***********************************************************************
  5. ' <copyright file="FileSplitter.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.ComponentModel
  13. Imports System.IO
  14.  
  15. #End Region
  16.  
  17. Public Class FileSplitter
  18.  
  19. #Region " Properties "
  20.  
  21.    ''' <summary>
  22.    ''' Gets or sets the buffer-size to split or merge, in Bytes.
  23.    ''' Default value is: 1048576 bytes (1 megabyte).
  24.    ''' </summary>
  25.    ''' <value>The buffer-size.</value>
  26.    Public Property BufferSize As Integer = 1048576I
  27.  
  28. #End Region
  29.  
  30. #Region " Events "
  31.  
  32. #Region " EventHandlers "
  33.  
  34.    ''' <summary>
  35.    ''' Occurs when the progress changes splitting a file.
  36.    ''' </summary>
  37.    Public Event SplitProgressChanged As EventHandler(Of SplitProgressChangedArgs)
  38.  
  39.    ''' <summary>
  40.    ''' Occurs when the progress changes merging a file.
  41.    ''' </summary>
  42.    Public Event MergeProgressChanged As EventHandler(Of MergeProgressChangedArgs)
  43.  
  44. #End Region
  45.  
  46. #Region " Event Args "
  47.  
  48. #Region " SplitProgressChanged "
  49.  
  50.    ''' <summary>
  51.    ''' Contains the Event arguments of the SplitProgressChanged Event.
  52.    ''' </summary>
  53.    Public Class SplitProgressChangedArgs : Inherits EventArgs
  54.  
  55. #Region " Constructors "
  56.  
  57.        ''' <summary>
  58.        ''' Prevents a default instance of the <see cref="SplitProgressChangedArgs"/> class from being created.
  59.        ''' </summary>
  60.        Private Sub New()
  61.        End Sub
  62.  
  63.        ''' <summary>
  64.        ''' Initializes a new instance of the <see cref="SplitProgressChangedArgs"/> class.
  65.        ''' </summary>
  66.        ''' <param name="TotalProgress">The total progress value.</param>
  67.        ''' <param name="ChunkProgress">The current chunk progress value.</param>
  68.        ''' <param name="ChunksToCreate">The amount of chunks to create.</param>
  69.        ''' <param name="ChunksCreated">The amount of created chunks.</param>
  70.        Public Sub New(ByVal TotalProgress As Double,
  71.                       ByVal ChunkProgress As Double,
  72.                       ByVal ChunksToCreate As Integer,
  73.                       ByVal ChunksCreated As Integer)
  74.  
  75.            Me._TotalProgress = TotalProgress
  76.            Me._ChunkProgress = ChunkProgress
  77.            Me._ChunksToCreate = ChunksToCreate
  78.            Me._ChunksCreated = ChunksCreated
  79.  
  80.        End Sub
  81.  
  82. #End Region
  83.  
  84. #Region " Properties "
  85.  
  86.        ''' <summary>
  87.        ''' Gets the total progress value.
  88.        ''' (From 0 to 100)
  89.        ''' </summary>
  90.        ''' <value>The total progress value.</value>
  91.        Public ReadOnly Property TotalProgress As Double
  92.            Get
  93.                Return Me._TotalProgress
  94.            End Get
  95.        End Property
  96.        Private _TotalProgress As Double = 0.0R
  97.  
  98.        ''' <summary>
  99.        ''' Gets the current chunk progress value.
  100.        ''' </summary>
  101.        ''' <value>The current chunk progress value.</value>
  102.        Public ReadOnly Property ChunkProgress As Double
  103.            Get
  104.                Return Me._ChunkProgress
  105.            End Get
  106.        End Property
  107.        Private _ChunkProgress As Double = 0.0R
  108.  
  109.        ''' <summary>
  110.        ''' Gets the amount of chunks to create.
  111.        ''' </summary>
  112.        ''' <value>The amount of chunks to create.</value>
  113.        Public ReadOnly Property ChunksToCreate As Integer
  114.            Get
  115.                Return Me._ChunksToCreate
  116.            End Get
  117.        End Property
  118.        Private _ChunksToCreate As Integer = 0I
  119.  
  120.        ''' <summary>
  121.        ''' Gets the amount of created chunks.
  122.        ''' </summary>
  123.        ''' <value>The amount of created chunks.</value>
  124.        Public ReadOnly Property ChunksCreated As Integer
  125.            Get
  126.                Return Me._ChunksCreated
  127.            End Get
  128.        End Property
  129.        Private _ChunksCreated As Integer = 0I
  130.  
  131. #End Region
  132.  
  133. #Region " Hidden Methods "
  134.  
  135.        ''' <summary>
  136.        ''' Serves as a hash function for a particular type.
  137.        ''' </summary>
  138.        <EditorBrowsable(EditorBrowsableState.Never)>
  139.        Public Shadows Sub GetHashCode()
  140.        End Sub
  141.  
  142.        ''' <summary>
  143.        ''' Determines whether the specified System.Object instances are considered equal.
  144.        ''' </summary>
  145.        <EditorBrowsable(EditorBrowsableState.Never)>
  146.        Public Shadows Sub Equals()
  147.        End Sub
  148.  
  149.        ''' <summary>
  150.        ''' Determines whether the specified System.Object instances are the same instance.
  151.        ''' </summary>
  152.        <EditorBrowsable(EditorBrowsableState.Never)>
  153.        Private Shadows Sub ReferenceEquals()
  154.        End Sub
  155.  
  156.        ''' <summary>
  157.        ''' Returns a String that represents the current object.
  158.        ''' </summary>
  159.        <EditorBrowsable(EditorBrowsableState.Never)>
  160.        Public Shadows Sub ToString()
  161.        End Sub
  162.  
  163. #End Region
  164.  
  165.    End Class
  166.  
  167. #End Region
  168.  
  169. #Region " MergeProgressChangedArgs "
  170.  
  171.    ''' <summary>
  172.    ''' Contains the Event arguments of the MergeProgressChangedArgs Event.
  173.    ''' </summary>
  174.    Public Class MergeProgressChangedArgs : Inherits EventArgs
  175.  
  176. #Region " Constructors "
  177.  
  178.        ''' <summary>
  179.        ''' Prevents a default instance of the <see cref="MergeProgressChangedArgs"/> class from being created.
  180.        ''' </summary>
  181.        Private Sub New()
  182.        End Sub
  183.  
  184.        ''' <summary>
  185.        ''' Initializes a new instance of the <see cref="MergeProgressChangedArgs"/> class.
  186.        ''' </summary>
  187.        ''' <param name="TotalProgress">The total progress value.</param>
  188.        ''' <param name="ChunkProgress">The current chunk progress value.</param>
  189.        ''' <param name="ChunksToMerge">The amount of chunks to merge.</param>
  190.        ''' <param name="ChunksMerged">The amount of merged chunks.</param>
  191.        Public Sub New(ByVal TotalProgress As Double,
  192.                       ByVal ChunkProgress As Double,
  193.                       ByVal ChunksToMerge As Integer,
  194.                       ByVal ChunksMerged As Integer)
  195.  
  196.            Me._TotalProgress = TotalProgress
  197.            Me._ChunkProgress = ChunkProgress
  198.            Me._ChunksToMerge = ChunksToMerge
  199.            Me._ChunksMerged = ChunksMerged
  200.  
  201.        End Sub
  202.  
  203. #End Region
  204.  
  205. #Region " Properties "
  206.  
  207.        ''' <summary>
  208.        ''' Gets the total progress value.
  209.        ''' (From 0 to 100)
  210.        ''' </summary>
  211.        ''' <value>The total progress value.</value>
  212.        Public ReadOnly Property TotalProgress As Double
  213.            Get
  214.                Return Me._TotalProgress
  215.            End Get
  216.        End Property
  217.        Private _TotalProgress As Double = 0.0R
  218.  
  219.        ''' <summary>
  220.        ''' Gets the current chunk progress value.
  221.        ''' </summary>
  222.        ''' <value>The current chunk progress value.</value>
  223.        Public ReadOnly Property ChunkProgress As Double
  224.            Get
  225.                Return Me._ChunkProgress
  226.            End Get
  227.        End Property
  228.        Private _ChunkProgress As Double = 0.0R
  229.  
  230.        ''' <summary>
  231.        ''' Gets the amount of chunks to merge.
  232.        ''' </summary>
  233.        ''' <value>The amount of chunks to merge.</value>
  234.        Public ReadOnly Property ChunksToMerge As Integer
  235.            Get
  236.                Return Me._ChunksToMerge
  237.            End Get
  238.        End Property
  239.        Private _ChunksToMerge As Integer = 0I
  240.  
  241.        ''' <summary>
  242.        ''' Gets the amount of merged chunks.
  243.        ''' </summary>
  244.        ''' <value>The amount of merged chunks.</value>
  245.        Public ReadOnly Property ChunksMerged As Integer
  246.            Get
  247.                Return Me._ChunksMerged
  248.            End Get
  249.        End Property
  250.        Private _ChunksMerged As Integer = 0I
  251.  
  252. #End Region
  253.  
  254. #Region " Hidden Methods "
  255.  
  256.        ''' <summary>
  257.        ''' Serves as a hash function for a particular type.
  258.        ''' </summary>
  259.        <EditorBrowsable(EditorBrowsableState.Never)>
  260.        Public Shadows Sub GetHashCode()
  261.        End Sub
  262.  
  263.        ''' <summary>
  264.        ''' Determines whether the specified System.Object instances are considered equal.
  265.        ''' </summary>
  266.        <EditorBrowsable(EditorBrowsableState.Never)>
  267.        Public Shadows Sub Equals()
  268.        End Sub
  269.  
  270.        ''' <summary>
  271.        ''' Determines whether the specified System.Object instances are the same instance.
  272.        ''' </summary>
  273.        <EditorBrowsable(EditorBrowsableState.Never)>
  274.        Private Shadows Sub ReferenceEquals()
  275.        End Sub
  276.  
  277.        ''' <summary>
  278.        ''' Returns a String that represents the current object.
  279.        ''' </summary>
  280.        <EditorBrowsable(EditorBrowsableState.Never)>
  281.        Public Shadows Sub ToString()
  282.        End Sub
  283.  
  284. #End Region
  285.  
  286.    End Class
  287.  
  288. #End Region
  289.  
  290. #End Region
  291.  
  292. #End Region
  293.  
  294. #Region " Hidden Methods "
  295.  
  296.    ''' <summary>
  297.    ''' Serves as a hash function for a particular type.
  298.    ''' </summary>
  299.    <EditorBrowsable(EditorBrowsableState.Never)>
  300.    Public Shadows Sub GetHashCode()
  301.    End Sub
  302.  
  303.    ''' <summary>
  304.    ''' Determines whether the specified System.Object instances are considered equal.
  305.    ''' </summary>
  306.    <EditorBrowsable(EditorBrowsableState.Never)>
  307.    Public Shadows Sub Equals()
  308.    End Sub
  309.  
  310.    ''' <summary>
  311.    ''' Determines whether the specified System.Object instances are the same instance.
  312.    ''' </summary>
  313.    <EditorBrowsable(EditorBrowsableState.Never)>
  314.    Private Shadows Sub ReferenceEquals()
  315.    End Sub
  316.  
  317.    ''' <summary>
  318.    ''' Returns a String that represents the current object.
  319.    ''' </summary>
  320.    <EditorBrowsable(EditorBrowsableState.Never)>
  321.    Public Shadows Sub ToString()
  322.    End Sub
  323.  
  324. #End Region
  325.  
  326. #Region " Public Methods "
  327.  
  328.    ''' <summary>
  329.    ''' Splits the specified file.
  330.    ''' </summary>
  331.    ''' <param name="InputFile">Indicates the file to split.</param>
  332.    ''' <param name="ChunkSize">Indicates the size of each chunk.</param>
  333.    ''' <param name="ChunkName">Indicates the name-format for the chunks.</param>
  334.    ''' <param name="ChunkExt">Indicates the file-extension for the chunks.</param>
  335.    ''' <param name="Overwrite">
  336.    ''' If set to <c>true</c> any existing file will be overwritten if needed to create a chunk,
  337.    ''' otherwise, an exception will be thrown.
  338.    ''' </param>
  339.    ''' <param name="DeleteAfterSplit">If set to <c>true</c> the input file will be deleted after a successful split.</param>
  340.    ''' <exception cref="System.IO.FileNotFoundException">The specified file doesn't exists.</exception>
  341.    ''' <exception cref="System.IO.IOException">File already exists.</exception>
  342.    ''' <exception cref="System.OverflowException">'ChunkSize' should be smaller than the Filesize.</exception>
  343.    Public Sub Split(ByVal InputFile As String,
  344.                     ByVal ChunkSize As Long,
  345.                     Optional ByVal ChunkName As String = Nothing,
  346.                     Optional ByVal ChunkExt As String = Nothing,
  347.                     Optional ByVal Overwrite As Boolean = False,
  348.                     Optional ByVal DeleteAfterSplit As Boolean = False)
  349.  
  350.        If Not File.Exists(InputFile) Then
  351.            Throw New FileNotFoundException("The specified file doesn't exists.", InputFile)
  352.            Exit Sub
  353.        End If
  354.  
  355.        ' The progress event arguments.
  356.        Dim ProgressArguments As SplitProgressChangedArgs
  357.  
  358.        ' FileInfo instance of the input file.
  359.        Dim fInfo As New FileInfo(InputFile)
  360.  
  361.        ' The total filesize to split, in bytes.
  362.        Dim TotalSize As Long = fInfo.Length
  363.  
  364.        ' The remaining size to calculate the percentage, in bytes.
  365.        Dim SizeRemaining As Long = TotalSize
  366.  
  367.        ' Counts the length of the current chunk file to calculate the percentage, in bytes.
  368.        Dim SizeWritten As Long = 0L
  369.  
  370.        ' The buffer to read data and write the chunks.
  371.        Dim Buffer As Byte() = New Byte() {}
  372.  
  373.        ' The buffer length.
  374.        Dim BufferLength As Integer = Me.BufferSize
  375.  
  376.        ' The total amount of chunks to create.
  377.        Dim ChunkCount As Integer = CInt(Math.Floor(fInfo.Length / ChunkSize))
  378.  
  379.        ' Keeps track of the current chunk.
  380.        Dim ChunkIndex As Integer = 0I
  381.  
  382.        ' Keeps track of the total percentage done.
  383.        Dim TotalProgress As Double = 0.0R
  384.  
  385.        ' Keeps track of the current chunk percentage done.
  386.        Dim ChunkProgress As Double = 0.0R
  387.  
  388.        ' A zero-filled string to enumerate the chunk files.
  389.        Dim Zeros As String = String.Empty
  390.  
  391.        ' The given filename for each chunk.
  392.        Dim ChunkFile As String = String.Empty
  393.  
  394.        ' The chunk file basename.
  395.        ChunkName = If(String.IsNullOrEmpty(ChunkName),
  396.                       Path.Combine(fInfo.DirectoryName, Path.GetFileNameWithoutExtension(fInfo.Name)),
  397.                       Path.Combine(fInfo.DirectoryName, ChunkName))
  398.  
  399.        ' The chunk file extension.
  400.        ChunkExt = If(String.IsNullOrEmpty(ChunkExt),
  401.                      fInfo.Extension.Substring(1I),
  402.                      ChunkExt)
  403.  
  404.        ' If ChunkSize is bigger than filesize then...
  405.        If ChunkSize >= fInfo.Length Then
  406.            Throw New OverflowException("'ChunkSize' should be smaller than the Filesize.")
  407.            Exit Sub
  408.  
  409.            ' For cases where a chunksize is smaller than the buffersize.
  410.        ElseIf ChunkSize < BufferLength Then
  411.            BufferLength = CInt(ChunkSize)
  412.  
  413.        End If ' ChunkSize <>...
  414.  
  415.        ' If not file-overwrite is allowed then...
  416.        If Not Overwrite Then
  417.  
  418.            For Index As Integer = 0I To (ChunkCount)
  419.  
  420.                ' Set chunk filename.
  421.                Zeros = New String("0", CStr(ChunkCount).Length - CStr(Index + 1I).Length)
  422.                ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(Index + 1I), ChunkExt)
  423.  
  424.                ' If chunk file already exists then...
  425.                If File.Exists(ChunkFile) Then
  426.  
  427.                    Throw New IOException(String.Format("File already exists: {0}", ChunkFile))
  428.                    Exit Sub
  429.  
  430.                End If ' File.Exists(ChunkFile)
  431.  
  432.            Next Index
  433.  
  434.            Zeros = String.Empty
  435.            ChunkFile = String.Empty
  436.  
  437.        End If ' Overwrite
  438.  
  439.        ' Open the file to start reading bytes.
  440.        Using InputStream As New FileStream(fInfo.FullName, FileMode.Open)
  441.  
  442.            Using BinaryReader As New BinaryReader(InputStream)
  443.  
  444.                While (InputStream.Position < InputStream.Length)
  445.  
  446.                    ' Set chunk filename.
  447.                    Zeros = New String("0", CStr(ChunkCount).Length - CStr(ChunkIndex + 1I).Length)
  448.                    ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(ChunkIndex + 1I), ChunkExt)
  449.  
  450.                    ' Reset written byte-length counter.
  451.                    SizeWritten = 0L
  452.  
  453.  
  454.                    ' Create the chunk file to Write the bytes.
  455.                    Using OutputStream As New FileStream(ChunkFile, FileMode.Create)
  456.  
  457.                        Using BinaryWriter As New BinaryWriter(OutputStream)
  458.  
  459.                            ' Read until reached the end-bytes of the input file.
  460.                            While (SizeWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)
  461.  
  462.                                ' Read bytes from the original file (BufferSize byte-length).
  463.                                Buffer = BinaryReader.ReadBytes(BufferLength)
  464.  
  465.                                ' Write those bytes in the chunk file.
  466.                                BinaryWriter.Write(Buffer)
  467.  
  468.                                ' Increment the bytes-written counter.
  469.                                SizeWritten += Buffer.Count
  470.  
  471.                                ' Decrease the bytes-remaining counter.
  472.                                SizeRemaining -= Buffer.Count
  473.  
  474.                                ' Set the total progress.
  475.                                TotalProgress = (TotalSize - SizeRemaining) * (100I / TotalSize)
  476.  
  477.                                ' Set the current chunk progress.
  478.                                ChunkProgress =
  479.                                    If(Not ChunkIndex = ChunkCount,
  480.                                       (100I / ChunkSize) * (SizeWritten - BufferLength),
  481.                                       (100I / (InputStream.Length - (ChunkSize * ChunkIndex))) * (SizeWritten - BufferLength))
  482.  
  483.                                ' Set the progress event-arguments.
  484.                                ProgressArguments =
  485.                                    New SplitProgressChangedArgs(
  486.                                        TotalProgress:=If(Not TotalProgress > 99.9R, TotalProgress, 99.9R),
  487.                                        ChunkProgress:=ChunkProgress,
  488.                                        ChunksToCreate:=ChunkCount + 1I,
  489.                                        ChunksCreated:=ChunkIndex)
  490.  
  491.                                ' Report the progress event-arguments.
  492.                                RaiseEvent SplitProgressChanged(Me, ProgressArguments)
  493.  
  494.                            End While ' (SizeWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)
  495.  
  496.                            OutputStream.Flush()
  497.  
  498.                        End Using ' BinaryWriter
  499.  
  500.                    End Using ' OutputStream
  501.  
  502.                    ChunkIndex += 1I 'Increment the chunk file counter.
  503.  
  504.                End While ' InputStream.Position < InputStream.Length
  505.  
  506.            End Using ' BinaryReader
  507.  
  508.        End Using ' InputStream
  509.  
  510.        ' Set the progress event-arguments.
  511.        ProgressArguments =
  512.            New SplitProgressChangedArgs(
  513.                TotalProgress:=100.0R,
  514.                ChunkProgress:=100.0R,
  515.                ChunksToCreate:=ChunkCount + 1I,
  516.                ChunksCreated:=ChunkIndex)
  517.  
  518.        ' Report the progress event-arguments.
  519.        RaiseEvent SplitProgressChanged(Me, ProgressArguments)
  520.  
  521.    End Sub
  522.  
  523.    ''' <summary>
  524.    ''' Merges the specified file.
  525.    ''' </summary>
  526.    ''' <param name="InputFile">
  527.    ''' Indicates the file to merge its chunks.
  528.    ''' This should be the first chunk file (eg: 'File.Part.01.mkv')
  529.    ''' </param>
  530.    ''' <param name="OutputFile">Indicates the output file.</param>
  531.    ''' <param name="Overwrite">
  532.    ''' If set to <c>true</c>, in case that the 'OutputFile' exists it will be overwritten,
  533.    ''' otherwise, an exception will be thrown.
  534.    ''' </param>
  535.    ''' <param name="DeleteChunksAfterMerged">
  536.    ''' If set to <c>true</c>, the chunks will be deleted after a successful.
  537.    ''' </param>
  538.    ''' <exception cref="System.IO.FileNotFoundException">The specified file doesn't exists.</exception>
  539.    ''' <exception cref="System.IO.IOException">File already exists.</exception>
  540.    ''' <exception cref="System.Exception">The last chunk file is missing.</exception>
  541.    ''' <exception cref="System.Exception">Unexpected chunk filesize-count detected.</exception>
  542.    Public Sub Merge(ByVal InputFile As String,
  543.                     Optional ByVal OutputFile As String = Nothing,
  544.                     Optional ByVal Overwrite As Boolean = False,
  545.                     Optional DeleteChunksAfterMerged As Boolean = False)
  546.  
  547.        If Not File.Exists(InputFile) Then
  548.            Throw New FileNotFoundException("The specified file doesn't exists.", InputFile)
  549.            Exit Sub
  550.  
  551.        ElseIf Not Overwrite AndAlso File.Exists(OutputFile) Then
  552.            Throw New IOException(String.Format("File already exists: {0}", OutputFile))
  553.            Exit Sub
  554.  
  555.        End If
  556.  
  557.        ' The progress event arguments.
  558.        Dim ProgressArguments As MergeProgressChangedArgs
  559.  
  560.        ' FileInfo instance of the input chunk file.
  561.        Dim fInfo As New FileInfo(InputFile)
  562.  
  563.        ' Get the filename without extension.
  564.        Dim Filename As String = Path.GetFileNameWithoutExtension(fInfo.FullName)
  565.        ' Remove the chunk enumeration from the filename.
  566.        Filename = Filename.Substring(0I, Filename.LastIndexOf("."c))
  567.  
  568.        ' TSet the pattern to find the chunk files to merge.
  569.        Dim ChunkPatternSearch As String =
  570.            Filename & ".*" & If(Not String.IsNullOrEmpty(fInfo.Extension), fInfo.Extension, "")
  571.  
  572.        ' Retrieve all the chunk files to merge them.
  573.        Dim Chunks As IEnumerable(Of FileInfo) =
  574.           From Chunk As String In
  575.           Directory.GetFiles(fInfo.DirectoryName, ChunkPatternSearch, SearchOption.TopDirectoryOnly)
  576.           Select New FileInfo(Chunk)
  577.  
  578.        If Chunks.Count < 2I Then ' If chunk files are less than 2 then...
  579.            Throw New Exception("The last chunk file is missing.")
  580.            Exit Sub
  581.        End If
  582.  
  583.        ' The total filesize to merge, in bytes.
  584.        Dim TotalSize As Long =
  585.            (From Chunk As FileInfo In Chunks Select Chunk.Length).Sum
  586.  
  587.        ' Gets the filesize of the chunk files and the last chunk file, in bytes.
  588.        Dim ChunkSizes As Long() =
  589.            (From Chunk As FileInfo In Chunks
  590.             Select Chunk.Length Order By Length Descending
  591.            ).Distinct.ToArray
  592.  
  593.        If ChunkSizes.Count > 2I Then ' If chunk sizes are more than 2...
  594.            Throw New Exception("Unexpected chunk filesize-count detected.")
  595.            Exit Sub
  596.        End If
  597.  
  598.        ' The remaining size to calculate the percentage, in bytes.
  599.        Dim SizeRemaining As Long = TotalSize
  600.  
  601.        ' Counts the length of the current chunk file to calculate the percentage, in bytes.
  602.        Dim SizeWritten As Long = 0L
  603.  
  604.        ' Counts the length of the written size on the current chunk file, in bytes.
  605.        Dim ChunkSizeWritten As Long = 0L
  606.  
  607.        ' The buffer to read data and merge the chunks.
  608.        Dim Buffer As Byte() = New Byte() {}
  609.  
  610.        ' The buffer length.
  611.        Dim BufferLength As Integer = Me.BufferSize
  612.  
  613.        ' The total amount of chunks to merge.
  614.        Dim ChunkCount As Integer = Chunks.Count
  615.  
  616.        ' Keeps track of the current chunk.
  617.        Dim ChunkIndex As Integer = 0I
  618.  
  619.        ' Keeps track of the total percentage done.
  620.        Dim TotalProgress As Double = 0.0R
  621.  
  622.        ' Create the output file to merge the chunks inside.
  623.        Using OutputStream As New FileStream(OutputFile, FileMode.Create)
  624.  
  625.            Using BinaryWriter As New BinaryWriter(OutputStream)
  626.  
  627.                ' Iterate the chunks.
  628.                For Each Chunk As FileInfo In Chunks
  629.  
  630.                    ' Open the chunk to start reading bytes.
  631.                    Using InputStream As New FileStream(Chunk.FullName, FileMode.Open)
  632.  
  633.                        Using BinaryReader As New BinaryReader(InputStream)
  634.  
  635.                            ' Read until reached the end-bytes of the chunk file.
  636.                            While (InputStream.Position < InputStream.Length)
  637.  
  638.                                ' Read bytes from the chunk file (BufferSize byte-length).
  639.                                Buffer = BinaryReader.ReadBytes(BufferLength)
  640.  
  641.                                ' Write those bytes in the output file.
  642.                                BinaryWriter.Write(Buffer)
  643.  
  644.                                ' Increment the bytes-written counters.
  645.                                SizeWritten += Buffer.Count
  646.                                ChunkSizeWritten += Buffer.Count
  647.  
  648.                                ' Decrease the bytes-remaining counter.
  649.                                SizeRemaining -= Buffer.Count
  650.  
  651.                                ' Set the total progress.
  652.                                TotalProgress = (TotalSize - SizeRemaining) * (100I / TotalSize)
  653.  
  654.                                ' Set the progress event-arguments.
  655.                                ProgressArguments = New MergeProgressChangedArgs(
  656.                                    TotalProgress:=If(Not TotalProgress > 99.9R, TotalProgress, 99.9R),
  657.                                    ChunkProgress:=(100I / InputStream.Length) * (ChunkSizeWritten - BufferLength),
  658.                                    ChunksToMerge:=ChunkCount,
  659.                                    ChunksMerged:=ChunkIndex)
  660.  
  661.                                ' Report the progress.
  662.                                RaiseEvent MergeProgressChanged(Me, ProgressArguments)
  663.  
  664.                            End While ' (InputStream.Position < InputStream.Length)
  665.  
  666.                            ChunkIndex += 1I ' Increment the chunk file counter.
  667.                            ChunkSizeWritten = 0L ' Reset the bytes-written for the next chunk.
  668.  
  669.                        End Using ' BinaryReader
  670.  
  671.                    End Using ' InputStream
  672.  
  673.                Next Chunk
  674.  
  675.                OutputStream.Flush()
  676.  
  677.            End Using ' BinaryWriter
  678.  
  679.        End Using ' OutputStream
  680.  
  681.        ' Set the progress event-arguments.
  682.        ProgressArguments = New MergeProgressChangedArgs(
  683.            TotalProgress:=100.0R,
  684.            ChunkProgress:=100.0R,
  685.            ChunksToMerge:=ChunkCount,
  686.            ChunksMerged:=ChunkIndex)
  687.  
  688.        ' Report the progress.
  689.        RaiseEvent MergeProgressChanged(Me, ProgressArguments)
  690.  
  691.        If DeleteChunksAfterMerged Then ' Delethe the chunk files.
  692.  
  693.            For Each Chunk As FileInfo In Chunks
  694.                File.Delete(Chunk.FullName)
  695.            Next Chunk
  696.  
  697.        End If ' DeleteChunksAfterMerged
  698.  
  699.    End Sub
  700.  
  701. #End Region
  702.  
  703. End Class


Ejemplo de uso:



Código
  1. Public Class FileSplitter_Test
  2.  
  3.    ' Some Sizes to choose.
  4.    Private ReadOnly Megabyte As Integer = 1048576I
  5.    Private ReadOnly Gigabyte As Integer = 1073741824I
  6.  
  7.    ' The controls that will report the progress.
  8.    Private LabelSplit1, LabelSplit2, LabelSplit3 As New Label
  9.    Private LabelMerge1, LabelMerge2, LabelMerge3 As New Label
  10.  
  11.    ' The controls to split or merge.
  12.    Private WithEvents ButtonSplit, ButtonMerge As New Button
  13.  
  14.    ' The FileSplitter instance.
  15.    Private WithEvents Splitter As New FileSplitter() With
  16.        {
  17.          .BufferSize = (Megabyte * 10I)
  18.        } ' With BufferSize of 10 Megabytes.
  19.  
  20.    Public Sub New()
  21.  
  22.        ' This call is required by the designer.
  23.        InitializeComponent()
  24.  
  25.        ' Set the Form properties.
  26.        With Me
  27.            .Size = New Point(400, 200)
  28.            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
  29.            .MaximizeBox = False
  30.        End With
  31.  
  32.        ' Set the control properties.
  33.        With ButtonSplit
  34.            .Text = "Split"
  35.            .Font = New Font(Me.Font.FontFamily, 14.0F, FontStyle.Bold)
  36.            .Size = New Point(200I, 75I)
  37.            .Location = New Point(0I, 0I)
  38.            .Cursor = Cursors.Hand
  39.        End With
  40.  
  41.        With ButtonMerge
  42.            .Text = "Merge"
  43.            .Font = New Font(Me.Font.FontFamily, 14.0F, FontStyle.Bold)
  44.            .Size = New Point(200I, 75I)
  45.            .Location = New Point(ButtonSplit.Location.X + ButtonSplit.Width, 0I)
  46.            .Cursor = Cursors.Hand
  47.        End With
  48.  
  49.        With LabelSplit1
  50.            .Text = "Total Progress:"
  51.            .AutoSize = True
  52.            .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
  53.            .Location = New Point(0I, ButtonSplit.Location.Y + ButtonSplit.Height + 10I)
  54.        End With
  55.  
  56.        With LabelSplit2
  57.            .Text = "Chunk Progress:"
  58.            .AutoSize = True
  59.            .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
  60.            .Location = New Point(0I, LabelSplit1.Location.Y + LabelSplit1.Height)
  61.        End With
  62.  
  63.        With LabelSplit3
  64.            .Text = "Chunk Count:"
  65.            .AutoSize = True
  66.            .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
  67.            .Location = New Point(0I, LabelSplit2.Location.Y + LabelSplit2.Height)
  68.        End With
  69.  
  70.        With LabelMerge1
  71.            .Text = "Total Progress:"
  72.            .AutoSize = True
  73.            .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
  74.            .Location = New Point(ButtonMerge.Location.X, ButtonMerge.Location.Y + ButtonMerge.Height + 10I)
  75.        End With
  76.  
  77.        With LabelMerge2
  78.            .Text = "Chunk Progress:"
  79.            .AutoSize = True
  80.            .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
  81.            .Location = New Point(ButtonMerge.Location.X, LabelMerge1.Location.Y + LabelMerge1.Height)
  82.        End With
  83.  
  84.        With LabelMerge3
  85.            .Text = "Chunk Count:"
  86.            .AutoSize = True
  87.            .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
  88.            .Location = New Point(ButtonMerge.Location.X, LabelMerge2.Location.Y + LabelMerge2.Height)
  89.        End With
  90.  
  91.        ' Add the controls into the form.
  92.        Me.Controls.AddRange({LabelSplit1, LabelSplit2, LabelSplit3})
  93.        Me.Controls.AddRange({LabelMerge1, LabelMerge2, LabelMerge3})
  94.        Me.Controls.AddRange({ButtonSplit, ButtonMerge})
  95.  
  96.    End Sub
  97.  
  98.    ''' <summary>
  99.    ''' Handles the 'Click' event of the 'ButtonSplit' control.
  100.    ''' </summary>
  101.    Private Sub ButtonSplit_Click() Handles ButtonSplit.Click
  102.  
  103.        Splitter.Split(InputFile:="C:\File.mkv",
  104.                       ChunkSize:=Gigabyte,
  105.                       ChunkName:="File.Part",
  106.                       ChunkExt:="fs",
  107.                       Overwrite:=True,
  108.                       DeleteAfterSplit:=False)
  109.  
  110.    End Sub
  111.  
  112.    ''' <summary>
  113.    ''' Handles the 'Click' event of the 'ButtonMerge' control.
  114.    ''' </summary>
  115.    Private Sub ButtonMerge_Click() Handles ButtonMerge.Click
  116.  
  117.        Splitter.Merge(InputFile:="C:\File.Part.1.fs",
  118.                       OutputFile:="C:\Merged.mkv",
  119.                       Overwrite:=True,
  120.                       DeleteChunksAfterMerged:=True)
  121.  
  122.    End Sub
  123.  
  124.    ''' <summary>
  125.    ''' Handles the 'SplitProgressChangedArgs' event of the 'Splitter' object.
  126.    ''' </summary>
  127.    ''' <param name="sender">The source of the event.</param>
  128.    ''' <param name="e">The <see cref="FileSplitter.SplitProgressChangedArgs"/> instance containing the event data.</param>
  129.    Private Sub Splitter_SplitProgressChangedArgs(ByVal sender As Object, ByVal e As FileSplitter.SplitProgressChangedArgs) _
  130.    Handles Splitter.SplitProgressChanged
  131.  
  132.        LabelSplit1.Text = String.Format("Total Progress: {0}%", e.TotalProgress.ToString("n1"))
  133.        LabelSplit2.Text = String.Format("Chunk Progress: {0}%", e.ChunkProgress.ToString("n1"))
  134.        LabelSplit3.Text = String.Format("Chunk Count: {0} of {1}", CStr(e.ChunksCreated), CStr(e.ChunksToCreate))
  135.        Application.DoEvents()
  136.  
  137.    End Sub
  138.  
  139.    ''' <summary>
  140.    ''' Handles the 'MergeProgressChangedArgs' event of the 'Splitter' object.
  141.    ''' </summary>
  142.    ''' <param name="sender">The source of the event.</param>
  143.    ''' <param name="e">The <see cref="FileSplitter.MergeProgressChangedArgs"/> instance containing the event data.</param>
  144.    Private Sub Splitter_MergeProgressChangedArgs(ByVal sender As Object, ByVal e As FileSplitter.MergeProgressChangedArgs) _
  145.    Handles Splitter.MergeProgressChanged
  146.  
  147.        LabelMerge1.Text = String.Format("Total Progress: {0}%", e.TotalProgress.ToString("n1"))
  148.        LabelMerge2.Text = String.Format("Chunk Progress: {0}%", e.ChunkProgress.ToString("n1"))
  149.        LabelMerge3.Text = String.Format("Chunk Count: {0} of {1}", CStr(e.ChunksMerged), CStr(e.ChunksToMerge))
  150.        Application.DoEvents()
  151.  
  152.    End Sub
  153.  
  154. End Class
« Última modificación: 15 Agosto 2014, 20:43 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #416 en: 18 Agosto 2014, 08:40 am »

Aquí explico una manera de limitar manualmente la aplicación a única instancia (Single-Instance), mediante el MUTEX.



Código
  1. ' Single-Instance Application Example
  2. ' By Elektro
  3.  
  4. ' Instructions:
  5. ' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button.
  6. ' 2. Copy and paste this code to replace the 'MyApplication' class contents.
  7. ' 3. Define a proper identifier for 'MutexID' property.
  8.  
  9. Namespace My
  10.  
  11.    Partial Friend Class MyApplication
  12.  
  13. #Region " Properties "
  14.  
  15.        ''' <summary>
  16.        ''' Gets the current process mutex identifier.
  17.        ''' </summary>
  18.        ''' <value>the current process mutex identifier.</value>
  19.        ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception>
  20.        Private ReadOnly Property MutexID As String
  21.            Get
  22.                ' Define a Golabl Unique Identifier to name the Mutex.
  23.                Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454"
  24.  
  25.                If Guid.TryParse(input:=Id, result:=New Guid) Then
  26.                    Return Id
  27.                Else
  28.                    Throw New FormatException("The specified value is not in a valid GUID format.")
  29.                End If
  30.  
  31.            End Get
  32.        End Property
  33.  
  34. #End Region
  35.  
  36. #Region " Private Methods "
  37.  
  38.        ''' <summary>
  39.        ''' Determines whether this is the unique instance that is running for this process.
  40.        ''' </summary>
  41.        ''' <returns><c>true</c> if this is the unique instance; otherwise, <c>false</c>.</returns>
  42.        Private Function IsUniqueInstance() As Boolean
  43.  
  44.            Dim mtx As Threading.Mutex = Nothing
  45.  
  46.            Try
  47.                mtx = Threading.Mutex.OpenExisting(name:=Me.MutexID)
  48.                mtx.Close()
  49.                mtx = Nothing
  50.            Catch
  51.                mtx = New Threading.Mutex(initiallyOwned:=True, name:=Me.MutexID)
  52.            End Try
  53.  
  54.            Return mtx IsNot Nothing
  55.  
  56.        End Function
  57.  
  58. #End Region
  59.  
  60. #Region " Event-Handlers "
  61.  
  62.        ''' <summary>
  63.        ''' This occurs when the application starts, before the startup Form is created.
  64.        ''' </summary>
  65.        ''' <param name="sender">The source of the event.</param>
  66.        ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param>
  67.        Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _
  68.        Handles Me.Startup
  69.  
  70.            ' If there is more than one instance running of this process with the same mutex then...
  71.            If Not Me.IsUniqueInstance Then ' Prevent multi-instancing.
  72.  
  73.                MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.",
  74.                               Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
  75.  
  76.                ' Cancel the application execution.
  77.                e.Cancel = True
  78.  
  79.            End If
  80.  
  81.        End Sub
  82.  
  83. #End Region
  84.  
  85.    End Class ' MyApplication
  86.  
  87. End Namespace
« Última modificación: 18 Agosto 2014, 12:31 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #417 en: 18 Agosto 2014, 12:08 pm »

Un ejemplo de como añadir y usar un control WPF (no un proyecto) en Winforms, en tiempo de ejecución.

En este ejemplo uso un control simple que imita el indicador de progreso de Windows 8:



Código
  1. ' Example of how to add an WPF Control in a WinForms project at execution time.
  2. ' By Elektro
  3.  
  4. ' Instructions:
  5. ' 1. Compile your own WPF user-control or download this one: http://www.codeproject.com/Articles/700185/Windows-Progress-Ring?msg=4884207#xx4884207xx
  6. ' 2. Add a reference to 'WindowsformsIntegration', 'PresentationFramework', 'PresentationCore', 'WindowsBase' and 'System.Xaml'.
  7. ' 3. Add a reference to our WPF library, in this example is: 'WindowsProgressRing.dll'
  8. ' 4. If the 'WindowsProgressRing.dll' user-control doesnt's load properly, set the targeting Framework to '4.5'.
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.Windows.Forms.Integration ' ElementHost
  13.  
  14. #End Region
  15.  
  16. #Region " WPFControl_TestClass "
  17.  
  18. Public Class WPFControl_TestClass
  19.  
  20.    ''' <summary>
  21.    ''' The ElementHost instance that will host the WPF user-control.
  22.    ''' </summary>
  23.    Dim WPFHost As New ElementHost With {.Dock = DockStyle.Fill}
  24.  
  25.    ''' <summary>
  26.    ''' The WPF user-control instance.
  27.    ''' </summary>
  28.    Dim WPFControl As New NMT.Wpf.Controls.WindowsProgressRing
  29.  
  30.    ''' <summary>
  31.    ''' Initializes a new instance of the <see cref="WPFControl_TestClass"/> class.
  32.    ''' </summary>
  33.    Public Sub New()
  34.  
  35.        ' This call is required by the designer.
  36.        InitializeComponent()
  37.  
  38.        With Me ' Set the Form properties.
  39.            .StartPosition = FormStartPosition.CenterScreen
  40.            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
  41.            .MaximizeBox = False
  42.            .ShowIcon = False
  43.            .BackColor = Color.Black
  44.            .Size = New Drawing.Size(320I, 320I)
  45.  
  46.            .Controls.Add(WPFHost) ' Add the ElementHost.
  47.        End With ' Me
  48.  
  49.        With WPFHost ' Set the ElementHost properties.
  50.            .Width = 120I
  51.            .Height = 120I
  52.            WPFHost.Child = WPFControl ' Add the WPF Control.
  53.        End With ' WPFHost
  54.  
  55.        With WPFControl ' Set the WPF Control properties.
  56.            .Items = 60I
  57.            .Width = 120.0R
  58.            .Height = 120.0R
  59.            .Speed = New Windows.Duration(TimeSpan.FromSeconds(2.5R))
  60.            .Background = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.Black.R, Color.Black.G, Color.Black.B))
  61.            .Foreground = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.DodgerBlue.R, Color.DodgerBlue.G, Color.DodgerBlue.B))
  62.        End With ' WPFControl
  63.  
  64.    End Sub
  65.  
  66. End Class ' WPFControl_TestClass
  67.  
  68. #End Region
« Última modificación: 18 Agosto 2014, 12:35 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #418 en: 18 Agosto 2014, 15:02 pm »

Este código es parecido al ejemplo que mostré de como implementar una prevención de múltiples instancias, pero la diferencia de este código es que se puede especificar un máximo de instancias múltiples (en la propiedad 'SemaphID')



Código
  1. ' Multi-Instance Limit Example
  2. ' By Elektro
  3.  
  4. ' Instructions:
  5. ' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button.
  6. ' 2. Copy and paste this code to replace the 'MyApplication' class contents.
  7. ' 3. Define a proper identifier for 'SemaphID' property.
  8.  
  9. Namespace My
  10.  
  11.    Partial Friend Class MyApplication
  12.  
  13.        ''' <summary>
  14.        ''' The semaphore object used to limit the number of instances.
  15.        ''' </summary>
  16.        Private Semaph As Threading.Semaphore = Nothing
  17.  
  18.        ''' <summary>
  19.        ''' Gets the current semaphore object identifier.
  20.        ''' </summary>
  21.        ''' <value>The current process semaphore identifier.</value>
  22.        ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception>
  23.        Private ReadOnly Property SemaphID As String
  24.            Get
  25.  
  26.                ' Define a Golabl Unique Identifier to name the semaphore object.
  27.                Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454"
  28.  
  29.                If Guid.TryParse(input:=Id, result:=New Guid) Then
  30.                    Return Id
  31.                Else
  32.                    Throw New FormatException("The specified value is not in a valid GUID format.")
  33.                End If
  34.  
  35.            End Get
  36.        End Property
  37.  
  38.        ''' <summary>
  39.        ''' Gets the maximum instances allowed for this process.
  40.        ''' </summary>
  41.        ''' <value>The maximum instances allowed for this process.</value>
  42.        Private ReadOnly Property MaxInstances As Integer
  43.            Get
  44.                Return 3
  45.            End Get
  46.        End Property
  47.  
  48.        ''' <summary>
  49.        ''' Determines whether the semaphore can receive a signal.
  50.        ''' </summary>
  51.        ''' <returns><c>true</c> if this instance [can set semaphore]; otherwise, <c>false</c>.</returns>
  52.        Private Function CanSetSemaphore() As Boolean
  53.  
  54.            Semaph = New Threading.Semaphore(initialCount:=Me.MaxInstances,
  55.                                             maximumCount:=Me.MaxInstances,
  56.                                             name:=Me.SemaphID)
  57.  
  58.            Return Semaph.WaitOne(100I)
  59.  
  60.        End Function
  61.  
  62.        ''' <summary>
  63.        ''' This occurs when the application starts, before the startup Form is created.
  64.        ''' </summary>
  65.        ''' <param name="sender">The source of the event.</param>
  66.        ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param>
  67.        Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _
  68.        Handles Me.Startup
  69.  
  70.            ' If there is more than the maximum allowed instances running with the same id then...
  71.            If Not Me.CanSetSemaphore Then ' Prevent multi-instancing.
  72.  
  73.                MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.",
  74.                               Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
  75.  
  76.                ' Cancel the application Startup to terminate the process.
  77.                e.Cancel = True
  78.  
  79.            End If
  80.  
  81.        End Sub
  82.  
  83.        ''' <summary>
  84.        ''' This occurs when the application shuts down.
  85.        ''' </summary>
  86.        ''' <param name="sender">The source of the event.</param>
  87.        ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  88.        Private Sub MyApplication_Shutdown(ByVal sender As Object, ByVal e As EventArgs) _
  89.        Handles Me.Shutdown
  90.  
  91.            If Semaph IsNot Nothing Then
  92.  
  93.                ' Free the semaphore to allow next app runs.
  94.                Semaph.Release()
  95.                Semaph.Close()
  96.                Semaph = Nothing
  97.  
  98.            End If ' semaph IsNot Nothing
  99.  
  100.        End Sub
  101.  
  102.    End Class ' MyApplication
  103.  
  104. End Namespace
« Última modificación: 18 Agosto 2014, 15:04 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #419 en: 19 Agosto 2014, 04:33 am »

Convierte un String a HTMLDocument

Código
  1.    ' String To HtmlDocument
  2.    ' By Elektro
  3.    '
  4.    ' Example Usage:
  5.    ' Dim Document As HtmlDocument = StringToHtmlDocument(IO.File.ReadAllText("C:\File.html", Text.Encoding.Default))
  6.    '
  7.    ''' <summary>
  8.    ''' Converts a <see cref="String"/> to an <see cref="HTMLDocument"/>.
  9.    ''' </summary>
  10.    ''' <param name="str">Indicates the string.</param>
  11.    ''' <returns>The <see cref="HTMLDocument"/> object.</returns>
  12.    Public Function StringToHtmlDocument(ByVal str As String) As HtmlDocument
  13.  
  14.        Using wb As New WebBrowser
  15.  
  16.            wb.ScriptErrorsSuppressed = True
  17.            wb.DocumentText = ""
  18.            wb.Document.OpenNew(replaceInHistory:=True)
  19.            wb.Document.Write(str)
  20.            Return wb.Document
  21.  
  22.        End Using
  23.  
  24.    End Function



Obtiene los XPaths de un XMLDocument:



Código
  1.    ' Get XPaths
  2.    ' By Elektro
  3.    '
  4.    ' Example Usage:
  5.    '
  6.    ' Dim xDoc As New Xml.XmlDocument
  7.    ' xDoc.Load("C:\File.xml")
  8.    ' Dim XPathList As List(Of String) = GetXPaths(xDoc)
  9.    ' ListBox1.Items.AddRange((From XPath As String In XPathList Select XPath).ToArray)
  10.  
  11.    ''' <summary>
  12.    ''' Gets all the XPath expressions of an XML Document.
  13.    ''' </summary>
  14.    ''' <param name="Document">Indicates the XML document.</param>
  15.    ''' <returns>List(Of System.String).</returns>
  16.    Public Function GetXPaths(ByVal Document As Xml.XmlDocument) As List(Of String)
  17.  
  18.        Dim XPathList As New List(Of String)
  19.  
  20.        Dim XPath As String = String.Empty
  21.  
  22.        For Each Child As Xml.XmlNode In Document.ChildNodes
  23.  
  24.            If Child.NodeType = Xml.XmlNodeType.Element Then
  25.                GetXPaths(Child, XPathList, XPath)
  26.            End If
  27.  
  28.        Next ' child
  29.  
  30.        Return XPathList
  31.  
  32.    End Function
  33.  
  34.    ''' <summary>
  35.    ''' Gets all the XPath expressions of an XML Node.
  36.    ''' </summary>
  37.    ''' <param name="Node">Indicates the XML node.</param>
  38.    ''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param>
  39.    ''' <param name="XPath">Indicates the current XPath.</param>
  40.    Private Sub GetXPaths(ByVal Node As Xml.XmlNode,
  41.                          ByRef XPathList As List(Of String),
  42.                          Optional ByVal XPath As String = Nothing)
  43.  
  44.        XPath &= "/" & Node.Name
  45.  
  46.        If Not XPathList.Contains(XPath) Then
  47.            XPathList.Add(XPath)
  48.        End If
  49.  
  50.        For Each Child As Xml.XmlNode In Node.ChildNodes
  51.  
  52.            If Child.NodeType = Xml.XmlNodeType.Element Then
  53.                GetXPaths(Child, XPathList, XPath)
  54.            End If
  55.  
  56.        Next ' child
  57.  
  58.    End Sub
  59.  
En línea



Páginas: 1 ... 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 54 55 56 57 ... 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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