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

 

 


Tema destacado: Estamos en la red social de Mastodon


+  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 4 Visitantes están viendo este tema.
Páginas: 1 ... 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 [40] 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 529,059 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #390 en: 8 Marzo 2014, 15:41 pm »


Un ejemplo de uso muy básico de la librería NCalc ~> http://ncalc.codeplex.com/

Código
  1.        Dim MathExpression As String = "(2 + 3) * 2" ' Result: 10
  2.  
  3.        Dim NCalcExpression As New NCalc.Expression(MathExpression)
  4.  
  5.        MsgBox(NCalcExpression.Evaluate().ToString)





Una forma de comprobar si un archivo es un ensamblado .NET:

Código
  1.    ' Usage Examples:
  2.    '
  3.    ' MsgBox(IsNetAssembly("C:\File.exe"))
  4.    ' MsgBox(IsNetAssembly("C:\File.dll"))
  5.  
  6.    ''' <summary>
  7.    ''' Gets the common language runtime (CLR) version information of the specified file, using the specified buffer.
  8.    ''' </summary>
  9.    ''' <param name="filepath">Indicates the filepath of the file to be examined.</param>
  10.    ''' <param name="buffer">Indicates the buffer allocated for the version information that is returned.</param>
  11.    ''' <param name="buflen">Indicates the size, in wide characters, of the buffer.</param>
  12.    ''' <param name="written">Indicates the size, in bytes, of the returned buffer.</param>
  13.    ''' <returns>System.Int32.</returns>
  14.    <System.Runtime.InteropServices.DllImport("mscoree.dll",
  15.    CharSet:=System.Runtime.InteropServices.CharSet.Unicode)>
  16.    Private Shared Function GetFileVersion(
  17.                      ByVal filepath As String,
  18.                      ByVal buffer As System.Text.StringBuilder,
  19.                      ByVal buflen As Integer,
  20.                      ByRef written As Integer
  21.    ) As Integer
  22.    End Function
  23.  
  24.    ''' <summary>
  25.    ''' Determines whether an exe/dll file is an .Net assembly.
  26.    ''' </summary>
  27.    ''' <param name="File">Indicates the exe/dll file to check.</param>
  28.    ''' <returns><c>true</c> if file is an .Net assembly; otherwise, <c>false</c>.</returns>
  29.    Public Shared Function IsNetAssembly(ByVal [File] As String) As Boolean
  30.  
  31.        Dim sb = New System.Text.StringBuilder(256)
  32.        Dim written As Integer = 0
  33.        Dim hr = GetFileVersion([File], sb, sb.Capacity, written)
  34.        Return hr = 0
  35.  
  36.    End Function





Un simple efecto de máquina de escribir:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 03-08-2014
  4. ' ***********************************************************************
  5. ' <copyright file="TypeWritter.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Sub Main()
  13.  
  14. '    Console.WriteLine()
  15. '    TypeWritter.WriteLine("[ Typewritter ] - By Elektro")
  16. '    TypeWritter.WriteLine()
  17. '    TypeWritter.WriteLine()
  18. '    TypeWritter.WriteLine("Hola a todos!, les presento este humilde y simple efecto de máquina de escribir")
  19. '    TypeWritter.WriteLine()
  20. '    TypeWritter.WriteLine("Si os fijais aténtamente, quizás ya habreis notado, que hay pausas realistas,   al escribir signos de puntuación...")
  21. '    TypeWritter.WriteLine()
  22. '    TypeWritter.WriteLine("[+] Podemos establecer la velocidad de escritura, por ejemplo, a 20 ms. :")
  23. '    TypeWritter.WriteLine("abcdefghijklmnopqrstuvwxyz", 20)
  24. '    TypeWritter.WriteLine()
  25. '    TypeWritter.WriteLine("[+] Podemos establecer la velocidad de las pausas, por ejemplo, a 2 seg. :")
  26. '    TypeWritter.WriteLine(".,;:", , 2 * 1000)
  27. '    TypeWritter.WriteLine()
  28. '    TypeWritter.WriteLine("[+] El efecto corre en una tarea asíncrona, por lo que se pueden hacer otras cosas mientras tanto, sin frezzear una GUI, y también podemos cancelar la escritura en cualquier momento, gracias al Token de cancelación.")
  29. '    TypeWritter.WriteLine()
  30. '    TypeWritter.WriteLine()
  31. '    TypeWritter.WriteLine("Esto es todo por ahora.")
  32. '    Console.ReadKey()
  33.  
  34. 'End Sub
  35.  
  36. #End Region
  37.  
  38. #Region " TypeWritter "
  39.  
  40. ''' <summary>
  41. ''' Simulates text-typying effect like a Typewritter.
  42. ''' </summary>
  43. Public Class TypeWritter
  44.  
  45. #Region " Properties "
  46.  
  47.    ''' <summary>
  48.    ''' When set to 'True', the running 'Typewritter' task will be cancelled.
  49.    ''' ( The property is set again to 'False' automatically after a 'Task' is cancelled )
  50.    ''' </summary>
  51.    Public Shared Property RequestCancel As Boolean = False
  52.  
  53. #End Region
  54.  
  55. #Region " Task Objects "
  56.  
  57.    ''' <summary>
  58.    ''' The typewritter asynchronous Task.
  59.    ''' </summary>
  60.    Private Shared TypeWritterTask As Threading.Tasks.Task
  61.  
  62.    ''' <summary>
  63.    ''' The typewritter Task Cancellation TokenSource.
  64.    ''' </summary>
  65.    Private Shared TypeWritterTaskCTS As New Threading.CancellationTokenSource
  66.  
  67.    ''' <summary>
  68.    ''' The typewritter Task Cancellation Token.
  69.    ''' </summary>
  70.    Private Shared TypeWritterTaskCT As Threading.CancellationToken = TypeWritterTaskCTS.Token
  71.  
  72. #End Region
  73.  
  74. #Region " Private Methods "
  75.  
  76.    ''' <summary>
  77.    ''' Writes text simulating a Typewritter effect.
  78.    ''' </summary>
  79.    ''' <param name="CancellationToken">Indicates the cancellation token of the Task.</param>
  80.    ''' <param name="Text">Indicates the text to type.</param>
  81.    ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param>
  82.    ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param>
  83.    Private Shared Sub TypeWritter(ByVal CancellationToken As Threading.CancellationToken,
  84.                            ByVal [Text] As String,
  85.                            ByVal TypeSpeed As Integer,
  86.                            ByVal PauseDuration As Integer)
  87.  
  88.        ' If Text is empty then write an empty line...
  89.        If String.IsNullOrEmpty([Text]) Then
  90.  
  91.            ' If not cancellation is already requested then...
  92.            If Not CancellationToken.IsCancellationRequested Then
  93.  
  94.                ' Write an empty line.
  95.                Console.WriteLine()
  96.  
  97.                ' Wait-Speed (empty line).
  98.                Threading.Thread.Sleep(PauseDuration)
  99.  
  100.            End If ' CancellationToken.IsCancellationRequested
  101.  
  102.        End If ' String.IsNullOrEmpty([Text])
  103.  
  104.        ' For each Character in Text to type...
  105.        For Each c As Char In [Text]
  106.  
  107.            ' If not cancellation is already requested then...
  108.            If Not CancellationToken.IsCancellationRequested Then
  109.  
  110.                ' Type the character.
  111.                Console.Write(CStr(c))
  112.  
  113.                ' Type-Wait.
  114.                Threading.Thread.Sleep(TypeSpeed)
  115.  
  116.                If ".,;:".Contains(c) Then
  117.                    ' Pause-Wait.
  118.                    Threading.Thread.Sleep(PauseDuration)
  119.                End If
  120.  
  121.            Else ' want to cancel.
  122.  
  123.                ' Exit iteration.
  124.                Exit For
  125.  
  126.            End If ' CancellationToken.IsCancellationRequested
  127.  
  128.        Next c ' As Char In [Text]
  129.  
  130.    End Sub
  131.  
  132. #End Region
  133.  
  134. #Region " Public Methods "
  135.  
  136.    ''' <summary>
  137.    ''' Writes text simulating a Typewritter effect.
  138.    ''' </summary>
  139.    ''' <param name="Text">Indicates the text to type.</param>
  140.    ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param>
  141.    ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param>
  142.    Public Shared Sub Write(ByVal [Text] As String,
  143.                            Optional ByVal TypeSpeed As Integer = 75,
  144.                            Optional ByVal PauseDuration As Integer = 400)
  145.  
  146.        ' Run the asynchronous Task.
  147.        TypeWritterTask = Threading.Tasks.
  148.                   Task.Factory.StartNew(Sub()
  149.                                             TypeWritter(TypeWritterTaskCT, [Text], TypeSpeed, PauseDuration)
  150.                                         End Sub, TypeWritterTaskCT)
  151.  
  152.        ' Until Task is not completed or is not cancelled, do...
  153.        Do Until TypeWritterTask.IsCompleted OrElse TypeWritterTask.IsCanceled
  154.  
  155.            ' If want to cancel then...
  156.            If RequestCancel Then
  157.  
  158.                ' If not cancellation is already requested then...
  159.                If Not TypeWritterTaskCTS.IsCancellationRequested Then
  160.  
  161.                    ' Cancel the Task.
  162.                    TypeWritterTaskCTS.Cancel()
  163.  
  164.                    ' Renew the cancellation token and tokensource.
  165.                    TypeWritterTaskCTS = New Threading.CancellationTokenSource
  166.                    TypeWritterTaskCT = TypeWritterTaskCTS.Token
  167.  
  168.                End If
  169.  
  170.                ' Reset the cancellation flag var.
  171.                RequestCancel = False
  172.  
  173.                ' Exit iteration.
  174.                Exit Do
  175.  
  176.            End If
  177.  
  178.        Loop ' TypeTask.IsCompleted OrElse TypeTask.IsCanceled
  179.  
  180.    End Sub
  181.  
  182.    ''' <summary>
  183.    ''' Writes text simulating a Typewritter effect, and adds a break-line at the end.
  184.    ''' </summary>
  185.    ''' <param name="Text">Indicates the text to type.</param>
  186.    ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param>
  187.    ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param>
  188.    Public Shared Sub WriteLine(ByVal [Text] As String,
  189.                                Optional ByVal TypeSpeed As Integer = 75,
  190.                                Optional ByVal PauseDuration As Integer = 400)
  191.  
  192.        Write([Text], TypeSpeed, PauseDuration)
  193.        Console.WriteLine()
  194.  
  195.    End Sub
  196.  
  197.    ''' <summary>
  198.    ''' Writes an empty line.
  199.    ''' </summary>
  200.    ''' <param name="PauseDuration">Indicates the pause duration of the empty line, in ms.</param>
  201.    Public Shared Sub WriteLine(Optional ByVal PauseDuration As Integer = 750)
  202.  
  203.        Write(String.Empty, 1, PauseDuration)
  204.  
  205.    End Sub
  206.  
  207. #End Region
  208.  
  209. End Class
  210.  
  211. #End Region


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #391 en: 9 Marzo 2014, 16:27 pm »

Unos snippets para imitar las macros "LoByte", "LoWord", "LoDword", etc, usando la Class BitConverter, la cual, aunque necesita hacer más trabajo, me parece una solución mucho mas elegante que las que se pueden encontrar por ahí, e igual de efectiva.


Código
  1.    ' Get LoByte
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetLoByte(1587S)) ' Result: 51
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the low-order byte of an 'Int16' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param>
  11.    ''' <returns>The return value is the low-order byte.</returns>
  12.    Public Shared Function GetLoByte(ByVal value As Short) As Byte
  13.  
  14.        Return BitConverter.GetBytes(value).First
  15.  
  16.    End Function

Código
  1.    ' Get HiByte
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetHiByte(1587S)) ' Result: 6
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the high-order byte of an 'Int16' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param>
  11.    ''' <returns>The return value is the high-order byte.</returns>
  12.    Public Shared Function GetHiByte(ByVal value As Short) As Byte
  13.  
  14.        Return BitConverter.GetBytes(value).Last
  15.  
  16.    End Function

Código
  1.    ' Get LoWord
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetLoWord(13959358I)) ' Result: 190S
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the low-order word of an 'Int32' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param>
  11.    ''' <returns>The return value is the low-order word.</returns>
  12.    Public Shared Function GetLoWord(ByVal value As Integer) As Short
  13.  
  14.        Return BitConverter.ToInt16(BitConverter.GetBytes(value), 0)
  15.  
  16.    End Function

Código
  1.    ' Get HiWord
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetHiWord(13959358I)) ' Result: 213S
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the high-order word of an 'Int32' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param>
  11.    ''' <returns>The return value is the high-order word.</returns>
  12.    Public Shared Function GetHiWord(ByVal value As Integer) As Short
  13.  
  14.        Return BitConverter.ToInt16(BitConverter.GetBytes(value), 2)
  15.  
  16.    End Function

Código
  1.    ' Get LoDword (As Unsigned Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetLoDword(328576329396160UL)) ' Result: 2741317568UI
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the low-order double word of an 'UInt64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'UInt64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <returns>The return value is the low-order double word.</returns>
  12.    Public Shared Function GetLoDword(ByVal value As ULong) As UInteger
  13.  
  14.        Return BitConverter.ToUInt32(BitConverter.GetBytes(value), 0)
  15.  
  16.    End Function

Código
  1.    ' Get HiDword (As Unsigned Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetHiDword(328576329396160UL)) ' Result: 76502UI
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the high-order double word of an 'UInt64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'UInt64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <returns>The return value is the high-order double word.</returns>
  12.    Public Shared Function GetHiDword(ByVal value As ULong) As UInteger
  13.  
  14.        Return BitConverter.ToUInt32(BitConverter.GetBytes(value), 4)
  15.  
  16.    End Function

Código
  1.    ' Get LoDword (As Signed Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetLoDword(328576329396160L)) ' Result: -1553649728I
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the low-order double word of an 'Int64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <returns>The return value is the low-order double word.</returns>
  12.    Public Shared Function GetLoDword(ByVal value As Long) As Integer
  13.  
  14.        Return BitConverter.ToInt32(BitConverter.GetBytes(value), 0)
  15.  
  16.    End Function

Código
  1.    ' Get HiDword (As Signed Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetHiDword(328576329396160L)) ' Result: 76502I
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the high-order double word of an 'Int64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <returns>The return value is the high-order double word.</returns>
  12.    Public Shared Function GetHiDword(ByVal value As Long) As Integer
  13.  
  14.        Return BitConverter.ToInt32(BitConverter.GetBytes(value), 4)
  15.  
  16.    End Function

Código
  1.    ' Make Word
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(MakeWord(51S, 6S)) ' Result: 1587S
  6.    '
  7.    ''' <summary>
  8.    ''' Makes an 'Int16' value from two bytes.
  9.    ''' </summary>
  10.    ''' <param name="LoByte">Indicates the low-order byte.</param>
  11.    ''' <param name="HiByte">Indicates the high-order byte.</param>
  12.    ''' <returns>The 'Int16' value.</returns>
  13.    Public Shared Function MakeWord(ByVal LoByte As Byte,
  14.                                    ByVal HiByte As Byte) As Short
  15.  
  16.        Return BitConverter.ToInt16(New Byte() {LoByte, HiByte}, 0)
  17.  
  18.    End Function

Código
  1.    ' Make Dword
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(MakedWord(190S, 213S)) ' Result: 13959358I
  6.    '
  7.    ''' <summary>
  8.    ''' Makes an 'Int32' value from two 'Int16' values.
  9.    ''' </summary>
  10.    ''' <param name="LoWord">Indicates the low-order word.</param>
  11.    ''' <param name="HiWord">Indicates the high-order word.</param>
  12.    ''' <returns>The 'Int32' value.</returns>
  13.    Public Shared Function MakeDword(ByVal LoWord As Short,
  14.                                     ByVal HiWord As Short) As Integer
  15.  
  16.        Dim LoBytes As Byte() = BitConverter.GetBytes(LoWord)
  17.        Dim HiBytes As Byte() = BitConverter.GetBytes(HiWord)
  18.        Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray
  19.  
  20.        Return BitConverter.ToInt32(Combined, 0)
  21.  
  22.    End Function

Código
  1.    ' Make Long (From An Unsigned Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(MakeLong(2741317568UI, 76502UI)) ' Result: 328576329396160UL
  6.    '
  7.    ''' <summary>
  8.    ''' Makes an 'UInt64' value from two 'UInt32' values.
  9.    ''' </summary>
  10.    ''' <param name="LoDword">Indicates the low-order Dword.</param>
  11.    ''' <param name="HiDword">Indicates the high-order Dword.</param>
  12.    ''' <returns>The 'UInt64' value.</returns>
  13.    Public Shared Function MakeLong(ByVal LoDword As UInteger,
  14.                                    ByVal HiDword As UInteger) As ULong
  15.  
  16.        Dim LoBytes As Byte() = BitConverter.GetBytes(LoDword)
  17.        Dim HiBytes As Byte() = BitConverter.GetBytes(HiDword)
  18.        Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray
  19.  
  20.        Return BitConverter.ToUInt64(Combined, 0)
  21.  
  22.    End Function

Código
  1.    ' Make Long (From a Signed Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(MakeLong(-1553649728I, 76502I)) ' Result: 328576329396160L
  6.    '
  7.    ''' <summary>
  8.    ''' Makes an 'Int64' value from two 'Int32' values.
  9.    ''' </summary>
  10.    ''' <param name="LoDword">Indicates the low-order Dword.</param>
  11.    ''' <param name="HiDword">Indicates the high-order Dword.</param>
  12.    ''' <returns>The 'Int64' value.</returns>
  13.    Public Shared Function MakeLong(ByVal LoDword As Integer,
  14.                                    ByVal HiDword As Integer) As Long
  15.  
  16.        Dim LoBytes As Byte() = BitConverter.GetBytes(LoDword)
  17.        Dim HiBytes As Byte() = BitConverter.GetBytes(HiDword)
  18.        Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray
  19.  
  20.        Return BitConverter.ToInt64(Combined, 0)
  21.  
  22.    End Function


« Última modificación: 9 Marzo 2014, 16:34 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #392 en: 9 Marzo 2014, 17:31 pm »

Algunos métodos más sobre bytes.

Código
  1.    ' Set LoByte
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(SetHiByte(321, 0S)) ' Result: 65S
  6.    '
  7.    ''' <summary>
  8.    ''' Sets the low-order byte of an 'Int16' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param>
  11.    ''' <param name="NewLoByte">Indicates the new LoByte, a 'Byte' value.</param>
  12.    ''' <returns>The 'Int16' value containing both the HiByte and the new LoByte.</returns>
  13.    Private Function SetLoByte(ByVal Value As Short,
  14.                               ByVal NewLoByte As Byte) As Short
  15.  
  16.        Dim ValueBytes As Byte() = BitConverter.GetBytes(Value)
  17.        ValueBytes(0) = NewLoByte
  18.  
  19.        Return BitConverter.ToInt16(ValueBytes, 0)
  20.  
  21.    End Function

Código
  1.    ' Set HiByte
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(SetHiByte(65S, 1S)) ' Result: 321S
  6.    '
  7.    ''' <summary>
  8.    ''' Sets the high-order byte of an 'Int16' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param>
  11.    ''' <param name="NewHiByte">Indicates the new HiByte, a 'Byte' value.</param>
  12.    ''' <returns>The 'Int16' value containing both the LoByte and the new HiByte.</returns>
  13.    Private Function SetHiByte(ByVal Value As Short,
  14.                               ByVal NewHiByte As Byte) As Short
  15.  
  16.        Dim ValueBytes As Byte() = BitConverter.GetBytes(Value)
  17.        ValueBytes(1) = NewHiByte
  18.  
  19.        Return BitConverter.ToInt16(ValueBytes, 0)
  20.  
  21.    End Function

Código
  1.    ' Set LoWord
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(SetLoWord(13959358I, 6S)) ' Result: 13959174I
  6.    '
  7.    ''' <summary>
  8.    ''' Sets the low-order word of an 'Int32' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param>
  11.    ''' <param name="NewLoWord">Indicates the new LoWord, an 'Int16' value.</param>
  12.    ''' <returns>The 'Int32' value containing both the HiWord and the new LoWord.</returns>
  13.    Private Function SetLoWord(ByVal Value As Integer,
  14.                               ByVal NewLoWord As Short) As Integer
  15.  
  16.        Dim ValueBytes As Byte() = BitConverter.GetBytes(Value)
  17.        Dim LoWordBytes As Byte() = BitConverter.GetBytes(NewLoWord)
  18.  
  19.        ValueBytes(0) = LoWordBytes(0)
  20.        ValueBytes(1) = LoWordBytes(1)
  21.  
  22.        Return BitConverter.ToInt32(ValueBytes, 0)
  23.  
  24.    End Function

Código
  1.    ' Set HiWord
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(SetHiWord(13959358I, 25S)) ' Result: 1638590I
  6.    '
  7.    ''' <summary>
  8.    ''' Sets the high-order word of an 'Int32' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param>
  11.    ''' <param name="NewHiWord">Indicates the new HiWord, an 'Int16' value.</param>
  12.    ''' <returns>The 'Int32' value containing both the LoWord and the new HiWord.</returns>
  13.    Private Function SetHiWord(ByVal Value As Integer,
  14.                               ByVal NewHiWord As Short) As Integer
  15.  
  16.        Dim ValueBytes As Byte() = BitConverter.GetBytes(Value)
  17.        Dim HiWordBytes As Byte() = BitConverter.GetBytes(NewHiWord)
  18.  
  19.        ValueBytes(2) = HiWordBytes(0)
  20.        ValueBytes(3) = HiWordBytes(1)
  21.  
  22.        Return BitConverter.ToInt32(ValueBytes, 0)
  23.  
  24.    End Function

Código
  1.    ' Set LoDword (From a Signed Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(SetLoDword(328576329396160L, -1553649828I)) ' Result: 328576329396060L
  6.    '
  7.    ''' <summary>
  8.    ''' Sets the low-order double word of an 'Int64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <param name="NewLoDword">Indicates the new LoDword, an 'Int32' value.</param>
  12.    ''' <returns>The 'Int64' value containing both the HiDword and the new LoDword.</returns>
  13.    Private Function SetLoDword(ByVal Value As Long,
  14.                                ByVal NewLoDword As Integer) As Long
  15.  
  16.        Dim ValueBytes As Byte() = BitConverter.GetBytes(Value)
  17.        Dim LoDwordBytes As Byte() = BitConverter.GetBytes(NewLoDword)
  18.  
  19.        ValueBytes(0) = LoDwordBytes(0)
  20.        ValueBytes(1) = LoDwordBytes(1)
  21.        ValueBytes(2) = LoDwordBytes(2)
  22.        ValueBytes(3) = LoDwordBytes(3)
  23.  
  24.        Return BitConverter.ToInt64(ValueBytes, 0)
  25.  
  26.    End Function

Código
  1.    ' Set HiDword (From a Signed Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(SetHiDword(328576329396160L, 987654321I)) ' Result: 4241943011189403584L
  6.    '
  7.    ''' <summary>
  8.    ''' Sets the high-order double word of an 'Int64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <param name="NewHiDword">Indicates the new HiDword, an 'Int32' value.</param>
  12.    ''' <returns>The 'Int64' value containing both the LoDword and the new HiDword.</returns>
  13.    Private Function SetHiDword(ByVal Value As Long,
  14.                                ByVal NewHiDword As Integer) As Long
  15.  
  16.        Dim ValueBytes As Byte() = BitConverter.GetBytes(Value)
  17.        Dim HiDwordBytes As Byte() = BitConverter.GetBytes(NewHiDword)
  18.  
  19.        ValueBytes(4) = HiDwordBytes(0)
  20.        ValueBytes(5) = HiDwordBytes(1)
  21.        ValueBytes(6) = HiDwordBytes(2)
  22.        ValueBytes(7) = HiDwordBytes(3)
  23.  
  24.        Return BitConverter.ToInt64(ValueBytes, 0)
  25.  
  26.    End Function

Código
  1.    ' Set LoDword (From an Unsigned Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(SetLoDword(328576329396160L, 123456789UI)) ' Result: 328573711535381L
  6.    '
  7.    ''' <summary>
  8.    ''' Sets the low-order double word of an 'Int64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <param name="NewLoDword">Indicates the new LoDword, an 'UInt32' value.</param>
  12.    ''' <returns>The 'Int64' value containing both the HiDword and the new LoDword.</returns>
  13.    Private Function SetLoDword(ByVal Value As Long,
  14.                                ByVal NewLoDword As UInteger) As Long
  15.  
  16.        Dim ValueBytes As Byte() = BitConverter.GetBytes(Value)
  17.        Dim LoDwordBytes As Byte() = BitConverter.GetBytes(NewLoDword)
  18.  
  19.        ValueBytes(0) = LoDwordBytes(0)
  20.        ValueBytes(1) = LoDwordBytes(1)
  21.        ValueBytes(2) = LoDwordBytes(2)
  22.        ValueBytes(3) = LoDwordBytes(3)
  23.  
  24.        Return BitConverter.ToInt64(ValueBytes, 0)
  25.  
  26.    End Function

Código
  1.    ' Set HiDword (From an Unsigned Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(SetHiDword(328576329396160L, 987654321UI)) ' Result: 4241943011189403584L
  6.    '
  7.    ''' <summary>
  8.    ''' Sets the high-order double word of an 'Int64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <param name="NewHiDword">Indicates the new HiDword, an 'UInt32' value.</param>
  12.    ''' <returns>The 'Int64' value containing both the LoDword and the new HiDword.</returns>
  13.    Private Function SetHiDword(ByVal Value As Long,
  14.                                ByVal NewHiDword As UInteger) As Long
  15.  
  16.        Dim ValueBytes As Byte() = BitConverter.GetBytes(Value)
  17.        Dim HiDwordBytes As Byte() = BitConverter.GetBytes(NewHiDword)
  18.  
  19.        ValueBytes(4) = HiDwordBytes(0)
  20.        ValueBytes(5) = HiDwordBytes(1)
  21.        ValueBytes(6) = HiDwordBytes(2)
  22.        ValueBytes(7) = HiDwordBytes(3)
  23.  
  24.        Return BitConverter.ToInt64(ValueBytes, 0)
  25.  
  26.    End Function
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #393 en: 11 Marzo 2014, 21:08 pm »

Determina si un caracter es diacrítico o si contiene una marca diacrítica (no es 100% efectivo con caracteres demasiado raros de otras culturas)

Código
  1.    ' Character Is Diacritic?
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(CharacterIsDiacritic("á")) ' Result: True
  6.    '
  7.    ''' <summary>
  8.    ''' Determines whether a character is diacritic or else contains a diacritical mark.
  9.    ''' </summary>
  10.    ''' <param name="Character">Indicates the character.</param>
  11.    ''' <returns><c>true</c> if character is diacritic or contains a diacritical mark, <c>false</c> otherwise.</returns>
  12.    Public Function CharacterIsDiacritic(ByVal Character As Char) As Boolean
  13.  
  14.        If String.IsNullOrEmpty(CharacterIsDiacritic) Then
  15.  
  16.            Return False
  17.        Else
  18.            Dim Descomposed As Char() = Character.ToString.Normalize(System.Text.NormalizationForm.FormKD).ToCharArray
  19.            Return (Descomposed.Count <> 1 OrElse String.IsNullOrWhiteSpace(Descomposed))
  20.  
  21.        End If
  22.  
  23.    End Function




Convierte un caracter diacritico

Código
  1.    ' Convert Diacritic Character
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(ConvertDiacritic("á", UnicodeNormalization:=System.Text.NormalizationForm.FormKD)) ' Result: 'a'
  6.    '
  7.    ''' <summary>
  8.    ''' Converts the diacritic characters in a String to an equivalent normalized English characters.
  9.    ''' </summary>
  10.    ''' <param name="Character">
  11.    ''' Indicates the diacritic character.
  12.    ''' </param>
  13.    ''' <param name="UnicodeNormalization">
  14.    ''' Defines the type of Unicode character normalization to perform.
  15.    ''' (Default is 'NormalizationForm.FormKD')
  16.    ''' </param>
  17.    ''' <returns>The converted character.</returns>
  18.    Public Function ConvertDiacritic(ByVal Character As Char,
  19.                                     Optional ByVal UnicodeNormalization As System.Text.NormalizationForm =
  20.                                                                            System.Text.NormalizationForm.FormKD) As String
  21.  
  22.        Dim Chars As Char() =
  23.            CStr(Character).Normalize(System.Text.NormalizationForm.FormKD).ToCharArray
  24.  
  25.        For Each c As Char In Chars
  26.  
  27.            Select Case Globalization.CharUnicodeInfo.GetUnicodeCategory(c)
  28.  
  29.                Case Globalization.UnicodeCategory.NonSpacingMark,
  30.                     Globalization.UnicodeCategory.SpacingCombiningMark,
  31.                     Globalization.UnicodeCategory.EnclosingMark
  32.  
  33.                    ' Do nothing.
  34.                    Exit Select
  35.  
  36.                Case Else
  37.                    Return c
  38.  
  39.            End Select
  40.  
  41.        Next c
  42.  
  43.        Return Character
  44.  
  45.    End Function



Obtiene el keyboardlayout

Código
  1.    ' Get Keyboard Layout
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetKeyboardLayout(IntPtr.Zero)) ' Result: 10
  6.    ' MsgBox(GetKeyboardLayout(Process.GetCurrentProcess.MainWindowHandle)) ' Result: 10
  7.    '
  8.    ''' <summary>
  9.    ''' Retrieves the active input locale identifier (formerly called the keyboard layout).
  10.    ''' </summary>
  11.    ''' <param name="idThread">
  12.    ''' A window handle identifier of the thread to query, or 'IntPtr.Zero' to query the current thread.
  13.    ''' </param>
  14.    ''' <returns>
  15.    ''' The return value is the input locale identifier for the thread.
  16.    ''' </returns>
  17.    Public Shared Function GetKeyboardLayout(Optional ByVal idThread As IntPtr = Nothing) As Short
  18.  
  19.        Return BitConverter.GetBytes(APIGetKeyboardLayout(idThread)).First
  20.  
  21.    End Function
  22.  
  23.    ''' <summary>
  24.    ''' Retrieves the active input locale identifier (formerly called the keyboard layout).
  25.    ''' </summary>
  26.    ''' <param name="idThread">
  27.    ''' A window handle identifier of the thread to query, or 'IntPtr.Zero' to query the current thread.
  28.    ''' </param>
  29.    ''' <returns>
  30.    ''' The return value is the input locale identifier for the thread.
  31.    '''
  32.    ''' The low-order byte contains a Language Identifier for the input language,
  33.    ''' and the high-order byte contains a device handle to the physical layout of the keyboard.
  34.    ''' </returns>
  35.    <System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="GetKeyboardLayout",
  36.    CharSet:=System.Runtime.InteropServices.CharSet.Unicode)>
  37.    Private Shared Function APIGetKeyboardLayout(
  38.                            Optional ByVal idThread As IntPtr = Nothing
  39.    ) As UInteger
  40.    End Function



Obtiene el keycode de un caracter (ojo, no el keycode virtual).

Código
  1.    ' Get KeyCode
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetKeyCode("a")) ' Result: 65
  6.    ' MsgBox(GetKeyCode("á")) ' Result: 65
  7.    ' MsgBox(GetKeyCode("á", IntPtr.Zero)) ' Result: 65
  8.    ' MsgBox(GetKeyCode("a", Process.GetCurrentProcess.MainWindowHandle)) ' Result: 65
  9.    '
  10.    'Private Sub Test() Handles MyBase.Shown
  11.    '    Dim sb As New System.Text.StringBuilder
  12.    '    Dim Characters As Char() = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ñÑçÇ áéíóú ÁÉÍÓÚ àèìòù ÀÈÌÒÙ äëïÖÜ ÄËÏÖÜ º\'¡`+´-.,ª!·$%&/()=?¿".ToCharArray
  13.    '    For Each c As Char In Characters
  14.    '        sb.AppendFormat("Character: {0}", CStr(c))
  15.    '        sb.AppendLine()
  16.    '        sb.AppendFormat("KeyCode  : {0}", CStr(GetKeyCode(c, IntPtr.Zero)))
  17.    '        MessageBox.Show(sb.ToString)
  18.    '        sb.Clear()
  19.    '    Next c
  20.    'End Sub
  21.  
  22.    ''' <summary>
  23.    ''' Translates a character to the corresponding keycode.
  24.    ''' </summary>
  25.    ''' <param name="Character">Indicates the character.</param>
  26.    ''' <param name="KeyboardLayout">Indicates the keyboard layout.</param>
  27.    ''' <returns>
  28.    ''' If the function succeeds, the return value contains the keycode.
  29.    '''
  30.    ''' If the function finds no key that translates to the passed character code,
  31.    ''' the return value contains "-1".
  32.    ''' </returns>
  33.    Public Shared Function GetKeyCode(ByVal Character As Char,
  34.                                      Optional ByVal KeyboardLayout As IntPtr = Nothing) As Short
  35.  
  36.        ' Get the Keycode of the character.
  37.        Dim Keycode As Short =
  38.            BitConverter.GetBytes(VkKeyScanEx(Character)).First
  39.  
  40.        Select Case Keycode
  41.  
  42.            Case Is <> 255S ' Character is found on the current KeyboardLayout.
  43.                Return Keycode
  44.  
  45.            Case Else ' Character is not found on the current KeyboardLayout.
  46.  
  47.                ' Descompose the character.
  48.                Dim Descomposed As Char() =
  49.                    Character.ToString.Normalize(System.Text.NormalizationForm.FormKD).ToCharArray
  50.  
  51.                ' If character is diacritic then...
  52.                If Descomposed.Count <> 1 OrElse String.IsNullOrWhiteSpace(Descomposed) Then
  53.  
  54.                    For Each c As Char In Descomposed
  55.  
  56.                        Select Case Globalization.CharUnicodeInfo.GetUnicodeCategory(c)
  57.  
  58.                            Case Globalization.UnicodeCategory.NonSpacingMark,
  59.                                 Globalization.UnicodeCategory.SpacingCombiningMark,
  60.                                 Globalization.UnicodeCategory.EnclosingMark
  61.  
  62.                                ' Do nothing.
  63.                                Exit Select
  64.  
  65.                            Case Else ' Character is diacritic so we convert the diacritic and try to find the Keycode.
  66.                                Return GetKeyCode(c, KeyboardLayout)
  67.  
  68.                        End Select
  69.  
  70.                    Next c
  71.  
  72.                End If ' Chars.Count <> 1
  73.  
  74.        End Select ' Keycode
  75.  
  76.        Return -1S ' Character is not diacritic and the keycode is not found.
  77.  
  78.    End Function
  79.  
  80.    ''' <summary>
  81.    ''' Translates a character to the corresponding virtual-key code and shift state.
  82.    ''' The function translates the character using the input language and
  83.    ''' physical keyboard layout identified by the input locale identifier.
  84.    ''' For more info see here:
  85.    ''' http://msdn.microsoft.com/en-us/library/ms646332%28v=VS.85%29.aspx
  86.    ''' </summary>
  87.    ''' <param name="c">Indicates the character.</param>
  88.    ''' <param name="KeyboardLayout">Indicates the keyboard layout.</param>
  89.    ''' <returns>
  90.    ''' If the function succeeds,
  91.    ''' the low-order byte of the return value contains the virtual-key code,
  92.    ''' and the high-order byte contains the shift state.
  93.    '''
  94.    ''' If the function finds no key that translates to the passed character code,
  95.    ''' both the low-order and high-order bytes contain '255'.
  96.    ''' </returns>
  97.    <System.Runtime.InteropServices.DllImport("user32.dll",
  98.    CharSet:=System.Runtime.InteropServices.CharSet.Unicode)>
  99.    Private Shared Function VkKeyScanEx(
  100.                            ByVal c As Char,
  101.                            Optional ByVal KeyboardLayout As IntPtr = Nothing
  102.    ) As Short
  103.    End Function



Envio de peticion por el método POST

Código
  1.    ' Send POST
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    'Dim Response As String =
  7.    '    SendPOST("http://es.wikipedia.org/wiki/Special:Search?",
  8.    '             New Dictionary(Of String, String) From {
  9.    '                 {"search", "Petición+POST"},
  10.    '                 {"sourceid", "Mozilla-search"}
  11.    '             }) ' Formated POST Data: "search=Petición+POST&sourceid=Mozilla-search"
  12.    'Clipboard.SetText(Response) ' Copy the response to Clipboard.
  13.    '
  14.    ''' <summary>
  15.    ''' Sends a POST method petition and returns the server response.
  16.    ''' </summary>
  17.    ''' <param name="URL">Indicates the URL.</param>
  18.    ''' <param name="PostData">Indicates the post data.</param>
  19.    ''' <returns>The response.</returns>
  20.    Public Function SendPOST(ByVal URL As String,
  21.                             ByVal PostData As Dictionary(Of String, String)) As String
  22.  
  23.        Dim Data As New System.Text.StringBuilder ' PostData to send, formated.
  24.        Dim Request As Net.HttpWebRequest = HttpWebRequest.Create(URL) ' HTTP Request.
  25.        Dim Response As HttpWebResponse ' Server response.
  26.        Dim ResponseContent As String ' Server response result.
  27.  
  28.        ' Set and format the post data of the query.
  29.        For Each Item As KeyValuePair(Of String, String) In PostData
  30.            Data.AppendFormat("{0}={1}&", Item.Key, Item.Value)
  31.        Next Item
  32.  
  33.        ' Set the Request properties.
  34.        With Request
  35.            .Method = "POST"
  36.            .ContentType = "application/x-www-form-urlencoded"
  37.            .ContentLength = Data.ToString.Length
  38.            .Proxy = Nothing
  39.            ' .UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"
  40.        End With
  41.  
  42.        ' Write the POST data bytes into the Stream.
  43.        Using RequestStream As IO.Stream = Request.GetRequestStream()
  44.            RequestStream.Write(System.Text.Encoding.UTF8.GetBytes(Data.ToString), 0, Data.ToString.Length)
  45.            RequestStream.Close()
  46.        End Using
  47.  
  48.        ' Get the response.
  49.        Response = Request.GetResponse()
  50.  
  51.        ' Get the response content.
  52.        Using Reader As New IO.StreamReader(Response.GetResponseStream)
  53.            ResponseContent = Reader.ReadToEnd
  54.            Response.Close()
  55.        End Using
  56.  
  57.        ' Return the response content.
  58.        Return ResponseContent
  59.  
  60.    End Function
« Última modificación: 11 Marzo 2014, 21:53 pm por Eleкtro » En línea



Synth3tik0

Desconectado Desconectado

Mensajes: 126


Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #394 en: 17 Marzo 2014, 19:34 pm »

uuh u_u esperaba q fueran para c#
« Última modificación: 10 Abril 2014, 01:13 am por ๖ۣۜPム||ムđ1ůɱ » En línea

..........
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 #395 en: 6 Abril 2014, 19:09 pm »

Usa esta herramienta:

http://www.developerfusion.com/tools/convert/vb-to-csharp/
En línea


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

Mensajes: 9.874



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

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

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





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

Código
  1.    ' Get Debug-Console Output
  2.    ' By Elektro
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'EnvDTE' and 'envdte80'
  6.    '
  7.    ' Usage Examples:
  8.    '
  9.    ' Clipboard.SetText(GetDebugConsoleOutput)
  10.    '
  11.    ''' <summary>
  12.    ''' Gets the debug console output.
  13.    ''' </summary>
  14.    ''' <returns>System.String.</returns>
  15.    Public Function GetDebugConsoleOutput() As String
  16.  
  17.        Dim Output As EnvDTE.TextSelection =
  18.            DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0"), EnvDTE80.DTE2).
  19.                       ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug").TextDocument.Selection
  20.  
  21.        Output.SelectAll()
  22.        Return Output.Text
  23.  
  24.    End Function
« Última modificación: 3 Agosto 2014, 15:44 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



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

Como promprobar si un Type es serializable:

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



Como comprobar si un objeto es serializable:

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



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

Código
  1. #If NET20 Then
  2.        ' This happens when the app targets .NEt Framework 2.0
  3.  
  4. #ElseIf NET40 Then
  5.        ' This happens when the app targets .NEt Framework 4.0
  6.  
  7. #End If
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



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

Ejemplo detallado de como parsear la salida estándar y la salida de error de un proceso, de forma asíncrona.

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



Un ayudante del proceso MKVMerge (de MKVToolnix)

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

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



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

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



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



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

Como crear un archivo dummy (vacío) de cualquier tamaño:

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



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

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

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



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

Ir a:  

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