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

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


  Mostrar Mensajes
Páginas: 1 2 [3] 4 5 6 7 8 9 10 11 12 13 14
21  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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.  
22  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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.  
23  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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.  
24  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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

25  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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)
26  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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.  
27  Programación / Programación General / Re: ¿Crees que definir el tipo de variable es útil o perjudicial? en: 9 Septiembre 2023, 14:45 pm
¿Crees que definir el tipo de variable es útil o perjudicial?

No es cuestión de creencias personales, perjudicial no es en ningún sentido, aunque en el contexto de un lenguaje de scripting el impacto puede ser mucho menos significativo (sobre todo si se está usando un editor de texto simple), pero, generalizando y ampliando la respuesta a otros lenguajes de programación, escribir código sin especificar de forma explícita el tipo de las variables/objetos solo sirve para reducir el tiempo de escritura del programador a costa de perjudicar la comprensión y claridad del código, entre otros inconvenientes en tiempo de compilación y de diseño, como imposibilitar la detección temprana de errores del depurador, e imposibilitar la resolución de un enlace estático para beneficiarse del autocompletado de código.

En resumen, y generalizando y ampliando de nuevo a otros lenguajes, puede considerarse (yo lo considero) una mala costumbre y propensa a cometer errores humanos. Puede resultar útil en escenarios donde pueda ser considerado más viable recurrir a la resolución de tipos en tiempo de ejecución (late-binding), pero creo que poco o nada más. Prefiero la claridad de código ante todo, definiendo de forma explícita el tipo de cada variable.

yo veo ese "var" y lo demás y me da una especie de ataque de nervios  :laugh:

Eso me pasa a mi cuando veo un código de C# escrito por otra persona y lleno de "var". Lo considero una costumbre horrible, pero al final es una cuestión de preferencias, y si el lenguaje ofrece esa posibilidad es para que haya gente que opte por la escritura de código basada en la inferencia de tipos. Además, por suerte y por muchos "var" que haya en un código de C# es algo que se soluciona de forma simple con dos clicks en la IDE de Visual Studio.

Saludos.
28  Sistemas Operativos / Windows / Re: Google bloqueado en: 8 Septiembre 2023, 15:46 pm
La pregunta es: ¿Puedo hacer que queden establecidos en forma permanente?

En caso de que sepas como hacerlo, puedes editar esos valores del registro y luego deshabilitar los permisos de escritura para tu usuario y para el usuario de sistema "SYSTEM" (puedes hacerlo de forma tediosa y tradicional, o de forma algo más guiada con SetACL Studio). Pero si dices que esos valores se vuelven a reestablecer al reiniciar el PC entonces cabría la posibilidad de que algún programa o el propio sistema operativo tire error o cause algún otro tipo de problema al intentar editar esos valores.

Así que te propongo como alternativa crear un archivo con extensión CMD con este contenido:

Archivo.cmd
Código
  1. @ECHO OFF
  2.  
  3. (
  4. REG.exe ADD "HKLM\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" /V "CallLegacyWCMPolicies" /T "REG_DWORD" /D "0x00000000" /F
  5. REG.exe ADD "HKLM\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" /V "ProxySettingsPerUser"  /T "REG_DWORD" /D "0x00000001" /F
  6. )1>NUL 2>&1
  7.  
  8. EXIT /B 0

Y colocarlo en la carpeta de los programas que se inician al iniciar Windows, ubicada en: "C:\Users\<TuNombreDeUsuario>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup", de esta forma esos valores de registro siempre se añadirán al iniciar sesión de usuario en Windows.

Nota: también puedes colocarlo en la carpeta "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup" si quieres que el script se inicie para todos los usuarios.

Saludos.
29  Informática / Software / Re: Acronis True Imagen full en: 7 Septiembre 2023, 21:30 pm
Elektro Enjuto
Amigo estoy esperando pues a mi casilla no ha llegado nada todavía - Gracias igual

Te envié un mensaje privado aquél mismo día.  :-\

Acabo de reenviarte el mensaje privado AHORA MISMO, revisa bien la bandeja de entrada por que el buzón no lo tienes lleno, el mensaje te ha llegado.

Un saludo!
30  Informática / Software / Re: WinRAR 6.23 // 32 y 64 bits en: 7 Septiembre 2023, 20:35 pm
una licencia ¿La has probado?

Me tomo la libertad de responderte yo para comentarte que RarLab nunca se ha preocupado de añadir protección antipiratería en WinRAR, en el sentido de que hay quien lleva usando el mismo archivo de licencia desde hace décadas con las versiones más recientes de WinRAR, y sin problemas de ningún tipo, así que si esa es tu preocupación puedes estar tranquilo al respecto, por que si una licencia funciona ahora, debería seguirá funcionando en el futuro como ha sido hasta ahora.

Por ese motivo, y conservando ya una licencia pirata, para poder actualizar WinRAR lo único que hace falta es descargar la nueva versión desde el sitio web oficial.
Páginas: 1 2 [3] 4 5 6 7 8 9 10 11 12 13 14
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines