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 ... 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 [56] 57 58 59 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 529,047 veces)
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #550 en: 10 Septiembre 2023, 06:35 am »

Aquí les dejo varias clases de atributos pensadas estrictamente para ser utilizadas en .NET Framework.

Estas clases de atributo sirven como sustitutos de las clases de atributo disponibles en .NET Core que llevan el mismo nombre.

De este modo, podemos utilizar las mismas clases de atributo pero en un código de .NET Framework, permitiendo aplicar estos atributos a un código antes de migrarlo a .NET Core.

Estas clases de atirubuto son una copia idéntica de las clases disponibles en .NET Core, incluyendo los argumentos de atributo.

El modo de empleo es como cualquier otra clase de atributo:

Código
  1. <Extension>
  2. <SupportedOSPlatform("windows")>
  3. Public Function ToRectangle(bmp As Bitmap) As Rectangle
  4.    Return New Rectangle(Point.Empty, bmp.Size)
  5. End Function



SupportedOSPlatformAttribute.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 23-June-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. #End Region
  17.  
  18. #If Not NETCOREAPP Then
  19.  
  20. Namespace DevCase.Runtime.Attributes
  21.  
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <summary>
  24.    ''' This attribute class is solely intended to simulate and therefore preserve the
  25.    ''' 'System.Runtime.Versioning.SupportedOSPlatformAttribute' attribute class when migrating projects to .NET Core.
  26.    ''' <para></para>
  27.    ''' This attribute class marks APIs that are supported for a specified platform or operating system.
  28.    ''' If a version is specified, the API cannot be called from an earlier version.
  29.    ''' <para></para>
  30.    ''' Multiple attributes can be applied to indicate support for multiple platforms or operating systems.
  31.    ''' </summary>
  32.    ''' ----------------------------------------------------------------------------------------------------
  33.    ''' <remarks>
  34.    ''' For more information, see <see href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.versioning.supportedosplatformattribute">SupportedOSPlatformAttribute Class</see>.
  35.    ''' </remarks>
  36.    ''' ----------------------------------------------------------------------------------------------------
  37.    ''' <seealso cref="System.Attribute" />
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    <AttributeUsage(AttributeTargets.Assembly Or
  40.                    AttributeTargets.Class Or
  41.                    AttributeTargets.Constructor Or
  42.                    AttributeTargets.Enum Or
  43.                    AttributeTargets.Event Or
  44.                    AttributeTargets.Field Or
  45.                    AttributeTargets.Interface Or
  46.                    AttributeTargets.Method Or
  47.                    AttributeTargets.Module Or
  48.                    AttributeTargets.Property Or
  49.                    AttributeTargets.Struct,
  50.    AllowMultiple:=True, Inherited:=False)>
  51.    Public NotInheritable Class SupportedOSPlatformAttribute : Inherits Attribute
  52.  
  53.        ''' ----------------------------------------------------------------------------------------------------
  54.        ''' <summary>
  55.        ''' Gets the supported OS platform name that this attribute applies to,
  56.        ''' optionally including a version (eg. "windows7.0").
  57.        ''' </summary>
  58.        ''' ----------------------------------------------------------------------------------------------------
  59.        Public ReadOnly Property PlatformName As String
  60.  
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        ''' <summary>
  63.        ''' Initializes a new instance of the <see cref="SupportedOSPlatformAttribute"/> attribute class
  64.        ''' for the specified supported OS platform (eg. "windows7.0").
  65.        ''' </summary>
  66.        ''' ----------------------------------------------------------------------------------------------------
  67.        ''' <param name="platformName">
  68.        ''' The supported OS platform name that this attribute applies to,
  69.        ''' optionally including a version (eg. "windows7.0").
  70.        ''' </param>
  71.        ''' ----------------------------------------------------------------------------------------------------
  72.        Public Sub New(platformName As String)
  73.            Me.PlatformName = platformName
  74.        End Sub
  75.  
  76.    End Class
  77.  
  78. End Namespace
  79.  
  80. #End If
  81.  



UnsupportedOSPlatformAttribute.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 23-June-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. #End Region
  17.  
  18. #If Not NETCOREAPP Then
  19.  
  20. Namespace DevCase.Runtime.Attributes
  21.  
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <summary>
  24.    ''' This attribute class is solely intended to simulate and therefore preserve the
  25.    ''' 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' attribute class when migrating projects to .NET Core.
  26.    ''' <para></para>
  27.    ''' This attribute class marks APIs that were removed or are unsupported in a given operating system version.
  28.    ''' <para></para>
  29.    ''' Multiple attributes can be applied to indicate unsupported platforms or operating systems.
  30.    ''' </summary>
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    ''' <remarks>
  33.    ''' For more information, see <see href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.versioning.unsupportedosplatformattribute">UnsupportedOSPlatformAttribute Class</see>.
  34.    ''' </remarks>
  35.    ''' ----------------------------------------------------------------------------------------------------
  36.    ''' <seealso cref="System.Attribute" />
  37.    ''' ----------------------------------------------------------------------------------------------------
  38.    <AttributeUsage(AttributeTargets.Assembly Or
  39.                    AttributeTargets.Class Or
  40.                    AttributeTargets.Constructor Or
  41.                    AttributeTargets.Enum Or
  42.                    AttributeTargets.Event Or
  43.                    AttributeTargets.Field Or
  44.                    AttributeTargets.Interface Or
  45.                    AttributeTargets.Method Or
  46.                    AttributeTargets.Module Or
  47.                    AttributeTargets.Property Or
  48.                    AttributeTargets.Struct,
  49.    AllowMultiple:=True, Inherited:=False)>
  50.    Public NotInheritable Class UnsupportedOSPlatformAttribute : Inherits Attribute
  51.  
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        ''' <summary>
  54.        ''' Gets the unsupported OS platform name that this attribute applies to,
  55.        ''' optionally including a version (eg. "windows7.0").
  56.        ''' </summary>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        Public ReadOnly Property PlatformName As String
  59.  
  60.        ''' ----------------------------------------------------------------------------------------------------
  61.        ''' <summary>
  62.        ''' Gets additional information about the unsupported API, for example,
  63.        ''' a message that mostly suggests a replacement for the unsupported API.
  64.        ''' </summary>
  65.        ''' ----------------------------------------------------------------------------------------------------
  66.        Public ReadOnly Property Message As String
  67.  
  68.        ''' ----------------------------------------------------------------------------------------------------
  69.        ''' <summary>
  70.        ''' Initializes a new instance of the <see cref="UnsupportedOSPlatformAttribute"/> attribute class
  71.        ''' for the specified unsupported OS platform.
  72.        ''' </summary>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        ''' <param name="platformName">
  75.        ''' The unsupported OS platform name that this attribute applies to,
  76.        ''' optionally including a version (eg. "windows7.0").
  77.        ''' </param>
  78.        ''' ----------------------------------------------------------------------------------------------------
  79.        Public Sub New(platformName As String)
  80.            Me.PlatformName = platformName
  81.        End Sub
  82.  
  83.        ''' ----------------------------------------------------------------------------------------------------
  84.        ''' <summary>
  85.        ''' Initializes a new instance of the <see cref="UnsupportedOSPlatformAttribute"/> attribute class
  86.        ''' for the specified unsupported OS platform with an additional message.
  87.        ''' </summary>
  88.        ''' ----------------------------------------------------------------------------------------------------
  89.        ''' <param name="platformName">
  90.        ''' The unsupported OS platform name that this attribute applies to,
  91.        ''' optionally including a version (eg. "windows7.0").
  92.        ''' </param>
  93.        '''
  94.        ''' <param name="message">
  95.        ''' Additional information about the unsupported API, for example,
  96.        ''' a message that mostly suggests a replacement for the unsupported API.
  97.        ''' </param>
  98.        ''' ----------------------------------------------------------------------------------------------------
  99.        Public Sub New(platformName As String, message As String)
  100.            Me.PlatformName = platformName
  101.            Me.Message = message
  102.        End Sub
  103.  
  104.    End Class
  105.  
  106. End Namespace
  107.  
  108. #End If
  109.  



ObsoletedOSPlatformAttribute.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 23-June-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. #End Region
  17.  
  18. #If Not NETCOREAPP Then
  19.  
  20. Namespace DevCase.Runtime.Attributes
  21.  
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <summary>
  24.    ''' This attribute class is solely intended to simulate and therefore preserve the
  25.    ''' 'System.Runtime.Versioning.ObsoletedOSPlatformAttribute' attribute class when migrating projects to .NET Core.
  26.    ''' <para></para>
  27.    ''' This attribute class marks APIs that were obsoleted in a given operating system version.
  28.    ''' <para></para>
  29.    ''' Multiple attributes can be applied to indicate obsoleted platforms or operating systems.
  30.    ''' </summary>
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    ''' <remarks>
  33.    ''' For more information, see <see href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.versioning.obsoletedosplatformattribute">ObsoletedOSPlatformAttribute Class</see>.
  34.    ''' </remarks>
  35.    ''' ----------------------------------------------------------------------------------------------------
  36.    ''' <seealso cref="System.Attribute" />
  37.    ''' ----------------------------------------------------------------------------------------------------
  38.    <AttributeUsage(AttributeTargets.Assembly Or
  39.                    AttributeTargets.Class Or
  40.                    AttributeTargets.Constructor Or
  41.                    AttributeTargets.Enum Or
  42.                    AttributeTargets.Event Or
  43.                    AttributeTargets.Field Or
  44.                    AttributeTargets.Interface Or
  45.                    AttributeTargets.Method Or
  46.                    AttributeTargets.Module Or
  47.                    AttributeTargets.Property Or
  48.                    AttributeTargets.Struct,
  49.    AllowMultiple:=True, Inherited:=False)>
  50.    Public NotInheritable Class ObsoletedOSPlatformAttribute : Inherits Attribute
  51.  
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        ''' <summary>
  54.        ''' Gets the obsoleted OS platform name that this attribute applies to,
  55.        ''' optionally including a version (eg. "windows7.0").
  56.        ''' </summary>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        Public ReadOnly Property PlatformName As String
  59.  
  60.        ''' ----------------------------------------------------------------------------------------------------
  61.        ''' <summary>
  62.        ''' Gets additional information about the obsoletion, for example,
  63.        ''' a message that mostly suggests an alternative for the obsoleted API.
  64.        ''' </summary>
  65.        ''' ----------------------------------------------------------------------------------------------------
  66.        Public ReadOnly Property Message As String
  67.  
  68.        ''' ----------------------------------------------------------------------------------------------------
  69.        ''' <summary>
  70.        ''' Initializes a new instance of the <see cref="UnsupportedOSPlatformAttribute"/> attribute class
  71.        ''' for the specified obsoleted OS platform.
  72.        ''' </summary>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        ''' <param name="platformName">
  75.        ''' The obsoleted OS platform name that this attribute applies to,
  76.        ''' optionally including a version (eg. "windows7.0").
  77.        ''' </param>
  78.        ''' ----------------------------------------------------------------------------------------------------
  79.        Public Sub New(platformName As String)
  80.            Me.PlatformName = platformName
  81.        End Sub
  82.  
  83.        ''' ----------------------------------------------------------------------------------------------------
  84.        ''' <summary>
  85.        ''' Initializes a new instance of the <see cref="UnsupportedOSPlatformAttribute"/> attribute class
  86.        ''' for the specified obsoleted OS platform with an additional message.
  87.        ''' </summary>
  88.        ''' ----------------------------------------------------------------------------------------------------
  89.        ''' <param name="platformName">
  90.        ''' The obsoleted OS platform name that this attribute applies to,
  91.        ''' optionally including a version (eg. "windows7.0").
  92.        ''' </param>
  93.        '''
  94.        ''' <param name="message">
  95.        ''' Additional information about the obsoletion, for example,
  96.        ''' a message that mostly suggests an alternative for the obsoleted API.
  97.        ''' </param>
  98.        ''' ----------------------------------------------------------------------------------------------------
  99.        Public Sub New(platformName As String, message As String)
  100.            Me.PlatformName = platformName
  101.            Me.Message = message
  102.        End Sub
  103.  
  104.    End Class
  105.  
  106. End Namespace
  107.  
  108. #End If
  109.  



TargetPlatformAttribute.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 23-June-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. #End Region
  17.  
  18. #If Not NETCOREAPP Then
  19.  
  20. Namespace DevCase.Runtime.Attributes
  21.  
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <summary>
  24.    ''' This attribute class is solely intended to simulate and therefore preserve the
  25.    ''' 'System.Runtime.Versioning.TargetPlatformAttribute' attribute class when migrating projects to .NET Core.
  26.    ''' <para></para>
  27.    ''' This attribute class specifies the operating system that a project targets, for example, Windows or iOS.
  28.    ''' </summary>
  29.    ''' ----------------------------------------------------------------------------------------------------
  30.    ''' <remarks>
  31.    ''' For more information, see <see href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.versioning.targetplatformattribute">TargetPlatformAttribute Class</see>.
  32.    ''' </remarks>
  33.    ''' ----------------------------------------------------------------------------------------------------
  34.    ''' <seealso cref="System.Attribute" />
  35.    ''' ----------------------------------------------------------------------------------------------------
  36.    <AttributeUsage(AttributeTargets.Assembly, AllowMultiple:=False, Inherited:=False)>
  37.    Public NotInheritable Class TargetPlatformAttribute : Inherits Attribute
  38.  
  39.        ''' ----------------------------------------------------------------------------------------------------
  40.        ''' <summary>
  41.        ''' Gets the target OS platform name that this attribute applies to (eg. "windows").
  42.        ''' </summary>
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        Public ReadOnly Property PlatformName As String
  45.  
  46.        ''' ----------------------------------------------------------------------------------------------------
  47.        ''' <summary>
  48.        ''' Initializes a new instance of the <see cref="TargetPlatformAttribute"/> attribute class
  49.        ''' for the specified target OS platform.
  50.        ''' </summary>
  51.        ''' ----------------------------------------------------------------------------------------------------
  52.        ''' <param name="platformName">
  53.        ''' The target OS platform name that this attribute applies to (eg. "windows").
  54.        ''' </param>
  55.        ''' ----------------------------------------------------------------------------------------------------
  56.        Public Sub New(platformName As String)
  57.            Me.PlatformName = platformName
  58.        End Sub
  59.  
  60.    End Class
  61.  
  62. End Namespace
  63.  
  64. #End If
  65.  



ModuleInitializerAttribute.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 23-June-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. #End Region
  17.  
  18. #If Not NETCOREAPP Then
  19.  
  20. Namespace DevCase.Runtime.Attributes
  21.  
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <summary>
  24.    ''' This attribute class is solely intended to simulate and therefore preserve the
  25.    ''' 'System.Runtime.CompilerServices.ModuleInitializerAttribute' attribute class when migrating projects to .NET Core.
  26.    ''' <para></para>
  27.    ''' This attribute indicates to the compiler that a method should be called in its containing module's initializer.
  28.    ''' </summary>
  29.    ''' ----------------------------------------------------------------------------------------------------
  30.    ''' <remarks>
  31.    ''' For more information, see <see href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.moduleinitializerattribute">ModuleInitializerAttribute Class</see>.
  32.    ''' <para></para>
  33.    ''' When one or more valid methods with this attribute are found in a compilation,
  34.    ''' the compiler will emit a module initializer that calls each of the attributed methods.
  35.    ''' </remarks>
  36.    ''' ----------------------------------------------------------------------------------------------------
  37.    ''' <seealso cref="System.Attribute" />
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    <AttributeUsage(AttributeTargets.Method, AllowMultiple:=False, Inherited:=False)>
  40.    Public NotInheritable Class ModuleInitializerAttribute : Inherits Attribute
  41.  
  42.        ''' ----------------------------------------------------------------------------------------------------
  43.        ''' <summary>
  44.        ''' Initializes a new instance of the <see cref="ModuleInitializerAttribute"/> attribute class.
  45.        ''' </summary>
  46.        ''' ----------------------------------------------------------------------------------------------------
  47.        Public Sub New()
  48.        End Sub
  49.  
  50.    End Class
  51.  
  52. End Namespace
  53.  
  54. #End If
  55.  



SkipLocalsInitAttribute.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 23-June-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. #End Region
  17.  
  18. #If Not NETCOREAPP Then
  19.  
  20. Namespace DevCase.Runtime.Attributes
  21.  
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <summary>
  24.    ''' This attribute class is solely intended to simulate and therefore preserve the
  25.    ''' 'System.Runtime.CompilerServices.SkipLocalsInitAttribute' attribute class when migrating projects to .NET Core.
  26.    ''' <para></para>
  27.    ''' This attribute indicates to the compiler that the .locals init flag should not be set
  28.    ''' in nested method headers when emitting to metadata.
  29.    ''' </summary>
  30.    ''' ----------------------------------------------------------------------------------------------------
  31.    ''' <remarks>
  32.    ''' For more information, see <see href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.skiplocalsinitattribute">SkipLocalsInitAttribute Class</see>.
  33.    ''' <para></para>
  34.    ''' This attribute is unsafe, because it may reveal uninitialized memory to the application in certain instances
  35.    ''' (for example, reading from uninitialized stack-allocated memory).
  36.    ''' <para></para>
  37.    ''' If applied to a method directly, the attribute applies to that method and all its nested functions,
  38.    ''' including lambdas and local functions.
  39.    ''' <para></para>
  40.    ''' If applied to a type or module, it applies to all methods nested inside.
  41.    ''' <para></para>
  42.    ''' This attribute is intentionally not permitted on assemblies.
  43.    ''' <para></para>
  44.    ''' To apply the attribute to multiple type declarations, use it at the module level instead.
  45.    ''' </remarks>
  46.    ''' ----------------------------------------------------------------------------------------------------
  47.    ''' <seealso cref="System.Attribute" />
  48.    ''' ----------------------------------------------------------------------------------------------------
  49.    <AttributeUsage(AttributeTargets.Class Or
  50.                    AttributeTargets.Constructor Or
  51.                    AttributeTargets.Event Or
  52.                    AttributeTargets.Interface Or
  53.                    AttributeTargets.Method Or
  54.                    AttributeTargets.Module Or
  55.                    AttributeTargets.Property Or
  56.                    AttributeTargets.Struct,
  57.    AllowMultiple:=False, Inherited:=False)>
  58.    Public NotInheritable Class SkipLocalsInitAttribute : Inherits Attribute
  59.  
  60.        ''' ----------------------------------------------------------------------------------------------------
  61.        ''' <summary>
  62.        ''' Initializes a new instance of the <see cref="SkipLocalsInitAttribute"/> attribute class.
  63.        ''' </summary>
  64.        ''' ----------------------------------------------------------------------------------------------------
  65.        Public Sub New()
  66.        End Sub
  67.  
  68.    End Class
  69.  
  70. End Namespace
  71.  
  72. #End If
  73.  


« Última modificación: 10 Septiembre 2023, 06:41 am por Elektro Enjuto » En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #551 en: 10 Septiembre 2023, 06:45 am »

He escrito este código que permite obtener el código IL (Intermediate Language Code) de un método dinámico para posteriormente manipularlo mediante un array de bytes:

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Returns the MSIL for the method body of the source <see cref="DynamicMethod"/>, as an array of bytes.
  4. ''' <para></para>
  5. ''' This is the necessary equivalent for <see cref="MethodBody.GetILCodeAsByteArray()"/> function,
  6. ''' because <see cref="MethodBody.GetILCodeAsByteArray()"/> will not work with the method body returned by
  7. ''' an <see cref="DynamicMethod.GetMethodBody()"/> function since the IL code is stored in
  8. ''' the MethodBuilder's ILGenerator.
  9. ''' </summary>
  10. ''' ----------------------------------------------------------------------------------------------------
  11. ''' <example> This is a code example #1.
  12. ''' <code language="VB.NET">
  13. ''' Dim dynMethod As New DynamicMethod("my_dynamic_method_name", Nothing, Type.EmptyTypes, restrictedSkipVisibility:=True)
  14. ''' Dim ilGen As ILGenerator = dynMethod.GetILGenerator(streamSize:=64)
  15. ''' ilGen.Emit(OpCodes.Nop)
  16. '''
  17. ''' Dim ilCode As Byte() = GetILCodeAsByteArray(dynMethod)
  18. ''' </code>
  19. ''' </example>
  20. ''' ----------------------------------------------------------------------------------------------------
  21. ''' <example> This is a code example #2.
  22. ''' <code language="VB.NET">
  23. ''' ' Create a simple dynamic method that has no parameters and does not return a value.
  24. ''' Dim dynMethod As New DynamicMethod("my_dynamic_method_name", Nothing, Type.EmptyTypes, restrictedSkipVisibility:=True)
  25. '''
  26. ''' ' Get an ILGenerator and emit a body for the dynamic method.
  27. ''' Dim il As ILGenerator = dynMethod.GetILGenerator(streamSize:=64)
  28. ''' il.Emit(OpCodes.Nop)
  29. ''' il.Emit(OpCodes.Ret)
  30. '''
  31. ''' ' Completes the dynamic method and creates a delegate that can be used to execute it.
  32. ''' ' Any further attempts to change the IL code will cause an exception.
  33. ''' Dim dynMethodInvoker As Action = CType(dynMethod.CreateDelegate(GetType(Action)), Action)
  34. '''
  35. ''' ' Get the IL code.
  36. ''' Dim ilCode As Byte() = GetILCodeAsByteArray(dynMethod)
  37. '''
  38. ''' Console.WriteLine($"Method body's IL bytes: {String.Join(", ", ilCode)}")
  39. ''' </code>
  40. ''' </example>
  41. ''' ----------------------------------------------------------------------------------------------------
  42. ''' <param name="dynMethod">
  43. ''' The source <see cref="DynamicMethod"/>.
  44. ''' </param>
  45. ''' ----------------------------------------------------------------------------------------------------
  46. ''' <returns>
  47. ''' The MSIL for the method body of the source <see cref="DynamicMethod"/>, as an array of bytes.
  48. ''' </returns>
  49. ''' ----------------------------------------------------------------------------------------------------
  50. <DebuggerStepThrough>
  51. <Extension>
  52. <EditorBrowsable(EditorBrowsableState.Always)>
  53. Public Function GetILCodeAsByteArray(dynMethod As DynamicMethod) As Byte()
  54.  
  55.    Dim bindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic
  56.  
  57.    ' First we try to retrieve the value of "m_resolver" field,
  58.    ' which will always be null unless the dynamic method is completed
  59.    ' by either calling 'dynMethod.CreateDelegate()' or 'dynMethod.Invoke()' function.
  60.    ' Source: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.dynamicmethod.getilgenerator
  61.    ' (in remarks section)
  62.  
  63.    ' Note that the dynamic method object does not know when it is ready for use
  64.    ' since there is not API which indicates that IL generation has completed.
  65.    ' Source: https://referencesource.microsoft.com/#mscorlib/system/reflection/emit/dynamicmethod.cs,7fc135a2ceea0854,references
  66.    ' (in commentary lines)
  67.  
  68.    Dim resolver As Object = GetType(DynamicMethod).GetField("m_resolver", bindingFlags).GetValue(dynMethod)
  69.    If resolver IsNot Nothing Then
  70.        Return DirectCast(resolver.GetType().GetField("m_code", bindingFlags).GetValue(resolver), Byte())
  71.  
  72.    Else
  73.        ' So, if the dynamic method is not completed, we will retrieve the "m_ILStream" field instead.
  74.        ' The only difference I notice between "m_resolver" and "m_ILStream" fields is that the IL bytes in "m_ILStream"
  75.        ' will have trailing zeros / null bytes depending on the amount of unused bytes in this stream.
  76.        ' ( The buffer size for "m_ILStream" is allocated by a call to 'dynMethod.GetILGenerator(streamSize)' function. )
  77.  
  78.        Dim ilGen As ILGenerator = dynMethod.GetILGenerator()
  79.  
  80.        ' Conditional for .NET 4.x because DynamicILGenerator class derived from ILGenerator.
  81.        ' Source: https://stackoverflow.com/a/4147132/1248295
  82.        Dim ilStream As FieldInfo = If(Environment.Version.Major >= 4,
  83.            ilGen.GetType().BaseType.GetField("m_ILStream", bindingFlags),
  84.            ilGen.GetType().GetField("m_ILStream", bindingFlags))
  85.  
  86.        Return TryCast(ilStream.GetValue(ilGen), Byte())
  87.    End If
  88.  
  89. End Function

Ejemplo de uso:

Código
  1. Dim dynMethod As New DynamicMethod("my_dynamic_method_name", Nothing, Type.EmptyTypes, restrictedSkipVisibility:=True)
  2. Dim ilGen As ILGenerator = dynMethod.GetILGenerator(streamSize:=64)
  3. ilGen.Emit(OpCodes.Nop)
  4.  
  5. Dim ilCode As Byte() = GetILCodeAsByteArray(dynMethod)


« Última modificación: 10 Septiembre 2023, 06:58 am por Elektro Enjuto » En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #552 en: 10 Septiembre 2023, 07:32 am »

Un sustituto de la clase System.Random para generar números aleatorios.

Ejemplo de uso:

Código
  1. RandomNumberGenerator.Instance.Next(0, 10)



RandomNumberGenerator.vb

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 25-November-2022
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. Imports System.Security.Cryptography
  17.  
  18. #End Region
  19.  
  20. #Region " RandomNumberGenerator "
  21.  
  22. ' ReSharper disable once CheckNamespace
  23.  
  24. Namespace DevCase.Runtime.Numerics
  25.  
  26.    ''' ----------------------------------------------------------------------------------------------------
  27.    ''' <summary>
  28.    ''' Wrapper class for thread-safe generation of pseudo-random numbers.
  29.    ''' <para></para>
  30.    ''' Lazy-load singleton for ThreadStatic <see cref="Random"/>.
  31.    ''' </summary>
  32.    ''' ----------------------------------------------------------------------------------------------------
  33.    <CodeAnalysis.SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification:="Required to migrate this code to .NET Core")>
  34.    Public Class RandomNumberGenerator
  35.  
  36. #Region " Private Fields "
  37.  
  38.        ''' ----------------------------------------------------------------------------------------------------
  39.        ''' <summary>
  40.        ''' The <see cref="Random"/> instance for generation of pseudo-random numbers.
  41.        ''' </summary>
  42.        ''' ----------------------------------------------------------------------------------------------------
  43.        <ThreadStatic>
  44.        Private Shared RNG As Random
  45.  
  46. #End Region
  47.  
  48. #Region " Properties "
  49.  
  50.        ''' ----------------------------------------------------------------------------------------------------
  51.        ''' <summary>
  52.        ''' Gets a <see cref="Random"/> instance for generation of pseudo-random numbers.
  53.        ''' </summary>
  54.        ''' ----------------------------------------------------------------------------------------------------
  55.        Public Shared ReadOnly Property Instance As Random
  56.            Get
  57.                If RandomNumberGenerator.RNG Is Nothing Then
  58.                    Dim buffer As Byte() = New Byte(3) {}
  59. #Disable Warning SYSLIB0023 ' Type or member is obsolete
  60.                    Using rngProvider As New RNGCryptoServiceProvider()
  61.                        rngProvider.GetBytes(buffer)
  62.                        RandomNumberGenerator.RNG = New Random(Seed:=BitConverter.ToInt32(buffer, 0))
  63.                    End Using
  64. #Enable Warning SYSLIB0023 ' Type or member is obsolete
  65.                End If
  66.  
  67.                Return RandomNumberGenerator.RNG
  68.            End Get
  69.        End Property
  70.  
  71. #End Region
  72.  
  73.    End Class
  74.  
  75. End Namespace
  76.  
  77. #End Region

En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #553 en: 10 Septiembre 2023, 07:55 am »

Les presento mi GENERADOR DE CONTRASEÑAS MEMORIZABLES.

Inspirado en el proyecto: https://xkpasswd.net/s/ y https://www.bartbusschots.ie/s/publications/software/xkpasswd/

Ejemplo de uso:
Código
  1. Dim options As New MemorablePasswordOptions With {
  2.    .NumberOfWords = 3,
  3.    .MinimumWordLength = 4,
  4.    .MaximumWordLength = 8,
  5.    .SeparatorCharacters = "._-+".ToCharArray(),
  6.    .StringCase = MemorablePasswordStringCase.TitleCase,
  7.    .FixedPrefix = Nothing,
  8.    .FixedSuffix = "!",
  9.    .NumberOfDigitsPrefix = 0,
  10.    .NumberOfDigitsSuffix = 3
  11. }
  12.  
  13. Dim wordList As String() = System.IO.File.ReadAllLines(".\words.txt", Encoding.Default)
  14.  
  15. For i As Integer = 0 To 10
  16.    Dim password As String = UtilPasswords.GenerateMemorablePassword(options, wordList)
  17.    Console.WriteLine(password)
  18. Next

Salida:
Código:
Actor+Teaching_Spring-174!
Example_Hotel_Slavery_861!
Maximum-Accuse_Offense.016!
Banana.China.Baseball-154!
Attach+Wash-Wagon+647!
Consumer+Allow.Boom-946!
Employ+Lose+Opinion_106!
Feel.Carbon.Focus+176!
Candy-Remove+Kick+581!
Internal-Buddy_Wide-280!
Serious-Everyone+Approve-522!

El tipo y estructura de la contraseña se puede personalizar mediante el objeto de tipo MemorablePasswordOptions para adaptarlo a su gusto y necesidades.



Clase principal, UtilPasswords.vb

Código
  1. Imports DevCase.Core.DataProcessing.Common
  2. Imports DevCase.Core.Security.Passwords
  3. Imports DevCase.Extensions
  4. Imports DevCase.Runtime.Numerics
  5.  
  6. Imports System.Text
  7.  
  8. Public Class UtilPasswords
  9.  
  10.    ''' ----------------------------------------------------------------------------------------------------
  11.    ''' <summary>
  12.    ''' Generates a memorable password based on the provided options and word list.
  13.    ''' <para></para>
  14.    ''' A memorable password is a type of password that is designed to be easy to remember,
  15.    ''' while still providing a reasonable level of security.
  16.    ''' <para></para>
  17.    ''' It is a password generation methodology that aims to be recalled by the user
  18.    ''' without the need for written notes or  relying solely on password managers.
  19.    ''' <para></para>
  20.    ''' The concept behind a memorable password is to create a combination of words, phrases,
  21.    ''' or memorable patterns that are personally meaningful to the user.
  22.    ''' This can include using familiar words, personal information,
  23.    ''' or unique combinations that have personal significance.
  24.    ''' <para></para>
  25.    ''' The goal is to create a password that is both secure and memorable,
  26.    ''' striking a balance between convenience and protection.
  27.    ''' </summary>
  28.    ''' ----------------------------------------------------------------------------------------------------
  29.    ''' <remarks>
  30.    ''' The generated password by this function follows the following format:
  31.    ''' (FixedPrefix)(DigitsPrefix+Separator)(Words+Separators)(Separator+DigitsSuffix)(FixedSuffix)
  32.    ''' </remarks>
  33.    ''' ----------------------------------------------------------------------------------------------------
  34.    ''' <example> This is a code example.
  35.    ''' <code language="VB.NET">
  36.    ''' Dim options As New MemorablePasswordOptions With {
  37.    '''     .NumberOfWords = 3,
  38.    '''     .MinimumWordLength = 4,
  39.    '''     .MaximumWordLength = 8,
  40.    '''     .SeparatorCharacters = "._-+".ToCharArray(),
  41.    '''     .StringCase = MemorablePasswordStringCase.TitleCase,
  42.    '''     .FixedPrefix = Nothing,
  43.    '''     .FixedSuffix = "!",
  44.    '''     .NumberOfDigitsPrefix = 0,
  45.    '''     .NumberOfDigitsSuffix = 3
  46.    ''' }
  47.    '''
  48.    ''' Dim wordList As String() = System.IO.File.ReadAllLines(".\words.txt", Encoding.Default)
  49.    '''
  50.    ''' For i As Integer = 0 To 10
  51.    '''     Dim password As String = GenerateMemorablePassword(options, wordList)
  52.    '''     Console.WriteLine(password)
  53.    ''' Next
  54.    ''' </code>
  55.    ''' </example>
  56.    ''' ----------------------------------------------------------------------------------------------------
  57.    ''' <param name="options">
  58.    ''' The options for generating the memorable password.
  59.    ''' </param>
  60.    '''
  61.    ''' <param name="wordList">
  62.    ''' The list of words to choose from.
  63.    ''' </param>
  64.    ''' ----------------------------------------------------------------------------------------------------
  65.    ''' <returns>
  66.    ''' The resulting memorable password.
  67.    ''' </returns>
  68.    ''' ----------------------------------------------------------------------------------------------------
  69.    <DebuggerStepThrough>
  70.    Public Shared Function GenerateMemorablePassword(options As MemorablePasswordOptions, wordList As IEnumerable(Of String)) As String
  71.  
  72.        If options.NumberOfDigitsPrefix < 0 Then
  73.            Throw New InvalidOperationException(
  74.                $"Value of property: '{NameOf(options)}.{options.NumberOfDigitsPrefix}' must be zero or greather.")
  75.        End If
  76.  
  77.        If options.NumberOfDigitsSuffix < 0 Then
  78.            Throw New InvalidOperationException(
  79.                $"Value of property: '{NameOf(options)}.{options.NumberOfDigitsSuffix}' must be zero or greather.")
  80.        End If
  81.  
  82.        Dim filteredWords As IEnumerable(Of String) =
  83.            wordList.Where(Function(word As String)
  84.                               Return word.Length >= options.MinimumWordLength AndAlso
  85.                                      word.Length <= options.MaximumWordLength
  86.                           End Function)
  87.  
  88.        Dim filteredWordsCount As Integer = filteredWords.Count
  89.        If filteredWordsCount = 0 Then
  90.            Throw New InvalidOperationException(
  91.                "The provided word list does not contain any word between the " &
  92.                "minimum and maximum word length specified in properties: " &
  93.                $"'{options}.{options.MinimumWordLength}' and '{options}.{options.MaximumWordLength}'.")
  94.        End If
  95.        If filteredWordsCount < options.NumberOfWords Then
  96.            Throw New InvalidOperationException(
  97.                "The provided word list does not contain the" &
  98.                $"enough number of words specified in property: '{options}.{options.NumberOfWords}'.")
  99.        End If
  100.  
  101.        Dim selectedWords As New HashSet(Of String)
  102.        Do Until selectedWords.Count = options.NumberOfWords
  103.            selectedWords.Add(filteredWords(RandomNumberGenerator.Instance.Next(0, filteredWordsCount)))
  104.        Loop
  105.  
  106.        Dim separatorsCount As Integer
  107.        If options.SeparatorCharacters IsNot Nothing Then
  108.            separatorsCount = options.SeparatorCharacters.Length
  109.        End If
  110.  
  111.        Const digits As String = "1234567890"
  112.  
  113.        Dim sb As New StringBuilder()
  114.  
  115.        ' 1. Append the fixed prefix if provided.
  116.        sb.Append(options.FixedPrefix)
  117.  
  118.        ' 2. Append a prefix of digits if provided, and a separator if provided.
  119.        If options.NumberOfDigitsPrefix <> 0 Then
  120.            For i As Integer = 0 To options.NumberOfDigitsPrefix - 1
  121.                sb.Append(digits(RandomNumberGenerator.Instance.Next(0, digits.Length)))
  122.            Next
  123.            If options.SeparatorCharacters IsNot Nothing AndAlso separatorsCount <> 0 Then
  124.                sb.Append(options.SeparatorCharacters(RandomNumberGenerator.Instance.Next(0, separatorsCount)))
  125.            End If
  126.        End If
  127.  
  128.        ' 3. Append the selected words, together with the word separators if provided.
  129.        Dim selectedWordsCount As Integer = selectedWords.Count
  130.        For i As Integer = 0 To selectedWordsCount - 1
  131.            sb.Append(StringExtensions.Rename(selectedWords(i), CType(options.StringCase, StringCase)))
  132.            If i <> (selectedWordsCount - 1) Then
  133.                If options.SeparatorCharacters IsNot Nothing AndAlso separatorsCount <> 0 Then
  134.                    sb.Append(options.SeparatorCharacters(RandomNumberGenerator.Instance.Next(0, separatorsCount)))
  135.                End If
  136.            End If
  137.        Next
  138.  
  139.        ' 4. Append a separator if provided, and a suffix of digits if provided.
  140.        If options.NumberOfDigitsSuffix <> 0 Then
  141.            If options.SeparatorCharacters IsNot Nothing AndAlso separatorsCount <> 0 Then
  142.                sb.Append(options.SeparatorCharacters(RandomNumberGenerator.Instance.Next(0, separatorsCount)))
  143.            End If
  144.            For i As Integer = 0 To options.NumberOfDigitsSuffix - 1
  145.                sb.Append(digits(RandomNumberGenerator.Instance.Next(0, digits.Length)))
  146.            Next
  147.        End If
  148.  
  149.        ' 5. Append the fixed suffix if provided.
  150.        sb.Append(options.FixedSuffix)
  151.  
  152.        ' (FixedPrefix)(DigitsPrefix+Separator)(Words+Separators)(Separator+DigitsSuffix)(FixedSuffix)
  153.        Return sb.ToString()
  154.  
  155.    End Function
  156.  
  157. End Class



RandomNumberGenerator.vb
https://foro.elhacker.net/net_c_vbnet_asp/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg2272581#msg2272581



MemorablePasswordOptions.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 14-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. #End Region
  17.  
  18. #Region " UtilPasswords "
  19.  
  20. ' ReSharper disable once CheckNamespace
  21.  
  22. Namespace DevCase.Core.Security.Passwords
  23.  
  24.    ''' ----------------------------------------------------------------------------------------------------
  25.    ''' <summary>
  26.    ''' Represents the options for generating a memorable password
  27.    ''' with <see cref="UtilPasswords.GenerateMemorablePassword"/> function.
  28.    ''' </summary>
  29.    ''' ----------------------------------------------------------------------------------------------------
  30.    Public Class MemorablePasswordOptions
  31.  
  32. #Region " Properties "
  33.  
  34.        ''' ----------------------------------------------------------------------------------------------------
  35.        ''' <summary>
  36.        ''' Gets or sets the number of words to include in the password.
  37.        ''' </summary>
  38.        ''' ----------------------------------------------------------------------------------------------------
  39.        Public Property NumberOfWords As Integer
  40.  
  41.        ''' ----------------------------------------------------------------------------------------------------
  42.        ''' <summary>
  43.        ''' Gets or sets the minimum length of a word to consider for the password.
  44.        ''' </summary>
  45.        ''' ----------------------------------------------------------------------------------------------------
  46.        Public Property MinimumWordLength As Integer
  47.  
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        ''' <summary>
  50.        ''' Gets or sets the maximum length of a word to consider for the password.
  51.        ''' </summary>
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        Public Property MaximumWordLength As Integer
  54.  
  55.        ''' ----------------------------------------------------------------------------------------------------
  56.        ''' <summary>
  57.        ''' Gets or sets the characters to use as separators between words.
  58.        ''' </summary>
  59.        ''' ----------------------------------------------------------------------------------------------------
  60.        Public Property SeparatorCharacters As Char()
  61.  
  62.        ''' ----------------------------------------------------------------------------------------------------
  63.        ''' <summary>
  64.        ''' Gets or sets the prefix to prepend to the password.
  65.        ''' </summary>
  66.        ''' ----------------------------------------------------------------------------------------------------
  67.        Public Property FixedPrefix As String
  68.  
  69.        ''' ----------------------------------------------------------------------------------------------------
  70.        ''' <summary>
  71.        ''' Gets or sets the suffix to append to the password.
  72.        ''' </summary>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        Public Property FixedSuffix As String
  75.  
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <summary>
  78.        ''' Gets or sets the number of digits to include as a prefix to the password
  79.        ''' (after prepending <see cref="MemorablePasswordOptions.FixedPrefix"/>).
  80.        ''' </summary>
  81.        ''' ----------------------------------------------------------------------------------------------------
  82.        Public Property NumberOfDigitsPrefix As Integer
  83.  
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        ''' <summary>
  86.        ''' Gets or sets the number of digits to include as a suffix to the password
  87.        ''' (before appending <see cref="MemorablePasswordOptions.FixedSuffix"/>).
  88.        ''' </summary>
  89.        ''' ----------------------------------------------------------------------------------------------------
  90.        Public Property NumberOfDigitsSuffix As Integer
  91.  
  92.        ''' ----------------------------------------------------------------------------------------------------
  93.        ''' <summary>
  94.        ''' Gets or sets the case of the words in the password.
  95.        ''' </summary>
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        Public Property StringCase As MemorablePasswordStringCase
  98.  
  99. #End Region
  100.  
  101. #Region " Constructors "
  102.  
  103.        ''' ----------------------------------------------------------------------------------------------------
  104.        ''' <summary>
  105.        ''' Initializes a new instance of the <see cref="MemorablePasswordOptions"/> class.
  106.        ''' </summary>
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        Public Sub New()
  109.        End Sub
  110.  
  111. #End Region
  112.    End Class
  113.  
  114. End Namespace
  115.  
  116. #End Region
  117.  



MemorablePasswordStringCase.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 14-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. Imports DevCase.Core.DataProcessing.Common
  17.  
  18. #End Region
  19.  
  20. #Region " MemorablePasswordStringCase "
  21.  
  22. ' ReSharper disable once CheckNamespace
  23.  
  24. Namespace DevCase.Core.Security.Passwords
  25.  
  26.    ''' <summary>
  27.    ''' Specifies the string-case of the words in a memorable password.
  28.    ''' </summary>
  29.    Public Enum MemorablePasswordStringCase
  30.  
  31.        ''' <summary>
  32.        ''' Changes all characters to lower-case.
  33.        ''' <para></para>
  34.        '''
  35.        ''' [Example]
  36.        ''' <para></para>
  37.        ''' Input : ABCDEF
  38.        ''' <para></para>
  39.        ''' Output: abcdef
  40.        ''' </summary>
  41.        LowerCase = StringCase.LowerCase
  42.  
  43.        ''' <summary>
  44.        ''' Changes all characters to upper-case.
  45.        ''' <para></para>
  46.        '''
  47.        ''' [Example]
  48.        ''' <para></para>
  49.        ''' Input : abcdef
  50.        ''' <para></para>
  51.        ''' Output: ABCDEF
  52.        ''' </summary>
  53.        UpperCase = StringCase.UpperCase
  54.  
  55.        ''' <summary>
  56.        ''' Changes the first characters to upper-case,
  57.        ''' and the rest of characters to lower-case.
  58.        ''' <para></para>
  59.        '''
  60.        ''' [Example]
  61.        ''' <para></para>
  62.        ''' Input : abcdef
  63.        ''' <para></para>
  64.        ''' Output: Abcdef
  65.        ''' </summary>
  66.        TitleCase = StringCase.TitleCase
  67.  
  68.        ''' <summary>
  69.        ''' Mixed-case with first character to lower-case.
  70.        ''' <para></para>
  71.        '''
  72.        ''' [Example]
  73.        ''' <para></para>
  74.        ''' Input : ab cd ef
  75.        ''' <para></para>
  76.        ''' Output: aB Cd eF
  77.        ''' </summary>
  78.        MixedTitleCaseLower = StringCase.MixedTitleCaseLower
  79.  
  80.        ''' <summary>
  81.        ''' Mixed-case with first character to upper-case.
  82.        ''' <para></para>
  83.        '''
  84.        ''' [Example]
  85.        ''' <para></para>
  86.        ''' Input : ab cd ef
  87.        ''' <para></para>
  88.        ''' Output: Ab cD Ef
  89.        ''' </summary>
  90.        MixedTitleCaseUpper = StringCase.MixedTitleCaseUpper
  91.  
  92.        ''' <summary>
  93.        ''' Toggle-case.
  94.        ''' <para></para>
  95.        '''
  96.        ''' [Example]
  97.        ''' <para></para>
  98.        ''' Input : abc def ghi
  99.        ''' <para></para>
  100.        ''' Output: aBC dEF gHI
  101.        ''' </summary>
  102.        ToggleCase = StringCase.ToggleCase
  103.  
  104.        ''' <summary>
  105.        ''' Alternates any lower-case character to upper-case and vice versa.
  106.        ''' <para></para>
  107.        '''
  108.        ''' [Example]
  109.        ''' <para></para>
  110.        ''' Input : Hello World!
  111.        ''' <para></para>
  112.        ''' Output: hELLO wORLD!
  113.        ''' </summary>
  114.        AlternateChars = StringCase.AlternateChars
  115.  
  116.    End Enum
  117.  
  118. End Namespace
  119.  
  120. #End Region
  121.  

StringCase.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 26-October-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " String Case "
  15.  
  16. ' ReSharper disable once CheckNamespace
  17.  
  18. Namespace DevCase.Core.DataProcessing.Common
  19.  
  20.    ''' ----------------------------------------------------------------------------------------------------
  21.    ''' <summary>
  22.    ''' Specifies a string case.
  23.    ''' </summary>
  24.    ''' ----------------------------------------------------------------------------------------------------
  25.    Public Enum StringCase As Integer
  26.  
  27.        ''' <summary>
  28.        ''' LowerCase
  29.        ''' <para></para>
  30.        '''
  31.        ''' [Example]
  32.        ''' <para></para>
  33.        ''' Input : ABCDEF
  34.        ''' <para></para>
  35.        ''' Output: abcdef
  36.        ''' </summary>
  37.        LowerCase = &H0
  38.  
  39.        ''' <summary>
  40.        ''' UpperCase.
  41.        ''' <para></para>
  42.        '''
  43.        ''' [Example]
  44.        ''' <para></para>
  45.        ''' Input : abcdef
  46.        ''' <para></para>
  47.        ''' Output: ABCDEF
  48.        ''' </summary>
  49.        UpperCase = &H1
  50.  
  51.        ''' <summary>
  52.        ''' TitleCase.
  53.        ''' <para></para>
  54.        '''
  55.        ''' [Example]
  56.        ''' <para></para>
  57.        ''' Input : abcdef
  58.        ''' <para></para>
  59.        ''' Output: Abcdef
  60.        ''' </summary>
  61.        TitleCase = &H2
  62.  
  63.        ''' <summary>
  64.        ''' WordCase.
  65.        ''' <para></para>
  66.        '''
  67.        ''' [Example]
  68.        ''' <para></para>
  69.        ''' Input : abc def
  70.        ''' <para></para>
  71.        ''' Output: Abc Def
  72.        ''' </summary>
  73.        WordCase = &H3
  74.  
  75.        ''' <summary>
  76.        ''' CamelCase (With first letter to LowerCase).
  77.        ''' <para></para>
  78.        '''
  79.        ''' [Example]
  80.        ''' <para></para>
  81.        ''' Input : ABC DEF
  82.        ''' <para></para>
  83.        ''' Output: abcDef
  84.        ''' </summary>
  85.        CamelCaseLower = &H4
  86.  
  87.        ''' <summary>
  88.        ''' CamelCase (With first letter to UpperCase).
  89.        ''' <para></para>
  90.        '''
  91.        ''' [Example]
  92.        ''' <para></para>
  93.        ''' Input : ABC DEF
  94.        ''' <para></para>
  95.        ''' Output: AbcDef
  96.        ''' </summary>
  97.        CamelCaseUpper = &H5
  98.  
  99.        ''' <summary>
  100.        ''' MixedCase (With first letter to LowerCase).
  101.        ''' <para></para>
  102.        '''
  103.        ''' [Example]
  104.        ''' <para></para>
  105.        ''' Input : ab cd ef
  106.        ''' <para></para>
  107.        ''' Output: aB Cd eF
  108.        ''' </summary>
  109.        MixedTitleCaseLower = &H6
  110.  
  111.        ''' <summary>
  112.        ''' MixedCase (With first letter to UpperCase).
  113.        ''' <para></para>
  114.        '''
  115.        ''' [Example]
  116.        ''' <para></para>
  117.        ''' Input : ab cd ef
  118.        ''' <para></para>
  119.        ''' Output: Ab cD Ef
  120.        ''' </summary>
  121.        MixedTitleCaseUpper = &H7
  122.  
  123.        ''' <summary>
  124.        ''' MixedCase (With first letter of each word to LowerCase).
  125.        ''' <para></para>
  126.        '''
  127.        ''' [Example]
  128.        ''' <para></para>
  129.        ''' Input : ab cd ef
  130.        ''' <para></para>
  131.        ''' Output: aB cD eF
  132.        ''' </summary>
  133.        MixedWordCaseLower = &H8
  134.  
  135.        ''' <summary>
  136.        ''' MixedCase (With first letter of each word to UpperCase).
  137.        ''' <para></para>
  138.        '''
  139.        ''' [Example]
  140.        ''' <para></para>
  141.        ''' Input : ab cd ef
  142.        ''' <para></para>
  143.        ''' Output: Ab Cd Ef
  144.        ''' </summary>
  145.        MixedWordCaseUpper = &H9
  146.  
  147.        ''' <summary>
  148.        ''' ToggleCase.
  149.        ''' <para></para>
  150.        '''
  151.        ''' [Example]
  152.        ''' <para></para>
  153.        ''' Input : abc def ghi
  154.        ''' <para></para>
  155.        ''' Output: aBC dEF gHI
  156.        ''' </summary>
  157.        ToggleCase = &H10
  158.  
  159.        ''' <summary>
  160.        ''' Duplicates the characters.
  161.        ''' <para></para>
  162.        '''
  163.        ''' [Example]
  164.        ''' <para></para>
  165.        ''' Input : Hello World!
  166.        ''' <para></para>
  167.        ''' Output: HHeelllloo  WWoorrlldd!!
  168.        ''' </summary>
  169.        DuplicateChars = &H11
  170.  
  171.        ''' <summary>
  172.        ''' Alternates the characters.
  173.        ''' <para></para>
  174.        '''
  175.        ''' [Example]
  176.        ''' <para></para>
  177.        ''' Input : Hello World!
  178.        ''' <para></para>
  179.        ''' Output: hELLO wORLD!
  180.        ''' </summary>
  181.        AlternateChars = &H12
  182.  
  183.    End Enum
  184.  
  185. End Namespace
  186.  
  187. #End Region
  188.  



StringExtensions.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 13-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' String.Rename(StringCase) As String
  9.  
  10. #End Region
  11.  
  12. #Region " Option Statements "
  13.  
  14. Option Strict On
  15. Option Explicit On
  16. Option Infer Off
  17.  
  18. #End Region
  19.  
  20. #Region " Imports "
  21.  
  22. Imports System.ComponentModel
  23. Imports System.Globalization
  24. Imports System.Runtime.CompilerServices
  25.  
  26. Imports DevCase.Core.DataProcessing.Common
  27.  
  28. #End Region
  29.  
  30. #Region " String Extensions "
  31.  
  32. ' ReSharper disable once CheckNamespace
  33.  
  34. Namespace DevCase.Extensions.StringExtensions
  35.  
  36.    ''' ----------------------------------------------------------------------------------------------------
  37.    ''' <summary>
  38.    ''' Contains custom extension methods to use with a <see cref="String"/> type.
  39.    ''' </summary>
  40.    ''' ----------------------------------------------------------------------------------------------------
  41.    <HideModuleName>
  42.    Public Module StringExtensions
  43.  
  44. #Region " Public Extension Methods "
  45.  
  46.        ''' ----------------------------------------------------------------------------------------------------
  47.        ''' <summary>
  48.        ''' Renames a string to the specified StringCase.
  49.        ''' </summary>
  50.        ''' ----------------------------------------------------------------------------------------------------
  51.        ''' <example> This is a code example.
  52.        ''' <code language="VB.NET">
  53.        ''' Dim str As String = "Hello World".Rename(StringCase.UpperCase)
  54.        '''
  55.        ''' MessageBox.Show(str)
  56.        ''' </code>
  57.        ''' </example>
  58.        ''' ----------------------------------------------------------------------------------------------------
  59.        ''' <param name="sender">
  60.        ''' The source <see cref="String"/>.
  61.        ''' </param>
  62.        '''
  63.        ''' <param name="stringCase">
  64.        ''' The <see cref="StringCase"/>.
  65.        ''' </param>
  66.        ''' ----------------------------------------------------------------------------------------------------
  67.        ''' <returns>
  68.        ''' The renamed string.
  69.        ''' </returns>
  70.        ''' ----------------------------------------------------------------------------------------------------
  71.        <DebuggerStepThrough>
  72.        <Extension>
  73.        <EditorBrowsable(EditorBrowsableState.Always)>
  74.        Public Function Rename(sender As String,
  75.                               stringCase As StringCase) As String
  76.  
  77.            Select Case stringCase
  78.  
  79.                Case StringCase.LowerCase
  80.                    Return sender.ToLower
  81.  
  82.                Case StringCase.UpperCase
  83.                    Return sender.ToUpper
  84.  
  85.                Case StringCase.TitleCase
  86.                    Return $"{Char.ToUpper(sender.First())}{sender.Remove(0, 1).ToLower()}"
  87.  
  88.                Case StringCase.WordCase
  89.                    Return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(sender.ToLower())
  90.  
  91.                Case StringCase.CamelCaseLower
  92.                    Return _
  93.                        $"{Char.ToLower(sender.First())}{ _
  94.                            CultureInfo.InvariantCulture.TextInfo.ToTitleCase(sender.ToLower()).
  95.                                Replace(" "c, String.Empty).
  96.                                Remove(0, 1)}"
  97.  
  98.                Case StringCase.CamelCaseUpper
  99.                    Return _
  100.                        $"{Char.ToUpper(sender.First())}{ _
  101.                            CultureInfo.InvariantCulture.TextInfo.ToTitleCase(sender.ToLower()).
  102.                                Replace(" "c, String.Empty).
  103.                                Remove(0, 1)}"
  104.  
  105.                Case StringCase.MixedTitleCaseLower
  106.                    Dim sb As New Global.System.Text.StringBuilder
  107.                    For i As Integer = 0 To sender.Length - 1 Step 2
  108.                        If Not (i + 1) >= sender.Length Then
  109.                            sb.AppendFormat("{0}{1}", Char.ToLower(sender(i)), Char.ToUpper(sender(i + 1)))
  110.                        Else
  111.                            sb.Append(Char.ToLower(sender(i)))
  112.                        End If
  113.                    Next i
  114.                    Return sb.ToString()
  115.  
  116.                Case StringCase.MixedTitleCaseUpper
  117.                    Dim sb As New Global.System.Text.StringBuilder
  118.                    For i As Integer = 0 To sender.Length - 1 Step 2
  119.                        If Not (i + 1) >= sender.Length Then
  120.                            sb.AppendFormat("{0}{1}", Char.ToUpper(sender(i)), Char.ToLower(sender(i + 1)))
  121.                        Else
  122.                            sb.Append(Char.ToUpper(sender(i)))
  123.                        End If
  124.                    Next i
  125.                    Return sb.ToString()
  126.  
  127.                Case StringCase.MixedWordCaseLower
  128.                    Dim sb As New Global.System.Text.StringBuilder
  129.                    For Each word As String In sender.Split
  130.                        sb.AppendFormat("{0} ", Rename(word, StringCase.MixedTitleCaseLower))
  131.                    Next word
  132.                    Return sb.ToString()
  133.  
  134.                Case StringCase.MixedWordCaseUpper
  135.                    Dim sb As New Global.System.Text.StringBuilder
  136.                    For Each word As String In sender.Split
  137.                        sb.AppendFormat("{0} ", Rename(word, StringCase.MixedTitleCaseUpper))
  138.                    Next word
  139.                    Return sb.ToString()
  140.  
  141.                Case StringCase.ToggleCase
  142.                    Dim sb As New Global.System.Text.StringBuilder
  143.                    For Each word As String In sender.Split
  144.                        sb.AppendFormat("{0}{1} ", Char.ToLower(word.First()), word.Remove(0, 1).ToUpper)
  145.                    Next word
  146.                    Return sb.ToString()
  147.  
  148.                Case StringCase.DuplicateChars
  149.                    Dim sb As New Global.System.Text.StringBuilder
  150.                    For Each c As Char In sender
  151.                        sb.Append(New String(c, 2))
  152.                    Next c
  153.                    Return sb.ToString()
  154.  
  155.                Case StringCase.AlternateChars
  156.                    Dim sb As New Global.System.Text.StringBuilder
  157.                    For Each c As Char In sender
  158.                        Select Case Char.IsLower(c)
  159.                            Case True
  160.                                sb.Append(Char.ToUpper(c))
  161.                            Case Else
  162.                                sb.Append(Char.ToLower(c))
  163.                        End Select
  164.                    Next c
  165.                    Return sb.ToString()
  166.  
  167.                Case Else
  168.                    Return sender
  169.  
  170.            End Select
  171.  
  172.        End Function
  173.  
  174. #End Region
  175.  
  176.    End Module
  177.  
  178. End Namespace
  179.  
  180. #End Region
  181.  
En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #554 en: 10 Septiembre 2023, 08:02 am »

Aquí les dejo varias funciones para enmascarar un String.

Este código permite enmascarar de izquierda a derecha o de derecha a izquierda, todo el string o de forma parcial especificando la longitud de máscara, y el símbolo de máscara es personalizable. Además, permite especificar caracteres que se deban ignorar / no deban ser enmascarados.

Por ejemplo, si tenemos el string "PASSWORD", podemos enmascararlo completamente:
Código:
********

O parcialmente de izquierda a derecha:
Código:
****WORD

O parcialmente de derecha a izquierda:
Código:
PASS****

O de forma selectiva podemos crear una máscara completa o parial, e ignorar las letras "S" y "W" de la máscara:
Código:
**SSW***



Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 12-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' MaskString(String, Opt: Char) As String
  11. ' MaskString(String, Char(), Opt: Char) As String
  12. ' MaskString(String, Integer, Boolean, Opt: Char) As String
  13. ' MaskString(String, Integer, Boolean, Char(), Opt: Char) As String
  14.  
  15. #End Region
  16.  
  17. #End Region
  18.  
  19. #Region " Option Statements "
  20.  
  21. Option Strict On
  22. Option Explicit On
  23. Option Infer Off
  24.  
  25. #End Region
  26.  
  27. #Region " Imports "
  28.  
  29. Imports System.Text
  30. Imports System.Security
  31. Imports System.ComponentModel
  32. Imports System.Runtime.InteropServices
  33. Imports System.Collections.Generic
  34. Imports System.Linq
  35.  
  36. #End Region
  37.  
  38. #Region " UtilPasswords "
  39.  
  40. ' ReSharper disable once CheckNamespace
  41.  
  42. Namespace DevCase.Core.Security.Passwords
  43.  
  44.    Public NotInheritable Class UtilPasswords
  45.  
  46. #Region " Public Methods "
  47.  
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        ''' <summary>
  50.        ''' Masks the source string with a specific character.
  51.        ''' </summary>
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        ''' <example> This is a code example.
  54.        ''' <code language="VB.NET">
  55.        ''' Dim password As String = "This is a password"
  56.        ''' Dim maskChar As Char = "*"c
  57.        ''' Dim masked As String = MaskString(password, maskChar)
  58.        ''' Console.WriteLine(masked)
  59.        ''' </code>
  60.        ''' </example>
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        ''' <param name="input">
  63.        ''' The string to mask.
  64.        ''' </param>
  65.        '''
  66.        ''' <param name="maskCharacter">
  67.        ''' Optional. The character used for masking (default: "*").
  68.        ''' </param>
  69.        ''' ----------------------------------------------------------------------------------------------------
  70.        ''' <returns>
  71.        ''' The masked string.
  72.        ''' </returns>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        <DebuggerStepperBoundary>
  75.        Public Shared Function MaskString(input As String, Optional maskCharacter As Char = "*"c) As String
  76.  
  77.            Return MaskString(input, maskLength:=input.Length, leftToRight:=True, allowedChars:=Nothing, maskCharacter)
  78.  
  79.        End Function
  80.  
  81.        ''' ----------------------------------------------------------------------------------------------------
  82.        ''' <summary>
  83.        ''' Masks the source string with a specific character,
  84.        ''' allowing certain characters to remain unmasked.
  85.        ''' </summary>
  86.        ''' ----------------------------------------------------------------------------------------------------
  87.        ''' <example> This is a code example.
  88.        ''' <code language="VB.NET">
  89.        ''' Dim serialKey As String = "123-456-789"
  90.        ''' Dim allowedChars As Char() = "-".ToCharArray()
  91.        ''' Dim maskChar As Char = "*"c
  92.        '''
  93.        ''' Dim masked As String = MaskString(serialKey, allowedChars, maskChar)
  94.        ''' Console.WriteLine(masked)
  95.        ''' </code>
  96.        ''' </example>
  97.        ''' ----------------------------------------------------------------------------------------------------
  98.        ''' <param name="input">
  99.        ''' The string to mask.
  100.        ''' </param>
  101.        '''
  102.        ''' <param name="allowedChars">
  103.        ''' An array of characters that are allowed to remain unmasked.
  104.        ''' </param>
  105.        '''
  106.        ''' <param name="maskCharacter">
  107.        ''' The character used for masking (default: "*").
  108.        ''' </param>
  109.        ''' ----------------------------------------------------------------------------------------------------
  110.        ''' <returns>
  111.        ''' The masked string.
  112.        ''' </returns>
  113.        ''' ----------------------------------------------------------------------------------------------------
  114.        <DebuggerStepperBoundary>
  115.        Public Shared Function MaskString(input As String, allowedChars As Char(), Optional maskCharacter As Char = "*"c) As String
  116.  
  117.            Return MaskString(input, maskLength:=input.Length, leftToRight:=True, allowedChars:=allowedChars, maskCharacter)
  118.  
  119.        End Function
  120.  
  121.        ''' ----------------------------------------------------------------------------------------------------
  122.        ''' <summary>
  123.        ''' Partially masks the source string with a specific character.
  124.        ''' </summary>
  125.        ''' ----------------------------------------------------------------------------------------------------
  126.        ''' <example> This is a code example.
  127.        ''' <code language="VB.NET">
  128.        ''' Dim serialKey As String = "123-456-789"
  129.        ''' Dim maskLength As Integer = 7
  130.        ''' Dim leftToRight As Boolean = True
  131.        ''' Dim maskChar As Char = "*"c
  132.        '''
  133.        ''' Dim masked As String = MaskString(serialKey, maskLength, leftToRight, maskChar)
  134.        ''' Console.WriteLine(masked)
  135.        ''' </code>
  136.        ''' </example>
  137.        ''' ----------------------------------------------------------------------------------------------------
  138.        ''' <param name="input">
  139.        ''' The string to mask.
  140.        ''' </param>
  141.        '''
  142.        ''' <param name="maskLength">
  143.        ''' The length of the mask.
  144.        ''' </param>
  145.        '''
  146.        ''' <param name="leftToRight">
  147.        ''' Indicates the direction of the mask (left to right or right to left).
  148.        ''' </param>
  149.        '''
  150.        ''' <param name="maskCharacter">
  151.        ''' The character used for masking (default: "*").
  152.        ''' </param>
  153.        ''' ----------------------------------------------------------------------------------------------------
  154.        ''' <returns>
  155.        ''' The masked string.
  156.        ''' </returns>
  157.        ''' ----------------------------------------------------------------------------------------------------
  158.        <DebuggerStepperBoundary>
  159.        Public Shared Function MaskString(input As String, maskLength As Integer, leftToRight As Boolean, Optional maskCharacter As Char = "*"c) As String
  160.  
  161.            Return MaskString(input, maskLength:=maskLength, leftToRight:=leftToRight, allowedChars:=Nothing, maskCharacter)
  162.  
  163.        End Function
  164.  
  165.        ''' ----------------------------------------------------------------------------------------------------
  166.        ''' <summary>
  167.        ''' Partially masks the source string with a specific character,
  168.        ''' allowing certain characters to remain unmasked.
  169.        ''' </summary>
  170.        ''' ----------------------------------------------------------------------------------------------------
  171.        ''' <example> This is a code example.
  172.        ''' <code language="VB.NET">
  173.        ''' Dim serialKey As String = "123-456-789"
  174.        ''' Dim maskLength As Integer = 7
  175.        ''' Dim leftToRight As Boolean = True
  176.        ''' Dim allowedChars As Char() = "-".ToCharArray()
  177.        ''' Dim maskChar As Char = "*"c
  178.        '''
  179.        ''' Dim masked As String = MaskString(serialKey, maskLength, leftToRight, allowedChars, maskChar)
  180.        ''' Console.WriteLine(masked)
  181.        ''' </code>
  182.        ''' </example>
  183.        ''' ----------------------------------------------------------------------------------------------------
  184.        ''' <param name="input">
  185.        ''' The string to mask.
  186.        ''' </param>
  187.        '''
  188.        ''' <param name="maskLength">
  189.        ''' The length of the mask.
  190.        ''' </param>
  191.        '''
  192.        ''' <param name="leftToRight">
  193.        ''' Indicates the direction of the mask (left to right or right to left).
  194.        ''' </param>
  195.        '''
  196.        ''' <param name="allowedChars">
  197.        ''' An array of characters that are allowed to remain unmasked.
  198.        ''' </param>
  199.        '''
  200.        ''' <param name="maskCharacter">
  201.        ''' The character used for masking (default: "*").
  202.        ''' </param>
  203.        ''' ----------------------------------------------------------------------------------------------------
  204.        ''' <returns>
  205.        ''' The masked string.
  206.        ''' </returns>
  207.        ''' ----------------------------------------------------------------------------------------------------
  208.        <DebuggerStepperBoundary>
  209.        Public Shared Function MaskString(input As String, maskLength As Integer, leftToRight As Boolean, allowedChars As Char(), Optional maskCharacter As Char = "*"c) As String
  210.  
  211.            If String.IsNullOrEmpty(input) Then
  212.                Throw New ArgumentNullException(paramName:=NameOf(input))
  213.            End If
  214.  
  215.            If String.IsNullOrEmpty(maskCharacter) Then
  216.                Throw New ArgumentNullException(paramName:=NameOf(maskCharacter))
  217.            End If
  218.  
  219.            If maskLength <= 0 Then
  220.                Throw New ArgumentException($"maskLength must be greather than zero.", paramName:=NameOf(maskLength))
  221.            End If
  222.  
  223.            Dim valueLength As Integer = input.Length
  224.            If maskLength > valueLength Then
  225.                Throw New ArgumentException($"maskLength can't be greather than the source string length.", paramName:=NameOf(maskLength))
  226.            End If
  227.  
  228.            Dim allowedCharIndices As IDictionary(Of Integer, Char) = Nothing
  229.            If allowedChars IsNot Nothing AndAlso allowedChars.Length > 0 Then
  230.                allowedCharIndices = New Dictionary(Of Integer, Char)
  231.                Dim startPos As Integer
  232.                Dim endPos As Integer
  233.  
  234.                If maskLength = valueLength Then ' Full mask.
  235.                    startPos = 0
  236.                    endPos = valueLength - 1
  237.                Else
  238.                    If leftToRight Then ' Left to right mask.
  239.                        startPos = 0
  240.                        endPos = maskLength - 1
  241.                    Else ' Right to left mask.
  242.                        startPos = valueLength - maskLength
  243.                        endPos = valueLength - 1
  244.                    End If
  245.                End If
  246.  
  247.                For i As Integer = startPos To endPos
  248.                    Dim c As Char = input(i)
  249.                    If allowedChars.Contains(c) Then
  250.                        allowedCharIndices.Add(i, c)
  251.                    End If
  252.                Next
  253.            End If
  254.  
  255.            Dim sb As New StringBuilder(valueLength, valueLength)
  256.            If maskLength = valueLength Then ' Full mask.
  257.                sb.Append(maskCharacter, maskLength)
  258.            Else
  259.                If leftToRight Then ' Left to right mask.
  260.                    sb.Append(maskCharacter, maskLength)
  261.                    sb.Append(input.Substring(maskLength))
  262.                Else ' Right to left mask.
  263.                    sb.Append(input.Substring(0, valueLength - maskLength))
  264.                    sb.Append(maskCharacter, maskLength)
  265.                End If
  266.            End If
  267.  
  268.            If allowedCharIndices IsNot Nothing Then
  269.                For Each pair As KeyValuePair(Of Integer, Char) In allowedCharIndices
  270.                    sb.Chars(pair.Key) = pair.Value
  271.                Next
  272.            End If
  273.  
  274.            Return sb.ToString()
  275.        End Function
  276.  
« Última modificación: 10 Septiembre 2023, 08:09 am por Elektro Enjuto » En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #555 en: 10 Septiembre 2023, 08:08 am »

Lo mismo de antes pero para un objeto de tipo SecureString:

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 12-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' MaskSecureString(String, Opt: Char) As SecureString
  11. ' MaskSecureString(String, Char(), Opt: Char) As SecureString
  12. ' MaskSecureString(String, Integer, Boolean, Opt: Char) As SecureString
  13. ' MaskSecureString(String, Integer, Boolean, Char(), Opt: Char) As SecureString
  14.  
  15. ' MaskSecureString(SecureString, Opt: Char) As SecureString
  16. ' MaskSecureString(SecureString, Char(), Opt: Char) As SecureString
  17. ' MaskSecureString(SecureString, Integer, Boolean, Opt: Char) As SecureString
  18. ' MaskSecureString(SecureString, Integer, Boolean, Char(), Opt: Char) As SecureString
  19.  
  20. #End Region
  21.  
  22. #End Region
  23.  
  24. #Region " Option Statements "
  25.  
  26. Option Strict On
  27. Option Explicit On
  28. Option Infer Off
  29.  
  30. #End Region
  31.  
  32. #Region " Imports "
  33.  
  34. Imports System.Text
  35. Imports System.Security
  36. Imports System.ComponentModel
  37. Imports System.Runtime.InteropServices
  38. Imports System.Collections.Generic
  39. Imports System.Linq
  40.  
  41. #End Region
  42.  
  43. #Region " UtilPasswords "
  44.  
  45. ' ReSharper disable once CheckNamespace
  46.  
  47. Namespace DevCase.Core.Security.Passwords
  48.  
  49.    Public NotInheritable Class UtilPasswords
  50.  
  51. #Region " Public Methods "
  52.  
  53.        ''' ----------------------------------------------------------------------------------------------------
  54.        ''' <summary>
  55.        ''' Masks the source string with a specific character.
  56.        ''' </summary>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <example> This is a code example.
  59.        ''' <code language="VB.NET">
  60.        ''' Dim password As String = "This is a password"
  61.        ''' Dim maskChar As Char = "*"c
  62.        '''
  63.        ''' Dim masked As SecureString = MaskSecureString(password, maskChar)
  64.        ''' </code>
  65.        ''' </example>
  66.        ''' ----------------------------------------------------------------------------------------------------
  67.        ''' <param name="input">
  68.        ''' The string to mask.
  69.        ''' </param>
  70.        '''
  71.        ''' <param name="maskCharacter">
  72.        ''' Optional. The character used for masking (default: "*").
  73.        ''' </param>
  74.        ''' ----------------------------------------------------------------------------------------------------
  75.        ''' <returns>
  76.        ''' The masked string.
  77.        ''' </returns>
  78.        ''' ----------------------------------------------------------------------------------------------------
  79.        <DebuggerStepperBoundary>
  80.        Public Shared Function MaskSecureString(input As String, Optional maskCharacter As Char = "*"c) As SecureString
  81.  
  82.            Return MaskSecureString(input, maskLength:=input.Length, leftToRight:=True, allowedChars:=Nothing, maskCharacter)
  83.  
  84.        End Function
  85.  
  86.        ''' ----------------------------------------------------------------------------------------------------
  87.        ''' <summary>
  88.        ''' Masks the source string with a specific character,
  89.        ''' allowing certain characters to remain unmasked.
  90.        ''' </summary>
  91.        ''' ----------------------------------------------------------------------------------------------------
  92.        ''' <example> This is a code example.
  93.        ''' <code language="VB.NET">
  94.        ''' Dim serialKey As String = "123-456-789"
  95.        ''' Dim allowedChars As Char() = "-".ToCharArray()
  96.        ''' Dim maskChar As Char = "*"c
  97.        '''
  98.        ''' Dim masked As SecureString = MaskSecureString(serialKey, allowedChars, maskChar)
  99.        ''' </code>
  100.        ''' </example>
  101.        ''' ----------------------------------------------------------------------------------------------------
  102.        ''' <param name="input">
  103.        ''' The string to mask.
  104.        ''' </param>
  105.        '''
  106.        ''' <param name="allowedChars">
  107.        ''' An array of characters that are allowed to remain unmasked.
  108.        ''' </param>
  109.        '''
  110.        ''' <param name="maskCharacter">
  111.        ''' The character used for masking (default: "*").
  112.        ''' </param>
  113.        ''' ----------------------------------------------------------------------------------------------------
  114.        ''' <returns>
  115.        ''' The masked string.
  116.        ''' </returns>
  117.        ''' ----------------------------------------------------------------------------------------------------
  118.        <DebuggerStepperBoundary>
  119.        Public Shared Function MaskSecureString(input As String, allowedChars As Char(), Optional maskCharacter As Char = "*"c) As SecureString
  120.  
  121.            Return MaskSecureString(input, maskLength:=input.Length, leftToRight:=True, allowedChars:=allowedChars, maskCharacter)
  122.  
  123.        End Function
  124.  
  125.        ''' ----------------------------------------------------------------------------------------------------
  126.        ''' <summary>
  127.        ''' Partially masks the source string with a specific character.
  128.        ''' </summary>
  129.        ''' ----------------------------------------------------------------------------------------------------
  130.        ''' <example> This is a code example.
  131.        ''' <code language="VB.NET">
  132.        ''' Dim serialKey As String = "123-456-789"
  133.        ''' Dim maskLength As Integer = 7
  134.        ''' Dim leftToRight As Boolean = True
  135.        ''' Dim maskChar As Char = "*"c
  136.        '''
  137.        ''' Dim masked As SecureString = MaskSecureString(serialKey, maskLength, leftToRight, maskChar)
  138.        ''' </code>
  139.        ''' </example>
  140.        ''' ----------------------------------------------------------------------------------------------------
  141.        ''' <param name="input">
  142.        ''' The string to mask.
  143.        ''' </param>
  144.        '''
  145.        ''' <param name="maskLength">
  146.        ''' The length of the mask.
  147.        ''' </param>
  148.        '''
  149.        ''' <param name="leftToRight">
  150.        ''' Indicates the direction of the mask (left to right or right to left).
  151.        ''' </param>
  152.        '''
  153.        ''' <param name="maskCharacter">
  154.        ''' The character used for masking (default: "*").
  155.        ''' </param>
  156.        ''' ----------------------------------------------------------------------------------------------------
  157.        ''' <returns>
  158.        ''' The masked string.
  159.        ''' </returns>
  160.        ''' ----------------------------------------------------------------------------------------------------
  161.        <DebuggerStepperBoundary>
  162.        Public Shared Function MaskSecureString(input As String, maskLength As Integer, leftToRight As Boolean, Optional maskCharacter As Char = "*"c) As SecureString
  163.  
  164.            Return MaskSecureString(input, maskLength:=maskLength, leftToRight:=leftToRight, allowedChars:=Nothing, maskCharacter)
  165.  
  166.        End Function
  167.  
  168.        ''' ----------------------------------------------------------------------------------------------------
  169.        ''' <summary>
  170.        ''' Partially masks the source string with a specific character,
  171.        ''' allowing certain characters to remain unmasked.
  172.        ''' </summary>
  173.        ''' ----------------------------------------------------------------------------------------------------
  174.        ''' <example> This is a code example.
  175.        ''' <code language="VB.NET">
  176.        ''' Dim serialKey As String = "123-456-789"
  177.        ''' Dim maskLength As Integer = 7
  178.        ''' Dim leftToRight As Boolean = True
  179.        ''' Dim allowedChars As Char() = "-".ToCharArray()
  180.        ''' Dim maskChar As Char = "*"c
  181.        '''
  182.        ''' Dim masked As SecureString = MaskSecureString(serialKey, maskLength, leftToRight, allowedChars, maskChar)
  183.        ''' </code>
  184.        ''' </example>
  185.        ''' ----------------------------------------------------------------------------------------------------
  186.        ''' <param name="input">
  187.        ''' The string to mask.
  188.        ''' </param>
  189.        '''
  190.        ''' <param name="maskLength">
  191.        ''' The length of the mask.
  192.        ''' </param>
  193.        '''
  194.        ''' <param name="leftToRight">
  195.        ''' Indicates the direction of the mask (left to right or right to left).
  196.        ''' </param>
  197.        '''
  198.        ''' <param name="allowedChars">
  199.        ''' An array of characters that are allowed to remain unmasked.
  200.        ''' </param>
  201.        '''
  202.        ''' <param name="maskCharacter">
  203.        ''' The character used for masking (default: "*").
  204.        ''' </param>
  205.        ''' ----------------------------------------------------------------------------------------------------
  206.        ''' <returns>
  207.        ''' The masked string.
  208.        ''' </returns>
  209.        ''' ----------------------------------------------------------------------------------------------------
  210.        <DebuggerStepperBoundary>
  211.        Public Shared Function MaskSecureString(input As String, maskLength As Integer, leftToRight As Boolean, allowedChars As Char(), Optional maskCharacter As Char = "*"c) As SecureString
  212.  
  213.            If String.IsNullOrEmpty(input) Then
  214.                Throw New ArgumentNullException(paramName:=NameOf(input))
  215.            End If
  216.  
  217.            If String.IsNullOrEmpty(maskCharacter) Then
  218.                Throw New ArgumentNullException(paramName:=NameOf(maskCharacter))
  219.            End If
  220.  
  221.            If maskLength <= 0 Then
  222.                Throw New ArgumentException($"maskLength must be greather than zero.", paramName:=NameOf(maskLength))
  223.            End If
  224.  
  225.            Dim valueLength As Integer = input.Length
  226.            If maskLength > valueLength Then
  227.                Throw New ArgumentException($"maskLength can't be greather than the source string length.", paramName:=NameOf(maskLength))
  228.            End If
  229.  
  230.            Dim allowedCharIndices As IDictionary(Of Integer, Char) = Nothing
  231.            If allowedChars IsNot Nothing AndAlso allowedChars.Length > 0 Then
  232.                allowedCharIndices = New Dictionary(Of Integer, Char)
  233.                Dim startPos As Integer
  234.                Dim endPos As Integer
  235.  
  236.                If maskLength = valueLength Then ' Full mask.
  237.                    startPos = 0
  238.                    endPos = valueLength - 1
  239.                Else
  240.                    If leftToRight Then ' Left to right mask.
  241.                        startPos = 0
  242.                        endPos = maskLength - 1
  243.                    Else ' Right to left mask.
  244.                        startPos = valueLength - maskLength
  245.                        endPos = valueLength - 1
  246.                    End If
  247.                End If
  248.  
  249.                For i As Integer = startPos To endPos
  250.                    Dim c As Char = input(i)
  251.                    If allowedChars.Contains(c) Then
  252.                        allowedCharIndices.Add(i, c)
  253.                    End If
  254.                Next
  255.            End If
  256.  
  257.            Dim sec As New SecureString()
  258.            If maskLength = valueLength Then ' Full mask.
  259.                For i As Integer = 0 To valueLength
  260.                    Dim dictValue As Char = Nothing
  261.                    If allowedCharIndices IsNot Nothing AndAlso allowedCharIndices.TryGetValue(i, dictValue) Then
  262.                        sec.AppendChar(dictValue)
  263.                        Continue For
  264.                    End If
  265.                    sec.AppendChar(maskCharacter)
  266.                Next
  267.  
  268.            Else
  269.                If leftToRight Then ' Left to right mask.
  270.                    For i As Integer = 0 To maskLength - 1
  271.                        Dim dictValue As Char = Nothing
  272.                        If allowedCharIndices IsNot Nothing AndAlso allowedCharIndices.TryGetValue(i, dictValue) Then
  273.                            sec.AppendChar(dictValue)
  274.                            Continue For
  275.                        End If
  276.                        sec.AppendChar(maskCharacter)
  277.                    Next
  278.                    For i As Integer = maskLength To valueLength - 1
  279.                        sec.AppendChar(input(i))
  280.                    Next
  281.                Else ' Right to left mask.
  282.                    For i As Integer = 0 To valueLength - maskLength - 1
  283.                        sec.AppendChar(input(i))
  284.                    Next
  285.                    For i As Integer = valueLength - maskLength To valueLength - 1
  286.                        Dim dictValue As Char = Nothing
  287.                        If allowedCharIndices IsNot Nothing AndAlso allowedCharIndices.TryGetValue(i, dictValue) Then
  288.                            sec.AppendChar(dictValue)
  289.                            Continue For
  290.                        End If
  291.                        sec.AppendChar(maskCharacter)
  292.                    Next
  293.                End If
  294.            End If
  295.  
  296.            Return sec
  297.        End Function
  298.  
  299.        ''' ----------------------------------------------------------------------------------------------------
  300.        ''' <summary>
  301.        ''' Masks the source string with a specific character.
  302.        ''' </summary>
  303.        ''' ----------------------------------------------------------------------------------------------------
  304.        ''' <example> This is a code example.
  305.        ''' <code language="VB.NET">
  306.        ''' Dim secureStr As New SecureString()
  307.        ''' With secureStr
  308.        '''     .AppendChar("p"c)
  309.        '''     .AppendChar("a"c)
  310.        '''     .AppendChar("s"c)
  311.        '''     .AppendChar("s"c)
  312.        '''     .AppendChar("w"c)
  313.        '''     .AppendChar("o"c)
  314.        '''     .AppendChar("r"c)
  315.        '''     .AppendChar("d"c)
  316.        ''' End With
  317.        '''
  318.        ''' Dim maskChar As Char = "*"c
  319.        ''' Dim masked As SecureString = MaskSecureString(secureStr, maskChar)
  320.        ''' </code>
  321.        ''' </example>
  322.        ''' ----------------------------------------------------------------------------------------------------
  323.        ''' <param name="value">
  324.        ''' The string to mask.
  325.        ''' </param>
  326.        '''
  327.        ''' <param name="maskCharacter">
  328.        ''' Optional. The character used for masking (default: "*").
  329.        ''' </param>
  330.        ''' ----------------------------------------------------------------------------------------------------
  331.        ''' <returns>
  332.        ''' The masked string.
  333.        ''' </returns>
  334.        ''' ----------------------------------------------------------------------------------------------------
  335.        <DebuggerStepperBoundary>
  336.        Public Shared Function MaskSecureString(value As SecureString, Optional maskCharacter As Char = "*"c) As SecureString
  337.  
  338.            Return MaskSecureString(value, maskLength:=value.Length, leftToRight:=True, allowedChars:=Nothing, maskCharacter)
  339.  
  340.        End Function
  341.  
  342.        ''' ----------------------------------------------------------------------------------------------------
  343.        ''' <summary>
  344.        ''' Masks the source string with a specific character,
  345.        ''' allowing certain characters to remain unmasked.
  346.        ''' </summary>
  347.        ''' ----------------------------------------------------------------------------------------------------
  348.        ''' <example> This is a code example.
  349.        ''' <code language="VB.NET">
  350.        ''' Dim serialKey As New SecureString()
  351.        ''' With serialKey
  352.        '''     .AppendChar("1"c)
  353.        '''     .AppendChar("2"c)
  354.        '''     .AppendChar("3"c)
  355.        '''     .AppendChar("-"c)
  356.        '''     .AppendChar("4"c)
  357.        '''     .AppendChar("5"c)
  358.        '''     .AppendChar("6"c)
  359.        '''     .AppendChar("-"c)
  360.        '''     .AppendChar("7"c)
  361.        '''     .AppendChar("8"c)
  362.        '''     .AppendChar("9"c)
  363.        ''' End With
  364.        '''
  365.        ''' Dim allowedChars As Char() = "-".ToCharArray()
  366.        ''' Dim maskChar As Char = "*"c
  367.        '''
  368.        ''' Dim masked As SecureString = MaskSecureString(serialKey, allowedChars, maskChar)
  369.        ''' </code>
  370.        ''' </example>
  371.        ''' ----------------------------------------------------------------------------------------------------
  372.        ''' <param name="value">
  373.        ''' The string to mask.
  374.        ''' </param>
  375.        '''
  376.        ''' <param name="allowedChars">
  377.        ''' An array of characters that are allowed to remain unmasked.
  378.        ''' </param>
  379.        '''
  380.        ''' <param name="maskCharacter">
  381.        ''' The character used for masking (default: "*").
  382.        ''' </param>
  383.        ''' ----------------------------------------------------------------------------------------------------
  384.        ''' <returns>
  385.        ''' The masked string.
  386.        ''' </returns>
  387.        ''' ----------------------------------------------------------------------------------------------------
  388.        <DebuggerStepperBoundary>
  389.        Public Shared Function MaskSecureString(value As SecureString, allowedChars As Char(), Optional maskCharacter As Char = "*"c) As SecureString
  390.  
  391.            Return MaskSecureString(value, maskLength:=value.Length, leftToRight:=True, allowedChars:=allowedChars, maskCharacter)
  392.  
  393.        End Function
  394.  
  395.        ''' ----------------------------------------------------------------------------------------------------
  396.        ''' <summary>
  397.        ''' Partially masks the source string with a specific character.
  398.        ''' </summary>
  399.        ''' ----------------------------------------------------------------------------------------------------
  400.        ''' <example> This is a code example.
  401.        ''' <code language="VB.NET">
  402.        ''' Dim serialKey As New SecureString()
  403.        ''' With serialKey
  404.        '''     .AppendChar("1"c)
  405.        '''     .AppendChar("2"c)
  406.        '''     .AppendChar("3"c)
  407.        '''     .AppendChar("-"c)
  408.        '''     .AppendChar("4"c)
  409.        '''     .AppendChar("5"c)
  410.        '''     .AppendChar("6"c)
  411.        '''     .AppendChar("-"c)
  412.        '''     .AppendChar("7"c)
  413.        '''     .AppendChar("8"c)
  414.        '''     .AppendChar("9"c)
  415.        ''' End With
  416.        '''
  417.        ''' Dim maskLength As Integer = 7
  418.        ''' Dim leftToRight As Boolean = True
  419.        ''' Dim maskChar As Char = "*"c
  420.        '''
  421.        ''' Dim masked As SecureString = MaskSecureString(serialKey, maskLength, leftToRight, maskChar)
  422.        ''' </code>
  423.        ''' </example>
  424.        ''' ----------------------------------------------------------------------------------------------------
  425.        ''' <param name="value">
  426.        ''' The string to mask.
  427.        ''' </param>
  428.        '''
  429.        ''' <param name="maskLength">
  430.        ''' The length of the mask.
  431.        ''' </param>
  432.        '''
  433.        ''' <param name="leftToRight">
  434.        ''' Indicates the direction of the mask (left to right or right to left).
  435.        ''' </param>
  436.        '''
  437.        ''' <param name="maskCharacter">
  438.        ''' The character used for masking (default: "*").
  439.        ''' </param>
  440.        ''' ----------------------------------------------------------------------------------------------------
  441.        ''' <returns>
  442.        ''' The masked string.
  443.        ''' </returns>
  444.        ''' ----------------------------------------------------------------------------------------------------
  445.        <DebuggerStepperBoundary>
  446.        Public Shared Function MaskSecureString(value As SecureString, maskLength As Integer, leftToRight As Boolean, Optional maskCharacter As Char = "*"c) As SecureString
  447.  
  448.            Return MaskSecureString(value, maskLength:=maskLength, leftToRight:=leftToRight, allowedChars:=Nothing, maskCharacter)
  449.  
  450.        End Function
  451.  
  452.        ''' ----------------------------------------------------------------------------------------------------
  453.        ''' <summary>
  454.        ''' Partially masks the source string with a specific character,
  455.        ''' allowing certain characters to remain unmasked.
  456.        ''' </summary>
  457.        ''' ----------------------------------------------------------------------------------------------------
  458.        ''' <example> This is a code example.
  459.        ''' <code language="VB.NET">
  460.        ''' Dim serialKey As New SecureString()
  461.        ''' With serialKey
  462.        '''     .AppendChar("1"c)
  463.        '''     .AppendChar("2"c)
  464.        '''     .AppendChar("3"c)
  465.        '''     .AppendChar("-"c)
  466.        '''     .AppendChar("4"c)
  467.        '''     .AppendChar("5"c)
  468.        '''     .AppendChar("6"c)
  469.        '''     .AppendChar("-"c)
  470.        '''     .AppendChar("7"c)
  471.        '''     .AppendChar("8"c)
  472.        '''     .AppendChar("9"c)
  473.        ''' End With
  474.        '''
  475.        ''' Dim maskLength As Integer = 7
  476.        ''' Dim leftToRight As Boolean = True
  477.        ''' Dim allowedChars As Char() = "-".ToCharArray()
  478.        ''' Dim maskChar As Char = "*"c
  479.        '''
  480.        ''' Dim masked As SecureString = MaskSecureString(serialKey, maskLength, leftToRight, allowedChars, maskChar)
  481.        ''' </code>
  482.        ''' </example>
  483.        ''' ----------------------------------------------------------------------------------------------------
  484.        ''' <param name="value">
  485.        ''' The string to mask.
  486.        ''' </param>
  487.        '''
  488.        ''' <param name="maskLength">
  489.        ''' The length of the mask.
  490.        ''' </param>
  491.        '''
  492.        ''' <param name="leftToRight">
  493.        ''' Indicates the direction of the mask (left to right or right to left).
  494.        ''' </param>
  495.        '''
  496.        ''' <param name="allowedChars">
  497.        ''' An array of characters that are allowed to remain unmasked.
  498.        ''' </param>
  499.        '''
  500.        ''' <param name="maskCharacter">
  501.        ''' The character used for masking (default: "*").
  502.        ''' </param>
  503.        ''' ----------------------------------------------------------------------------------------------------
  504.        ''' <returns>
  505.        ''' The masked string.
  506.        ''' </returns>
  507.        ''' ----------------------------------------------------------------------------------------------------
  508.        <DebuggerStepperBoundary>
  509.        Public Shared Function MaskSecureString(value As SecureString, maskLength As Integer, leftToRight As Boolean, allowedChars As Char(), Optional maskCharacter As Char = "*"c) As SecureString
  510.  
  511.            Dim managedString As String = ToManagedString(value)
  512.            Return MaskSecureString(managedString, maskLength:=maskLength, leftToRight:=leftToRight, allowedChars:=allowedChars, maskCharacter:=maskCharacter)
  513.  
  514.        End Function
  515.  
  516. #End Region
  517.  
  518. #Region " Private Methods "
  519.  
  520.        ''' ----------------------------------------------------------------------------------------------------
  521.        ''' <summary>
  522.        ''' Converts the source <see cref="Global.System.Security.SecureString"/> to a managed <see cref="String"/>.
  523.        ''' </summary>
  524.        ''' ----------------------------------------------------------------------------------------------------
  525.        ''' <example> This is a code example.
  526.        ''' <code language="VB.NET">
  527.        ''' Dim secStr As New SecureString()
  528.        ''' With secStr
  529.        '''     .AppendChar("q"c)
  530.        '''     .AppendChar("w"c)
  531.        '''     .AppendChar("e"c)
  532.        '''     .AppendChar("r"c)
  533.        '''     .AppendChar("t"c)
  534.        '''     .AppendChar("y"c)
  535.        ''' End With
  536.        '''
  537.        ''' MessageBox.Show(secStr.ToManagedString())
  538.        ''' </code>
  539.        ''' </example>
  540.        ''' ----------------------------------------------------------------------------------------------------
  541.        ''' <param name="secureString">
  542.        ''' The source <see cref="Global.System.Security.SecureString"/>.
  543.        ''' </param>
  544.        ''' ----------------------------------------------------------------------------------------------------
  545.        ''' <returns>
  546.        ''' The resulting <see cref="String"/>.
  547.        ''' </returns>
  548.        ''' ----------------------------------------------------------------------------------------------------
  549.        <DebuggerStepThrough>
  550.        <EditorBrowsable(EditorBrowsableState.Never)>
  551.        Private Shared Function ToManagedString(secureString As Global.System.Security.SecureString) As String
  552.  
  553.            If secureString Is Nothing Then
  554.                Throw New ArgumentNullException(NameOf(secureString))
  555.            End If
  556.  
  557.            If secureString.Length = 0 Then
  558.                Return ""
  559.  
  560.            Else
  561.                Dim ptr As System.IntPtr = Global.System.IntPtr.Zero
  562.  
  563.                Try
  564.                    ptr = Marshal.SecureStringToGlobalAllocUnicode(secureString)
  565.                    Return Marshal.PtrToStringUni(ptr)
  566.  
  567.                Finally
  568.                    If ptr <> IntPtr.Zero Then
  569.                        Marshal.ZeroFreeGlobalAllocUnicode(ptr)
  570.                    End If
  571.  
  572.                End Try
  573.  
  574.            End If
  575.  
  576.        End Function
  577.  
  578. #End Region
  579.  
  580.    End Class
  581.  
  582. End Namespace
  583.  
  584. #End Region
  585.  
En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #556 en: 10 Septiembre 2023, 08:25 am »

He escrito este simulador / generador de errores tipográficos en un string.

No está muy pulido, pero es un comienzo de idea.

Las reglas son las siguientes:

Citar
● The error-rate percentage calculation is done for the input text length,
instead of throwing the dice for each character.

● Letters can only be replaced with different letters of the same case (upper-case or lower-case).

● Numbers can only be replaced with other (different) numbers.

● Special characters like punctuation and white-spaces will remain untouched.

Ejemplo de uso:
Código
  1. Dim inputText As String = "I possess the virtues of rapid and error-free typing. Through my precise keystrokes and unwavering focus, I consistently deliver written content efficiently and accurately.
  2.  
  3. My typing speed is unparalleled, allowing me to swiftly transcribe thoughts into written form with remarkable velocity. Each keystroke is executed with precision, enabling me to maintain a consistent flow of text while adhering to the highest standards of accuracy.
  4.  
  5. In addition to speed, my dedication to perfection ensures that typographical errors are virtually non-existent in my output. Meticulously reviewing each line of text, I meticulously detect and rectify any potential errors, guaranteeing a polished and professional final product.
  6.  
  7. Whether it's crafting detailed reports, composing compelling articles, or engaging in fast-paced communication, my quick and error-free typing abilities empower me to meet deadlines with ease and precision. I take pride in my proficiency, knowing that it contributes to a seamless and efficient workflow.
  8.  
  9. In summary, my virtuosity in fast and error-free typing is a testament to my commitment to professionalism and excellence. With swift keystrokes and unwavering accuracy, I offer a valuable asset for any task that demands efficiency, precision, and an impeccable attention to detail."
  10.  
  11. Dim errorrate As Integer = 2 ' 2 percent of the total input text length.
  12. Dim letters As Boolean = True
  13. Dim numbers As Boolean = True
  14.  
  15. Dim result As String = UtilString.GenerateTypos(inputText, errorrate, letters, numbers)
  16.  
  17. Console.WriteLine(result)

Salida:
Citar
Whether it's crafting detailed reports, composing yompelling articles, or engaging in fast-paced communication, my quick and error-free gyping abilities empower me to meet deadlines with ease and precusion. I take pride in my proriciency, knowing that it contributes to a seamless and efficient workflow.

In summary, my virtuosity in fast and error-free typing is a kestament to my commitment to professionalism and excellence. With fwift keystrokes and unwavering accuracy, I offer a valuable asset for eny task that demands efficiencv, precision, and an imxeccable attention to detail.



UtilString.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 14-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' GenerateTypos(String, Integer,  Boolean, Boolean) As String
  11.  
  12. #End Region
  13.  
  14. #End Region
  15.  
  16. #Region " Option Statements "
  17.  
  18. Option Strict On
  19. Option Explicit On
  20. Option Infer Off
  21.  
  22. #End Region
  23.  
  24. #Region " Imports "
  25.  
  26. Imports System.Collections.Generic
  27. Imports System.Text
  28.  
  29. Imports DevCase.Runtime.Numerics
  30.  
  31. #End Region
  32.  
  33. #Region " String Util "
  34.  
  35. ' ReSharper disable once CheckNamespace
  36.  
  37. Namespace DevCase.Core.DataProcessing.Common
  38.  
  39.    Partial Public NotInheritable Class UtilString
  40.  
  41. #Region " Public Methods "
  42.  
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        ''' <summary>
  45.        ''' Simulate random typographical errors in the input text, based on the specified error rate.
  46.        ''' <para></para>
  47.        ''' Rules:
  48.        ''' <para></para>
  49.        ''' &#9679; The error-rate percentage calculation is done for the input text length,
  50.        ''' instead of throwing the dice for each character.
  51.        ''' <para></para>
  52.        ''' &#9679; Letters can only be replaced with different letters of the same case (upper-case or lower-case).
  53.        ''' <para></para>
  54.        ''' &#9679; Numbers can only be replaced with different numbers.
  55.        ''' <para></para>
  56.        ''' &#9679; Special characters like punctuation and white-spaces will remain untouched.
  57.        ''' </summary>
  58.        ''' ----------------------------------------------------------------------------------------------------
  59.        ''' <example> This is a code example.
  60.        ''' <code language="VB.NET">
  61.        ''' Dim inputText As String = "I possess the virtues of rapid and error-free typing. Through my precise keystrokes and unwavering focus, I consistently deliver written content efficiently and accurately.
  62.        '''
  63.        ''' My typing speed is unparalleled, allowing me to swiftly transcribe thoughts into written form with remarkable velocity. Each keystroke is executed with precision, enabling me to maintain a consistent flow of text while adhering to the highest standards of accuracy.
  64.        '''
  65.        ''' In addition to speed, my dedication to perfection ensures that typographical errors are virtually non-existent in my output. Meticulously reviewing each line of text, I meticulously detect and rectify any potential errors, guaranteeing a polished and professional final product.
  66.        '''
  67.        ''' Whether it's crafting detailed reports, composing compelling articles, or engaging in fast-paced communication, my quick and error-free typing abilities empower me to meet deadlines with ease and precision. I take pride in my proficiency, knowing that it contributes to a seamless and efficient workflow.
  68.        '''
  69.        ''' In summary, my virtuosity in fast and error-free typing is a testament to my commitment to professionalism and excellence. With swift keystrokes and unwavering accuracy, I offer a valuable asset for any task that demands efficiency, precision, and an impeccable attention to detail."
  70.        '''
  71.        ''' Dim errorrate As Integer = 2 ' 2 percent of the total input text length.
  72.        ''' Dim letters As Boolean = True
  73.        ''' Dim numbers As Boolean = True
  74.        '''
  75.        ''' Dim result As String = GenerateTypos(inputText, errorrate, letters, numbers)
  76.        '''
  77.        ''' Console.WriteLine(result)
  78.        ''' </code>
  79.        ''' </example>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <param name="input">
  82.        ''' The input text.
  83.        ''' </param>
  84.        '''
  85.        ''' <param name="errorRate">
  86.        ''' The error rate percentage. It must be in the range of 0 to 100.
  87.        ''' <para></para>
  88.        ''' Note: The error-rate percentage calculation is done for the input text length,
  89.        ''' instead of throwing the dice for each character.
  90.        ''' <para></para>
  91.        ''' If this value is 0, no changes are made to the input text.
  92.        ''' <para></para>
  93.        ''' If error rate is too small for the length of the input text, it may not add any typos.
  94.        ''' <para></para>
  95.        ''' Suggested values can go between 1 to 5 percent.
  96.        ''' Higher values will produce more typos, so more unrealistic simulations.
  97.        ''' </param>
  98.        '''
  99.        ''' <param name="letters">
  100.        ''' Optional. If true, allows to simulate random typographical errors in letters. Default value is True.
  101.        ''' <para></para>
  102.        ''' Note: Letters can only be replaced with different letters of the same case (upper-case or lower-case).
  103.        ''' </param>
  104.        '''
  105.        ''' <param name="numbers">
  106.        ''' Optional. If true, allows to simulate random typographical errors in numbers. Default value is True.
  107.        ''' <para></para>
  108.        ''' Note: Numbers can only be replaced with different numbers.
  109.        ''' </param>
  110.        ''' ----------------------------------------------------------------------------------------------------
  111.        ''' <returns>
  112.        ''' The resulting text with random typographical errors added.
  113.        ''' </returns>
  114.        ''' ----------------------------------------------------------------------------------------------------
  115.        Public Shared Function GenerateTypos(input As String, errorRate As Integer,
  116.                                             letters As Boolean, numbers As Boolean) As String
  117.  
  118.            If errorRate < 0 Or errorRate > 100 Then
  119.                Throw New ArgumentException($"'{NameOf(errorRate)}' must be in the range of 0 to 100.")
  120.            ElseIf errorRate = 0 Then
  121.                Return input
  122.            End If
  123.  
  124.            ' Get a proper input string length by replacing white-spaces
  125.            ' to try produce a more realistic (smaller) error rate count.
  126.            Dim charsToRemove As Char() = ",.´`+¡'!·$%&/()=?¿^;:¨*[]{}-_""".ToCharArray()
  127.            Dim inputLength As Integer = InternalReplaceChars(input, charsToRemove, Nothing, StringComparison.OrdinalIgnoreCase, -1).Length
  128.  
  129.            ' Calculate the amount of typographical errors to generate in the source string.
  130.            Dim typosCount As Integer = CInt(System.Math.Round(inputLength * errorRate / 100))
  131.            If typosCount = 0 Then
  132.                typosCount = 1
  133.            End If
  134.  
  135.            Dim sb As New StringBuilder()
  136.            Dim selectedIndices As New HashSet(Of Integer)()
  137.            Dim validIndices As New List(Of Integer)()
  138.  
  139.            For i As Integer = 0 To input.Length - 1
  140.                Dim c As Char = input(i)
  141.                If (letters AndAlso Char.IsLetter(c)) OrElse (numbers AndAlso Char.IsDigit(c)) Then
  142.                    validIndices.Add(i)
  143.                End If
  144.            Next
  145.  
  146.            If validIndices.Count = 0 Then
  147.                Return input
  148.            End If
  149.  
  150.            If validIndices.Count <= typosCount Then
  151.                For i As Integer = 0 To input.Length - 1
  152.                    Dim c As Char = input(i)
  153.                    Dim modifiedChar As Char = c
  154.                    If validIndices.Contains(i) AndAlso RandomNumberGenerator.Instance.Next(100) < errorRate Then
  155.                        If letters AndAlso Char.IsLetter(c) Then
  156.                            modifiedChar = RandomReplaceLetterOrDigit(c)
  157.                        ElseIf numbers AndAlso Char.IsDigit(c) Then
  158.                            modifiedChar = RandomReplaceLetterOrDigit(c)
  159.                        End If
  160.                    End If
  161.                    sb.Append(modifiedChar)
  162.                Next
  163.                Return sb.ToString()
  164.            End If
  165.  
  166.            While selectedIndices.Count < typosCount
  167.                Dim index As Integer = validIndices(RandomNumberGenerator.Instance.Next(validIndices.Count))
  168.                selectedIndices.Add(index)
  169.            End While
  170.  
  171.            For i As Integer = 0 To input.Length - 1
  172.                Dim c As Char = input(i)
  173.                Dim modifiedChar As Char = c
  174.                If selectedIndices.Contains(i) Then
  175.                    If letters AndAlso Char.IsLetter(c) Then
  176.                        modifiedChar = RandomReplaceLetterOrDigit(c)
  177.                    ElseIf numbers AndAlso Char.IsDigit(c) Then
  178.                        modifiedChar = RandomReplaceLetterOrDigit(c)
  179.                    End If
  180.                End If
  181.                sb.Append(modifiedChar)
  182.            Next
  183.  
  184.            Return sb.ToString()
  185.        End Function
  186.  
  187. #End Region
  188.  
  189. #Region " Private Methods "
  190.  
  191.        ''' ----------------------------------------------------------------------------------------------------
  192.        ''' <summary>
  193.        ''' Replaces text using the specified string comparison type.
  194.        ''' </summary>
  195.        ''' ----------------------------------------------------------------------------------------------------
  196.        ''' <remarks>
  197.        ''' Original source:
  198.        ''' <see href="http://www.codeproject.com/Articles/10890/Fastest-C-Case-Insenstive-String-Replace?msg=1835929#xx1835929xx"/>
  199.        ''' </remarks>
  200.        ''' ----------------------------------------------------------------------------------------------------
  201.        ''' <example> This is a code example.
  202.        ''' <code language="VB.NET">
  203.        ''' Dim str As String = "Hello World!".Replace("Hd".ToCharArray(), "_", StringComparison.OrdinalIgnoreCase)
  204.        ''' </code>
  205.        ''' </example>
  206.        ''' ----------------------------------------------------------------------------------------------------
  207.        ''' <param name="str">
  208.        ''' The source <see cref="String"/>.
  209.        ''' </param>
  210.        '''
  211.        ''' <param name="findWhat">
  212.        ''' The characters to find.
  213.        ''' </param>
  214.        '''
  215.        ''' <param name="replaceWith">
  216.        ''' The string to replace with.
  217.        ''' </param>
  218.        '''
  219.        ''' <param name="comparisonType">
  220.        ''' The string comparison type.
  221.        ''' </param>
  222.        '''
  223.        ''' <param name="stringBuilderCapacity">
  224.        ''' The initial buffer size of the <see cref="Stringbuilder"/>.
  225.        ''' This parameter is reserved for testing purposes.
  226.        ''' </param>
  227.        ''' ----------------------------------------------------------------------------------------------------
  228.        ''' <returns>
  229.        ''' The replaced string.
  230.        ''' </returns>
  231.        ''' ----------------------------------------------------------------------------------------------------
  232.        <DebuggerStepThrough>
  233.        Private Shared Function InternalReplaceChars(str As String,
  234.                                                     findWhat As IEnumerable(Of Char),
  235.                                                     replaceWith As String,
  236.                                                     comparisonType As StringComparison,
  237.                                                     stringBuilderCapacity As Integer) As String
  238.  
  239.            Dim sb As New Global.System.Text.StringBuilder(capacity:=If(stringBuilderCapacity <= 0, System.Math.Min(4096, str.Length), stringBuilderCapacity))
  240.  
  241.            Dim charFound As Boolean
  242.  
  243.            For Each c As Char In str
  244.                For Each find As Char In findWhat
  245.                    If CStr(c).Equals(find, comparisonType) Then
  246.                        charFound = True
  247.                        Exit For
  248.                    End If
  249.                Next
  250.  
  251.                If Not charFound Then
  252.                    sb.Append(c)
  253.                Else
  254.                    sb.Append(replaceWith)
  255.                    charFound = False
  256.                End If
  257.            Next
  258.  
  259.            Return sb.ToString()
  260.  
  261.        End Function
  262.  
  263. #End Region
  264.  
  265.    End Class
  266.  
  267. End Namespace
  268.  
  269. #End Region
  270.  



UtilString.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 14-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' RandomReplaceLetterOrDigit(Char) As Char
  11.  
  12. #End Region
  13.  
  14. #End Region
  15.  
  16. #Region " Option Statements "
  17.  
  18. Option Strict On
  19. Option Explicit On
  20. Option Infer Off
  21.  
  22. #End Region
  23.  
  24. #Region " Imports "
  25.  
  26. Imports DevCase.Runtime.Numerics
  27.  
  28. #End Region
  29.  
  30. #Region " String Util "
  31.  
  32. ' ReSharper disable once CheckNamespace
  33.  
  34. Namespace DevCase.Core.DataProcessing.Common
  35.  
  36.    Partial Public NotInheritable Class UtilString
  37.  
  38. #Region " Public Methods "
  39.  
  40.        ''' --------------------------------------------------------------------------------------------------
  41.        ''' <summary>
  42.        ''' Replaces a letter or digit character with a random character of the same type based on these specific rules:
  43.        ''' <para></para>
  44.        ''' &#9679; If the character is a digit ( <c>Char.IsDigit(character)</c> ),
  45.        ''' the function returns a different digit from the range "0" to "9".
  46.        ''' <para></para>
  47.        ''' &#9679; If the character is a letter ( <c>Char.IsLetter(character)</c> ):
  48.        ''' <para></para>
  49.        '''   - If it is a vowel, and it is upper-case, the function returns a different upper-case vowel.
  50.        ''' <para></para>
  51.        '''   - If it is a vowel, and it is lower-case, the function returns a different lower-case vowel.
  52.        ''' <para></para>
  53.        '''   - If it is a consonant, and it is upper-case, the function returns a different upper-case consonant.
  54.        ''' <para></para>
  55.        '''   - If it is a consonant, and it is lower-case, the function returns a different lower-case consonant.
  56.        ''' <para></para>
  57.        ''' &#9679; If the character is neither a letter nor a digit, the function returns the same character.
  58.        ''' </summary>
  59.        ''' --------------------------------------------------------------------------------------------------
  60.        ''' <param name="character">
  61.        ''' The character to be replaced.
  62.        ''' </param>
  63.        ''' --------------------------------------------------------------------------------------------------
  64.        ''' <returns>
  65.        ''' If the character is a letter or digit, returns a random character of the same type;
  66.        ''' otherwise, returns the same character.
  67.        ''' </returns>
  68.        ''' --------------------------------------------------------------------------------------------------
  69.        <DebuggerStepThrough>
  70.        Public Shared Function RandomReplaceLetterOrDigit(character As Char) As Char
  71.  
  72.            Dim availableChars As Char()
  73.  
  74.            If Char.IsDigit(character) Then
  75.                availableChars = "0123456789".ToCharArray()
  76.  
  77.            ElseIf Char.IsLetter(character) Then
  78.                availableChars = If(Char.IsUpper(character),
  79.                    If("AEIOU".Contains(character),
  80.                       "AEIOU".ToCharArray(),
  81.                       "BCDFGHJKLMNPQRSTVWXYZ".ToCharArray()),
  82.                    If("aeiou".Contains(character),
  83.                       "aeiou".ToCharArray(),
  84.                       "bcdfghjklmnpqrstvwxyz".ToCharArray()))
  85.  
  86.            Else
  87.                Return character
  88.                ' Throw New ArgumentException("The character is neither a letter nor a digit.", paramName:=NameOf(character))
  89.  
  90.            End If
  91.  
  92.            Dim randomChar As Char
  93.            Do
  94.                randomChar = availableChars(RandomNumberGenerator.Instance.Next(availableChars.Length))
  95.            Loop While randomChar = character
  96.  
  97.            Return randomChar
  98.        End Function
  99.  
  100. #End Region
  101.  
  102.    End Class
  103.  
  104. End Namespace
  105.  
  106. #End Region
  107.  



RandomNumberGenerator.vb
https://foro.elhacker.net/net_c_vbnet_asp/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg2272581#msg2272581

En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #557 en: 10 Septiembre 2023, 08:32 am »

Aquí les dejo una función para eliminar los tags html de un código html y dejar solo el texto, lo que se conoce como "html stripper".

Se necesita la librería HtmlAgilityPack: https://www.nuget.org/packages/HtmlAgilityPack

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 17-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' StripHtml(String, String()) As String
  11.  
  12. #End Region
  13.  
  14. #End Region
  15.  
  16. #Region " Option Statements "
  17.  
  18. Option Strict On
  19. Option Explicit On
  20. Option Infer Off
  21.  
  22. #End Region
  23.  
  24. #Region " Imports "
  25.  
  26. Imports System.Collections.Generic
  27. Imports System.Collections.ObjectModel
  28. Imports System.ComponentModel
  29. Imports System.Linq
  30.  
  31. Imports HtmlAgilityPack
  32.  
  33. #End Region
  34.  
  35. #Region " HtmlAgilityPack Util "
  36.  
  37. ' ReSharper disable once CheckNamespace
  38.  
  39. Namespace DevCase.ThirdParty.HtmlAgilityPack
  40.  
  41.    ''' ----------------------------------------------------------------------------------------------------
  42.    ''' <summary>
  43.    ''' Contains HtmlAgilityPack related utilities.
  44.    ''' </summary>
  45.    ''' ----------------------------------------------------------------------------------------------------
  46.    ''' <remarks>
  47.    ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  48.    ''' <para></para>
  49.    ''' <see href="https://www.nuget.org/packages/HtmlAgilityPack">HtmlAgilityPack</see>
  50.    ''' </remarks>
  51.    ''' ----------------------------------------------------------------------------------------------------
  52.    <ImmutableObject(True)>
  53.    Public NotInheritable Class UtilHtmlAgilityPack
  54.  
  55. #Region " Constructors "
  56.  
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <summary>
  59.        ''' Prevents a default instance of the <see cref="UtilHtmlAgilityPack"/> class from being created.
  60.        ''' </summary>
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        ''' <remarks>
  63.        ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  64.        ''' <para></para>
  65.        ''' <see href="https://www.nuget.org/packages/HtmlAgilityPack">HtmlAgilityPack</see>
  66.        ''' </remarks>
  67.        ''' ----------------------------------------------------------------------------------------------------
  68.        <DebuggerNonUserCode>
  69.        Private Sub New()
  70.        End Sub
  71.  
  72. #End Region
  73.  
  74. #Region " Public Methods "
  75.  
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <summary>
  78.        ''' Removes HTML tags from an html string and returns the content in plain text format.
  79.        ''' </summary>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <remarks>
  82.        ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  83.        ''' <para></para>
  84.        ''' <seealso href="https://www.nuget.org/packages/HtmlAgilityPack">HtmlAgilityPack</seealso>
  85.        ''' </remarks>
  86.        ''' ----------------------------------------------------------------------------------------------------
  87.        ''' <seealso href="https://stackoverflow.com/a/12836974/1248295">Original C# algorithm</seealso>
  88.        ''' ----------------------------------------------------------------------------------------------------
  89.        ''' <example> This is a code example.
  90.        ''' <code language="VB.NET">
  91.        ''' Dim html As String =
  92.        ''' <![CDATA[
  93.        ''' <P style="MARGIN: 0cm 0cm 10pt" class=MsoNormal><SPAN style="LINE-HEIGHT: 115%;
  94.        ''' FONT-FAMILY: 'Verdana','sans-serif'; COLOR: #333333; FONT-SIZE: 9pt">In an
  95.        ''' email sent just three days before the Deepwater Horizon exploded, the onshore
  96.        ''' <SPAN style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> manager in charge of
  97.        ''' the drilling rig warned his supervisor that last-minute procedural changes were
  98.        ''' creating "chaos". April emails were given to government investigators by <SPAN
  99.        ''' style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> and reviewed by The Wall
  100.        ''' Street Journal and are the most direct evidence yet that workers on the rig
  101.        ''' were unhappy with the numerous changes, and had voiced their concerns to <SPAN
  102.        ''' style="mso-bidi-font-weight: bold"><b>BP</b></SPAN>’s operations managers in
  103.        ''' Houston. This raises further questions about whether <SPAN
  104.        ''' style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> managers properly
  105.        ''' considered the consequences of changes they ordered on the rig, an issue
  106.        ''' investigators say contributed to the disaster.</SPAN></p><br/>
  107.        ''' ]]>.Value
  108.        '''
  109.        ''' Dim allowedTags As String() = {"span", "b"}
  110.        ''' Dim str As String = StripHtml(html, allowedTags)
  111.        ''' Console.WriteLine(str)
  112.        ''' </code>
  113.        ''' </example>
  114.        ''' ----------------------------------------------------------------------------------------------------
  115.        ''' <param name="html">
  116.        ''' The string that contains HTML tags.
  117.        ''' </param>
  118.        '''
  119.        ''' <param name="allowedTags">
  120.        ''' An optional list of allowed HTML tags that will not be removed from the string.
  121.        ''' </param>
  122.        ''' ----------------------------------------------------------------------------------------------------
  123.        ''' <returns>
  124.        ''' The resulting plain text content without HTML tags.
  125.        ''' </returns>
  126.        ''' ----------------------------------------------------------------------------------------------------
  127.        <DebuggerStepThrough>
  128.        Public Shared Function StripHtml(html As String, ParamArray allowedTags As String()) As String
  129.            If String.IsNullOrEmpty(html) Then
  130.                Return String.Empty
  131.            End If
  132.            Dim document As New HtmlDocument()
  133.            document.LoadHtml(html)
  134.  
  135.            Dim nodes As New Queue(Of HtmlNode)(document.DocumentNode.SelectNodes("./*|./text()"))
  136.            Do While nodes.Count > 0
  137.                Dim node As HtmlNode = nodes.Dequeue()
  138.                Dim parentNode As HtmlNode = node.ParentNode
  139.  
  140.                If Not allowedTags.Contains(node.Name) AndAlso node.Name <> "#text" Then
  141.                    Dim childNodes As HtmlNodeCollection = node.SelectNodes("./*|./text()")
  142.  
  143.                    If childNodes IsNot Nothing Then
  144.                        For Each child As HtmlNode In childNodes
  145.                            nodes.Enqueue(child)
  146.                            parentNode.InsertBefore(child, node)
  147.                        Next child
  148.                    End If
  149.  
  150.                    parentNode.RemoveChild(node)
  151.                End If
  152.            Loop
  153.  
  154.            Return System.Net.WebUtility.HtmlDecode(document.DocumentNode.InnerHtml)
  155.        End Function
  156.  
  157. #End Region
  158.  
  159.    End Class
  160.  
  161. End Namespace
  162.  
  163. #End Region
  164.  
En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #558 en: 10 Septiembre 2023, 08:44 am »

Aquí les dejo una clase utiliratia para manipular el indexador de carpetas de Windows. Permite añadir y eliminar directorios, enumerar los directorios actuales, y buscar un directorio.

Se necesita esta librería: https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop

Ejemplos de uso:

Incluir un directorio:
Código
  1. Dim directoryPath As String = "C:\Games\"
  2. SearchIndexerUtil.AddDirectoryRule(directoryPath, include:=True)

Eliminar el directorio:
Código
  1. SearchIndexerUtil.RemoveDirectoryRule(directoryPath)

Comprobar si el directorio está incluído:
Código
  1. Dim isIncluded As Boolean = SearchIndexerUtil.IsDirectoryIncluded(directoryPath)
  2. Debug.WriteLine($"{NameOf(isIncluded)}: {isIncluded}")

Obtener los directorios incluídos:
Código
  1. Dim rules As ReadOnlyCollection(Of CSearchScopeRule) = SearchIndexerUtil.GetDirectoryRules()
  2.  
  3. For Each rule As CSearchScopeRuleClass In rules.Where(Function(x) x.IsDefault = 0)
  4.    Debug.WriteLine($"{NameOf(rule.PatternOrURL)}: {rule.PatternOrURL}")
  5.    Debug.WriteLine($"{NameOf(rule.IsIncluded)}: {rule.IsIncluded = 1}")
  6.    Debug.WriteLine("")
  7. Next



Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 10-October-2022
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Methods "
  9.  
  10. ' AddDirectoryRule(String, Boolean)
  11. ' AddDirectoryRule(DirectoryInfo, Boolean)
  12.  
  13. ' RemoveDirectoryRule(String)
  14. ' RemoveDirectoryRule(DirectoryInfo)
  15.  
  16. ' GetDirectoryRules() As ReadOnlyCollection(Of CSearchScopeRule)
  17.  
  18. ' FindDirectoryRule(String) As CSearchScopeRule
  19. ' FindDirectoryRule(DirectoryInfo) As CSearchScopeRule
  20.  
  21. ' IsDirectoryIncluded(String) As Boolean
  22. ' IsDirectoryIncluded(DirectoryInfo) As Boolean
  23.  
  24. #End Region
  25.  
  26. #End Region
  27.  
  28. #Region " Option Statements "
  29.  
  30. Option Strict On
  31. Option Explicit On
  32. Option Infer Off
  33.  
  34. #End Region
  35.  
  36. #Region " Imports "
  37.  
  38. Imports System.Collections.ObjectModel
  39. Imports System.IO
  40.  
  41. Imports Microsoft.Search.Interop
  42.  
  43. #End Region
  44.  
  45. #Region " SearchIndexer Util "
  46.  
  47. ' ReSharper disable once CheckNamespace
  48.  
  49. Namespace DevCase.ThirdParty.MicrosoftSearchIndexer
  50.  
  51.    ''' ----------------------------------------------------------------------------------------------------
  52.    ''' <summary>
  53.    ''' Contains Microsoft Search Indexer related utilities.
  54.    ''' </summary>
  55.    ''' ----------------------------------------------------------------------------------------------------
  56.    ''' <remarks>
  57.    ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  58.    ''' <para></para>
  59.    ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see>
  60.    ''' </remarks>
  61.    ''' ----------------------------------------------------------------------------------------------------
  62.    Public NotInheritable Class UtilSearchIndexer
  63.  
  64. #Region " Private Fields "
  65.  
  66.        ''' ----------------------------------------------------------------------------------------------------
  67.        ''' <summary>
  68.        ''' Provides methods for controlling the Search service.
  69.        ''' <para></para>
  70.        ''' This interface manages settings and objects that affect the search engine across catalogs.
  71.        ''' </summary>
  72.        ''' ----------------------------------------------------------------------------------------------------
  73.        ''' <remarks>
  74.        ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  75.        ''' <para></para>
  76.        ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see>
  77.        ''' </remarks>
  78.        ''' ----------------------------------------------------------------------------------------------------
  79.        Private Shared searchManager As CSearchManager
  80.  
  81.        ''' ----------------------------------------------------------------------------------------------------
  82.        ''' <summary>
  83.        ''' Provides methods to manage a search catalog for purposes such as re-indexing or setting timeouts.
  84.        ''' </summary>
  85.        ''' ----------------------------------------------------------------------------------------------------
  86.        ''' <remarks>
  87.        ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  88.        ''' <para></para>
  89.        ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see>
  90.        ''' </remarks>
  91.        ''' ----------------------------------------------------------------------------------------------------
  92.        Private Shared catalogManager As CSearchCatalogManager
  93.  
  94.        ''' ----------------------------------------------------------------------------------------------------
  95.        ''' <summary>
  96.        ''' Provides methods that notify the search engine of containers to crawl and/or watch,
  97.        ''' and items under those containers to include or exclude when crawling or watching.
  98.        ''' </summary>
  99.        ''' ----------------------------------------------------------------------------------------------------
  100.        ''' <remarks>
  101.        ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  102.        ''' <para></para>
  103.        ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see>
  104.        ''' </remarks>
  105.        ''' ----------------------------------------------------------------------------------------------------
  106.        Private Shared scopeManager As CSearchCrawlScopeManager
  107.  
  108. #End Region
  109.  
  110. #Region " Constructors "
  111.  
  112.        ''' ----------------------------------------------------------------------------------------------------
  113.        ''' <summary>
  114.        ''' Prevents a default instance of the <see cref="UtilSearchIndexer"/> class from being created.
  115.        ''' </summary>
  116.        ''' ----------------------------------------------------------------------------------------------------
  117.        ''' <remarks>
  118.        ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  119.        ''' <para></para>
  120.        ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see>
  121.        ''' </remarks>
  122.        ''' ----------------------------------------------------------------------------------------------------
  123.        <DebuggerNonUserCode>
  124.        Private Sub New()
  125.        End Sub
  126.  
  127. #End Region
  128.  
  129. #Region " Public Methods "
  130.  
  131.        ''' ----------------------------------------------------------------------------------------------------
  132.        ''' <summary>
  133.        ''' Adds the specified directory path to Windows Search Index.
  134.        ''' </summary>
  135.        ''' ----------------------------------------------------------------------------------------------------
  136.        ''' <remarks>
  137.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-adduserscoperule"/>
  138.        ''' </remarks>
  139.        ''' ----------------------------------------------------------------------------------------------------
  140.        ''' <example> This is a code example.
  141.        ''' <code language="VB.NET">
  142.        ''' Dim directoryPath As String = "C:\Games\"
  143.        ''' SearchIndexerUtil.AddDirectoryRule(directoryPath, include:=True)
  144.        ''' </code>
  145.        ''' </example>
  146.        ''' ----------------------------------------------------------------------------------------------------
  147.        ''' <param name="directoryPathOrPattern">
  148.        ''' The directory path (or a directory path pattern with wildcards) to be indexed.
  149.        ''' </param>
  150.        '''
  151.        ''' <param name="include">
  152.        ''' <see langword="True"/> if this directory should be included in all searches;
  153.        ''' otherwise, <see langword="False"/>.
  154.        ''' </param>
  155.        ''' ----------------------------------------------------------------------------------------------------
  156.        <DebuggerStepThrough>
  157.        Public Shared Sub AddDirectoryRule(directoryPathOrPattern As String, include As Boolean)
  158.  
  159.            UtilSearchIndexer.InitializeManagers()
  160.  
  161.            Dim uriPath As String = $"file:///{directoryPathOrPattern}"
  162.            UtilSearchIndexer.scopeManager.AddUserScopeRule(uriPath, fInclude:=If(include, 1, 0), fOverrideChildren:=0, fFollowFlags:=Nothing)
  163.            UtilSearchIndexer.scopeManager.SaveAll()
  164.  
  165.        End Sub
  166.  
  167.        ''' ----------------------------------------------------------------------------------------------------
  168.        ''' <summary>
  169.        ''' Adds the specified directory path to Windows Search Index.
  170.        ''' </summary>
  171.        ''' ----------------------------------------------------------------------------------------------------
  172.        ''' <remarks>
  173.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-adduserscoperule"/>
  174.        ''' </remarks>
  175.        ''' ----------------------------------------------------------------------------------------------------
  176.        ''' <example> This is a code example.
  177.        ''' <code language="VB.NET">
  178.        ''' Dim directory As New DirectoryInfo("C:\Games\")
  179.        ''' SearchIndexerUtil.AddDirectoryRule(directory, include:=True)
  180.        ''' </code>
  181.        ''' </example>
  182.        ''' ----------------------------------------------------------------------------------------------------
  183.        ''' <param name="directory">
  184.        ''' The directory path to be indexed.
  185.        ''' </param>
  186.        '''
  187.        ''' <param name="include">
  188.        ''' <see langword="True"/> if this directory should be included in all searches;
  189.        ''' otherwise, <see langword="False"/>.
  190.        ''' </param>
  191.        ''' ----------------------------------------------------------------------------------------------------
  192.        <DebuggerStepThrough>
  193.        Public Shared Sub AddDirectoryRule(directory As DirectoryInfo, include As Boolean)
  194.            UtilSearchIndexer.AddDirectoryRule(directory.FullName, include)
  195.        End Sub
  196.  
  197.        ''' ----------------------------------------------------------------------------------------------------
  198.        ''' <summary>
  199.        ''' Removes the specified directory path from Windows Search Index.
  200.        ''' </summary>
  201.        ''' ----------------------------------------------------------------------------------------------------
  202.        ''' <remarks>
  203.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-removescoperule"/>
  204.        ''' </remarks>
  205.        ''' ----------------------------------------------------------------------------------------------------
  206.        ''' <example> This is a code example.
  207.        ''' <code language="VB.NET">
  208.        ''' Dim directoryPath As String = "C:\Games\"
  209.        ''' SearchIndexerUtil.RemoveDirectoryRule(directoryPath)
  210.        ''' </code>
  211.        ''' </example>
  212.        ''' ----------------------------------------------------------------------------------------------------
  213.        ''' <param name="directoryPath">
  214.        ''' The directory path (or a directory path pattern with wildcards) to be deindexed.
  215.        ''' </param>
  216.        ''' ----------------------------------------------------------------------------------------------------
  217.        <DebuggerStepThrough>
  218.        Public Shared Sub RemoveDirectoryRule(directoryPath As String)
  219.  
  220.            UtilSearchIndexer.InitializeManagers()
  221.  
  222.            Dim uriPath As String = $"file:///{directoryPath}"
  223.            UtilSearchIndexer.scopeManager.RemoveScopeRule(uriPath)
  224.            UtilSearchIndexer.scopeManager.SaveAll()
  225.  
  226.        End Sub
  227.  
  228.        ''' ----------------------------------------------------------------------------------------------------
  229.        ''' <summary>
  230.        ''' Removes the specified directory path from Windows Search Index.
  231.        ''' </summary>
  232.        ''' ----------------------------------------------------------------------------------------------------
  233.        ''' <remarks>
  234.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-removescoperule"/>
  235.        ''' </remarks>
  236.        ''' ----------------------------------------------------------------------------------------------------
  237.        ''' <example> This is a code example.
  238.        ''' <code language="VB.NET">
  239.        ''' Dim directory As New DirectoryInfo("C:\Games\")
  240.        ''' SearchIndexerUtil.RemoveDirectoryRule(directory)
  241.        ''' </code>
  242.        ''' </example>
  243.        ''' ----------------------------------------------------------------------------------------------------
  244.        ''' <param name="directory">
  245.        ''' The directory path to be deindexed.
  246.        ''' </param>
  247.        ''' ----------------------------------------------------------------------------------------------------
  248.        <DebuggerStepThrough>
  249.        Public Shared Sub RemoveDirectoryRule(directory As DirectoryInfo)
  250.            UtilSearchIndexer.RemoveDirectoryRule(directory.FullName)
  251.        End Sub
  252.  
  253.        ''' ----------------------------------------------------------------------------------------------------
  254.        ''' <summary>
  255.        ''' Returns all the directory rules in Windows Search Index.
  256.        ''' </summary>
  257.        ''' ----------------------------------------------------------------------------------------------------
  258.        ''' <remarks>
  259.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nn-searchapi-ienumsearchscoperules"/>
  260.        ''' </remarks>
  261.        ''' ----------------------------------------------------------------------------------------------------
  262.        ''' <example> This is a code example.
  263.        ''' <code language="VB.NET">
  264.        ''' Dim rules As ReadOnlyCollection(Of CSearchScopeRule) = SearchIndexerUtil.GetDirectoryRules()
  265.        '''
  266.        ''' For Each rule As CSearchScopeRuleClass In rules.Where(Function(x) x.IsDefault = 0)
  267.        '''     Debug.WriteLine($"{NameOf(rule.PatternOrURL)}: {rule.PatternOrURL}")
  268.        '''     Debug.WriteLine($"{NameOf(rule.IsIncluded)}: {rule.IsIncluded = 1}")
  269.        '''     Debug.WriteLine("")
  270.        ''' Next
  271.        ''' </code>
  272.        ''' </example>
  273.        ''' ----------------------------------------------------------------------------------------------------
  274.        ''' <returns>
  275.        ''' The resulting directory rules.
  276.        ''' </returns>
  277.        ''' ----------------------------------------------------------------------------------------------------
  278.        <DebuggerStepThrough>
  279.        Public Shared Function GetDirectoryRules() As ReadOnlyCollection(Of CSearchScopeRule)
  280.  
  281.            UtilSearchIndexer.InitializeManagers()
  282.  
  283.            Dim collection As New List(Of CSearchScopeRule)
  284.            Dim scopeEnumerator As CEnumSearchScopeRules = UtilSearchIndexer.scopeManager.EnumerateScopeRules()
  285.            Dim fetched As UInteger
  286.  
  287.            Do
  288.                Dim scopeRule As CSearchScopeRule = Nothing
  289.                scopeEnumerator.Next(1, scopeRule, fetched)
  290.                If fetched <> 0 Then
  291.                    collection.Add(scopeRule)
  292.                Else
  293.                    Exit Do
  294.                End If
  295.            Loop
  296.  
  297.            Return collection.AsReadOnly()
  298.  
  299.        End Function
  300.  
  301.        ''' ----------------------------------------------------------------------------------------------------
  302.        ''' <summary>
  303.        ''' Finds a directory rule that matches the specified directory path in Windows Search Index.
  304.        ''' </summary>
  305.        ''' ----------------------------------------------------------------------------------------------------
  306.        ''' <remarks>
  307.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-removescoperule"/>
  308.        ''' </remarks>
  309.        ''' ----------------------------------------------------------------------------------------------------
  310.        ''' <example> This is a code example.
  311.        ''' <code language="VB.NET">
  312.        ''' Dim directoryPath As String = "C:\Games\"
  313.        ''' Dim rule As CSearchScopeRule = FindDirectoryRule(directoryPath)
  314.        '''
  315.        ''' If rule IsNot Nothing Then
  316.        '''     Debug.WriteLine($"{NameOf(rule.PatternOrURL)}: {rule.PatternOrURL}")
  317.        '''     Debug.WriteLine($"{NameOf(rule.IsIncluded)}: {rule.IsIncluded = 1}")
  318.        ''' End If
  319.        ''' </code>
  320.        ''' </example>
  321.        ''' ----------------------------------------------------------------------------------------------------
  322.        ''' <param name="directoryPathOrPattern">
  323.        ''' The directory path (or a directory path pattern with wildcards) to find.
  324.        ''' </param>
  325.        ''' ----------------------------------------------------------------------------------------------------
  326.        ''' <returns>
  327.        ''' The resulting directory rule,
  328.        ''' or <see langword="Nothing"/> if does not exist a directory rule that matches the specified directory path.
  329.        ''' </returns>
  330.        ''' ----------------------------------------------------------------------------------------------------
  331.        <DebuggerStepThrough>
  332.        Public Shared Function FindDirectoryRule(directoryPathOrPattern As String) As CSearchScopeRule
  333.  
  334.            Dim uriPath As String = $"file:///{directoryPathOrPattern}"
  335.            Return UtilSearchIndexer.GetDirectoryRules().Where(Function(scope) scope.PatternOrURL = uriPath).SingleOrDefault()
  336.  
  337.        End Function
  338.  
  339.        ''' ----------------------------------------------------------------------------------------------------
  340.        ''' <summary>
  341.        ''' Finds a directory rule that matches the specified directory path in Windows Search Index.
  342.        ''' </summary>
  343.        ''' ----------------------------------------------------------------------------------------------------
  344.        ''' <remarks>
  345.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-removescoperule"/>
  346.        ''' </remarks>
  347.        ''' ----------------------------------------------------------------------------------------------------
  348.        ''' <example> This is a code example.
  349.        ''' <code language="VB.NET">
  350.        ''' Dim directory As New DirectoryInfo("C:\Games\")
  351.        ''' Dim rule As CSearchScopeRule = FindDirectoryRule(directory)
  352.        '''
  353.        ''' If rule IsNot Nothing Then
  354.        '''     Debug.WriteLine($"{NameOf(rule.PatternOrURL)}: {rule.PatternOrURL}")
  355.        '''     Debug.WriteLine($"{NameOf(rule.IsIncluded)}: {rule.IsIncluded = 1}")
  356.        ''' End If
  357.        ''' </code>
  358.        ''' </example>
  359.        ''' ----------------------------------------------------------------------------------------------------
  360.        ''' <param name="directory">
  361.        ''' The directory path to find.
  362.        ''' </param>
  363.        ''' ----------------------------------------------------------------------------------------------------
  364.        ''' <returns>
  365.        ''' The resulting directory rule,
  366.        ''' or <see langword="Nothing"/> if does not exist a directory rule that matches the specified directory path.
  367.        ''' </returns>
  368.        ''' ----------------------------------------------------------------------------------------------------
  369.        <DebuggerStepThrough>
  370.        Public Shared Function FindDirectoryRule(directory As DirectoryInfo) As CSearchScopeRule
  371.  
  372.            Return UtilSearchIndexer.FindDirectoryRule(directory.FullName)
  373.  
  374.        End Function
  375.  
  376.        ''' ----------------------------------------------------------------------------------------------------
  377.        ''' <summary>
  378.        ''' Returns a value indicating whether the specified directory path is included in Windows Search Index.
  379.        ''' </summary>
  380.        ''' ----------------------------------------------------------------------------------------------------
  381.        ''' <remarks>
  382.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-includedincrawlscope"/>
  383.        ''' </remarks>
  384.        ''' ----------------------------------------------------------------------------------------------------
  385.        ''' <example> This is a code example.
  386.        ''' <code language="VB.NET">
  387.        ''' Dim directoryPath As String = "C:\Games\"
  388.        ''' Dim isIncluded As Boolean = IsDirectoryIncluded(directoryPath)
  389.        '''
  390.        ''' Debug.WriteLine($"{NameOf(isIncluded)}: {isIncluded}")
  391.        ''' </code>
  392.        ''' </example>
  393.        ''' ----------------------------------------------------------------------------------------------------
  394.        ''' <param name="directoryPathOrPattern">
  395.        ''' The directory path (or a directory path pattern with wildcards) to find.
  396.        ''' </param>
  397.        ''' ----------------------------------------------------------------------------------------------------
  398.        ''' <returns>
  399.        ''' <see langword="True"/> if the specified directory path is included in Windows Search Index;
  400.        ''' otherwise, <see langword="False"/>.
  401.        ''' </returns>
  402.        ''' ----------------------------------------------------------------------------------------------------
  403.        <DebuggerStepThrough>
  404.        Public Shared Function IsDirectoryIncluded(directoryPathOrPattern As String) As Boolean
  405.  
  406.            UtilSearchIndexer.InitializeManagers()
  407.  
  408.            Dim uriPath As String = $"file:///{directoryPathOrPattern}"
  409.            Dim included As Integer = UtilSearchIndexer.scopeManager.IncludedInCrawlScope(uriPath)
  410.            Return included = 1
  411.  
  412.        End Function
  413.  
  414.        ''' ----------------------------------------------------------------------------------------------------
  415.        ''' <summary>
  416.        ''' Returns a value indicating whether the specified directory path is included in Windows Search Index.
  417.        ''' </summary>
  418.        ''' ----------------------------------------------------------------------------------------------------
  419.        ''' <remarks>
  420.        ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-includedincrawlscope"/>
  421.        ''' </remarks>
  422.        ''' ----------------------------------------------------------------------------------------------------
  423.        ''' <example> This is a code example.
  424.        ''' <code language="VB.NET">
  425.        ''' Dim directory As New DirectoryInfo("C:\Games\")
  426.        ''' Dim isIncluded As Boolean = IsDirectoryIncluded(directory)
  427.        '''
  428.        ''' Debug.WriteLine($"{NameOf(isIncluded)}: {isIncluded}")
  429.        ''' </code>
  430.        ''' </example>
  431.        ''' ----------------------------------------------------------------------------------------------------
  432.        ''' <param name="directory">
  433.        ''' The directory path to find.
  434.        ''' </param>
  435.        ''' ----------------------------------------------------------------------------------------------------
  436.        ''' <returns>
  437.        ''' <see langword="True"/> if the specified directory path is included in Windows Search Index;
  438.        ''' otherwise, <see langword="False"/>.
  439.        ''' </returns>
  440.        ''' ----------------------------------------------------------------------------------------------------
  441.        <DebuggerStepThrough>
  442.        Public Shared Function IsDirectoryIncluded(directory As DirectoryInfo) As Boolean
  443.  
  444.            Return UtilSearchIndexer.IsDirectoryIncluded(directory.FullName)
  445.  
  446.        End Function
  447.  
  448. #End Region
  449.  
  450. #Region " Private Methods "
  451.  
  452.        ''' ----------------------------------------------------------------------------------------------------
  453.        ''' <summary>
  454.        ''' Initializes the value for <see cref="UtilSearchIndexer.searchManager"/>,
  455.        ''' <see cref="UtilSearchIndexer.catalogManager"/> and
  456.        ''' <see cref="UtilSearchIndexer.scopeManager"/> members.
  457.        ''' </summary>
  458.        ''' ----------------------------------------------------------------------------------------------------
  459.        ''' <remarks>
  460.        ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages:
  461.        ''' <para></para>
  462.        ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see>
  463.        ''' </remarks>
  464.        ''' ----------------------------------------------------------------------------------------------------
  465.        <DebuggerStepThrough>
  466.        Private Shared Sub InitializeManagers()
  467.  
  468.            If UtilSearchIndexer.searchManager Is Nothing Then
  469.                UtilSearchIndexer.searchManager = New CSearchManager()
  470.            End If
  471.  
  472.            If UtilSearchIndexer.catalogManager Is Nothing Then
  473.                UtilSearchIndexer.catalogManager = DirectCast(searchManager.GetCatalog("SystemIndex"), CSearchCatalogManager)
  474.            End If
  475.  
  476.            If UtilSearchIndexer.scopeManager Is Nothing Then
  477.                UtilSearchIndexer.scopeManager = DirectCast(catalogManager.GetCrawlScopeManager(), CSearchCrawlScopeManager)
  478.            End If
  479.  
  480.        End Sub
  481.  
  482. #End Region
  483.  
  484.    End Class
  485.  
  486. End Namespace
  487.  
  488. #End Region
  489.  
En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #559 en: 10 Septiembre 2023, 08:50 am »

Aquí un código para generar las páginas de impresión (para la impresora) del contenido de un control DataGridView.

Ejemplo de uso:
Código
  1. Dim headerBackColor As Color = Color.Gray
  2. Dim headerForeColor As Color = Color.White
  3. Dim rowBackColor As Color = Color.LightGray
  4. Dim rowForeColor As Color = Color.LightGray
  5. Dim rowBackColorAlternate As Color = Color.WhiteSmoke
  6. Dim rowForeColorAlternate As Color = Color.WhiteSmoke
  7.  
  8. Dim printDocument As PrintDocument =
  9.    Me.DataGridView1.GetPrintDocument("Title", textFont:=New Font("Arial", 16),
  10.                                      headerBackColor:=headerBackColor, headerForeColor:=headerForeColor,
  11.                                      rowBackColor:=rowBackColor, rowForeColor:=rowForeColor,
  12.                                      rowBackColorAlternate:=rowBackColorAlternate, rowForeColorAlternate:=rowForeColorAlternate)
  13.  
  14. Dim printPreviewDialog As PrintPreviewDialog = PrintPreviewDialog1
  15. printPreviewDialog.ShowDialog()



Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 13-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' DataGridView.GetPrintDocument(Opt: String, Opt: Font, Opt: Color, Opt: Color, Opt: Color, Opt: Color, Opt: Color, Opt: Color) As PrintDocument
  9.  
  10. #End Region
  11.  
  12. #Region " Option Statements "
  13.  
  14. Option Strict On
  15. Option Explicit On
  16. Option Infer Off
  17.  
  18. #End Region
  19.  
  20. #Region " Imports "
  21.  
  22. Imports System.Drawing.Printing
  23. Imports System.Runtime.CompilerServices
  24.  
  25. #End Region
  26.  
  27. #Region " DataGridView Extensions "
  28.  
  29. ' ReSharper disable once CheckNamespace
  30.  
  31. Namespace DevCase.Extensions.DataGridViewExtensions
  32.  
  33.    ''' ----------------------------------------------------------------------------------------------------
  34.    ''' <summary>
  35.    ''' Contains custom extension methods to use with <see cref="DataGridView"/> control.
  36.    ''' </summary>
  37.    ''' ----------------------------------------------------------------------------------------------------
  38.    <HideModuleName>
  39.    Public Module DataGridViewExtensions
  40.  
  41. #Region " Public Extension Methods "
  42.  
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        ''' <summary>
  45.        ''' Generates a <see cref="PrintDocument"/> object for printing the contents of the source <see cref="DataGridView"/>.
  46.        ''' </summary>
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        ''' <example> This is a code example.
  49.        ''' <code language="VB.NET">
  50.        ''' Dim headerBackColor As Color = Color.Gray
  51.        ''' Dim headerForeColor As Color = Color.White
  52.        ''' Dim rowBackColor As Color = Color.LightGray
  53.        ''' Dim rowForeColor As Color = Color.LightGray
  54.        ''' Dim rowBackColorAlternate As Color = Color.WhiteSmoke
  55.        ''' Dim rowForeColorAlternate As Color = Color.WhiteSmoke
  56.        '''
  57.        ''' Dim printDocument As PrintDocument =
  58.        '''     Me.DataGridView1.GetPrintDocument("Title", textFont:=New Font("Arial", 16),
  59.        '''                                       headerBackColor:=headerBackColor, headerForeColor:=headerForeColor,
  60.        '''                                       rowBackColor:=rowBackColor, rowForeColor:=rowForeColor,
  61.        '''                                       rowBackColorAlternate:=rowBackColorAlternate, rowForeColorAlternate:=rowForeColorAlternate)
  62.        '''
  63.        ''' Dim printPreviewDialog As PrintPreviewDialog = PrintPreviewDialog1
  64.        ''' printPreviewDialog.ShowDialog()
  65.        ''' </code>
  66.        ''' </example>
  67.        ''' ----------------------------------------------------------------------------------------------------
  68.        ''' <param name="dataGridView">
  69.        ''' The <see cref="DataGridView"/> to print.
  70.        ''' </param>
  71.        '''
  72.        ''' <param name="title">
  73.        ''' The title to be printed at the top of the document.
  74.        ''' <para></para>
  75.        ''' If not provided, the <see cref="DataGridView.Name"/> property value will be used as the title.
  76.        ''' </param>
  77.        '''
  78.        ''' <param name="textFont">
  79.        ''' Optional. The font to draw header and row texts.
  80.        ''' <para></para>
  81.        ''' If not provided, the <see cref="DataGridView.Font"/> property value will be used as the text font.
  82.        ''' </param>
  83.        '''
  84.        ''' <param name="headerBackColor">
  85.        ''' Optional. The background color of the header row.
  86.        ''' <para></para>
  87.        ''' If not provided, the default color is <see cref="Color.White"/>.
  88.        ''' </param>
  89.        '''
  90.        ''' <param name="headerForeColor">
  91.        ''' Optional. The text color of the header row.
  92.        ''' <para></para>
  93.        ''' If not provided, the default color is <see cref="Color.Black"/>.
  94.        ''' </param>
  95.        '''
  96.        ''' <param name="rowBackColor">
  97.        ''' Optional. The background color of the data rows.
  98.        ''' <para></para>
  99.        ''' If not provided, the default color is <see cref="Color.White"/>.
  100.        ''' </param>
  101.        '''
  102.        ''' <param name="rowForeColor">
  103.        ''' Optional. The text color of the data rows.
  104.        ''' <para></para>
  105.        ''' If not provided, the default color is <see cref="Color.Black"/>.
  106.        ''' </param>
  107.        '''
  108.        ''' <param name="rowBackColorAlternate">
  109.        ''' Optional. The background color of the alternate data rows.
  110.        ''' <para></para>
  111.        ''' If not provided, the default color is <see cref="Color.White"/>.
  112.        ''' </param>
  113.        '''
  114.        ''' <param name="rowForeColorAlternate">
  115.        ''' Optional.  text color of the alternate data rows.
  116.        ''' <para></para>
  117.        ''' If not provided, the default color is <see cref="Color.Black"/>.
  118.        ''' </param>
  119.        ''' ----------------------------------------------------------------------------------------------------
  120.        ''' <returns>
  121.        ''' A <see cref="PrintDocument"/> object for printing the contents of the source <see cref="DataGridView"/>.
  122.        ''' </returns>
  123.        ''' ----------------------------------------------------------------------------------------------------
  124.        <Extension>
  125.        <DebuggerStepThrough>
  126.        Public Function GetPrintDocument(dataGridView As DataGridView,
  127.                                         Optional title As String = Nothing,
  128.                                         Optional textFont As Font = Nothing,
  129.                                         Optional headerBackColor As Color = Nothing,
  130.                                         Optional headerForeColor As Color = Nothing,
  131.                                         Optional rowBackColor As Color = Nothing,
  132.                                         Optional rowForeColor As Color = Nothing,
  133.                                         Optional rowBackColorAlternate As Color = Nothing,
  134.                                         Optional rowForeColorAlternate As Color = Nothing) As PrintDocument
  135.  
  136.            If String.IsNullOrEmpty(title) Then
  137.                title = dataGridView.Name
  138.            End If
  139.  
  140.            If textFont Is Nothing Then
  141.                textFont = dataGridView.Font
  142.            End If
  143.  
  144.            If headerBackColor = Nothing Then
  145.                headerBackColor = Color.White
  146.            End If
  147.  
  148.            If headerForeColor = Nothing Then
  149.                headerForeColor = Color.Black
  150.            End If
  151.  
  152.            If rowBackColor = Nothing Then
  153.                rowBackColor = Color.White
  154.            End If
  155.  
  156.            If rowForeColor = Nothing Then
  157.                rowForeColor = Color.Black
  158.            End If
  159.  
  160.            If rowBackColorAlternate = Nothing Then
  161.                rowBackColorAlternate = Color.White
  162.            End If
  163.  
  164.            If rowForeColorAlternate = Nothing Then
  165.                rowForeColorAlternate = Color.Black
  166.            End If
  167.  
  168.            Dim currentPageIndex As Integer = 0
  169.            Dim printedRowsCount As Integer = 0
  170.  
  171.            Dim printDocument As New PrintDocument()
  172.            AddHandler printDocument.PrintPage,
  173.                Sub(sender, e)
  174.                    Dim printAreaHeight As Integer = e.MarginBounds.Height
  175.                    Dim printAreaWidth As Integer = e.MarginBounds.Width
  176.                    Dim printAreaLeft As Integer = e.MarginBounds.Left
  177.                    Dim printAreaTop As Integer = e.MarginBounds.Top
  178.                    Dim headerHeight As Integer = dataGridView.ColumnHeadersHeight
  179.                    Dim rowHeight As Integer = dataGridView.Rows(0).Height
  180.  
  181.                    Dim gridWidth As Integer = dataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)
  182.                    Dim gridLeft As Integer = printAreaLeft + (printAreaWidth - gridWidth) \ 2
  183.  
  184.                    Dim titleSize As SizeF = e.Graphics.MeasureString(title, textFont)
  185.                    Dim titleLeft As Integer = gridLeft
  186.                    Dim titleTop As Integer = printAreaTop - CInt(titleSize.Height) - 20
  187.                    e.Graphics.DrawString(title, textFont, Brushes.Black, titleLeft, titleTop, New StringFormat() With {.Alignment = StringAlignment.Near})
  188.  
  189.                    Dim rowsPerPage As Integer = CInt(Math.Floor((printAreaHeight - headerHeight) / rowHeight))
  190.                    Dim rowIndex As Integer = printedRowsCount
  191.  
  192.                    Dim headerWidth As Integer = 0
  193.                    For Each column As DataGridViewColumn In dataGridView.Columns
  194.                        headerWidth += column.Width
  195.                    Next
  196.  
  197.                    Dim headerBounds As New Rectangle(gridLeft, printAreaTop + headerHeight, headerWidth, rowHeight)
  198.                    Using headerBackBrush As New SolidBrush(headerBackColor)
  199.                        e.Graphics.FillRectangle(headerBackBrush, headerBounds)
  200.  
  201.                        For Each column As DataGridViewColumn In dataGridView.Columns
  202.                            Dim cellBounds As New Rectangle(headerBounds.Left, headerBounds.Top, column.Width, headerBounds.Height)
  203.                            Using headerTextBrush As New SolidBrush(headerForeColor)
  204.                                e.Graphics.DrawString(column.HeaderText, textFont, headerTextBrush, cellBounds, New StringFormat() With {.Alignment = StringAlignment.Center})
  205.                            End Using
  206.                            headerBounds.X += column.Width
  207.                        Next
  208.                    End Using
  209.  
  210.                    While rowIndex < dataGridView.Rows.Count AndAlso rowIndex < printedRowsCount + rowsPerPage
  211.                        Dim row As DataGridViewRow = dataGridView.Rows(rowIndex)
  212.                        Dim cellIndex As Integer = 0
  213.  
  214.                        Dim currentRowBackColor As Color
  215.                        Dim currentRowForeColor As Color
  216.                        If rowIndex Mod 2 = 0 Then
  217.                            currentRowBackColor = rowBackColor
  218.                            currentRowForeColor = rowForeColor
  219.                        Else
  220.                            currentRowBackColor = rowBackColorAlternate
  221.                            currentRowForeColor = rowForeColorAlternate
  222.                        End If
  223.  
  224.                        While cellIndex < dataGridView.Columns.Count
  225.                            Dim cellBounds As New Rectangle(printAreaLeft + (gridLeft - dataGridView.Columns(cellIndex).Width), (printAreaTop + headerHeight + (rowIndex - printedRowsCount) * rowHeight) + headerBounds.Height * 2, dataGridView.Columns(cellIndex).Width, rowHeight)
  226.                            Using rowBackBrush As New SolidBrush(currentRowBackColor)
  227.                                e.Graphics.FillRectangle(rowBackBrush, cellBounds)
  228.                            End Using
  229.                            e.Graphics.DrawRectangle(Pens.LightGray, cellBounds)
  230.                            Using rowTextBrush As New SolidBrush(currentRowForeColor)
  231.                                e.Graphics.DrawString(row.Cells(cellIndex).FormattedValue.ToString(), textFont, rowTextBrush, cellBounds, New StringFormat())
  232.                            End Using
  233.                            printAreaLeft += dataGridView.Columns(cellIndex).Width
  234.                            cellIndex += 1
  235.                        End While
  236.  
  237.                        printAreaLeft = e.MarginBounds.Left
  238.                        rowIndex += 1
  239.                    End While
  240.  
  241.                    If rowIndex < dataGridView.Rows.Count Then
  242.                        printedRowsCount = rowIndex
  243.                        e.HasMorePages = True
  244.                    Else
  245.                        printedRowsCount = 0
  246.                        currentPageIndex = 0
  247.                        e.HasMorePages = False
  248.                    End If
  249.                End Sub
  250.  
  251.            Return printDocument
  252.  
  253.        End Function
  254.  
  255. #End Region
  256.  
  257.    End Module
  258.  
  259. End Namespace
  260.  
  261. #End Region
  262.  
En línea

@%$& #$ %&#$, ¡hay que decirlo más!.
Páginas: 1 ... 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 [56] 57 58 59 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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