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
11  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 09:28 am
Un algoritmo para volcar un texto de forma vertical.

Inspirado en este servicio: https://onlinetexttools.com/flip-text-vertically

Los resultados son idénticos o muy similares a estos:





UtilString.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' FlipTextVertically(String, VerticalFlipTextMode, Opt: Char) As String
  11.  
  12. #End Region
  13.  
  14. #End Region
  15.  
  16. #Region " Option Statements "
  17.  
  18. Option Strict On
  19. Option Explicit On
  20. Option Infer Off
  21.  
  22. #End Region
  23.  
  24. #Region " Imports "
  25.  
  26. Imports System.Collections.Generic
  27. Imports System.ComponentModel
  28. Imports System.Linq
  29. Imports System.Text
  30.  
  31. #End Region
  32.  
  33. #Region " String Util "
  34.  
  35. ' ReSharper disable once CheckNamespace
  36.  
  37. Namespace DevCase.Core.DataProcessing.Common
  38.  
  39.    Partial Public NotInheritable Class UtilString
  40.  
  41. #Region " Public Methods "
  42.  
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        ''' <summary>
  45.        ''' Transforms the source string into vertical text.
  46.        ''' </summary>
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        ''' <seealso href="https://onlinetexttools.com/flip-text-vertically"/>
  49.        ''' ----------------------------------------------------------------------------------------------------
  50.        ''' <param name="input">
  51.        ''' The input string to flip it vertically.
  52.        ''' <para></para>
  53.        ''' If this value is null, no changes are made to the string.
  54.        ''' </param>
  55.        '''
  56.        ''' <param name="flipMode">
  57.        ''' The vertical flip mode indicating how the text should be flipped.
  58.        ''' </param>
  59.        '''
  60.        ''' <param name="separatorChar">
  61.        ''' Optional. The character used to separate columns. Default is "|".
  62.        ''' </param>
  63.        ''' ----------------------------------------------------------------------------------------------------
  64.        ''' <returns>
  65.        ''' The resulting vertically flipped text.
  66.        ''' </returns>
  67.        ''' ----------------------------------------------------------------------------------------------------
  68.        <DebuggerStepThrough>
  69.        Public Shared Function FlipTextVertically(input As String, flipMode As VerticalFlipTextMode,
  70.                                                  Optional separatorChar As Char = "|"c) As String
  71.  
  72.            If String.IsNullOrEmpty(input) Then
  73.                Return input
  74.            End If
  75.  
  76.            If separatorChar.Equals(Nothing) Then
  77.                Throw New ArgumentNullException(paramName:=NameOf(separatorChar))
  78.            End If
  79.  
  80.            Select Case flipMode
  81.  
  82.                Case VerticalFlipTextMode.CharByChar
  83.                    Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
  84.                    Dim maxLength As Integer = lines.Max(Function(line) line.Length)
  85.                    Dim verticalText As New StringBuilder()
  86.                    For i As Integer = 0 To maxLength - 1
  87.                        For j As Integer = 0 To lines.Length - 1
  88.                            If i < lines(j).Length Then
  89.                                verticalText.Append(lines(j)(i))
  90.                            Else
  91.                                verticalText.Append(" "c)
  92.                            End If
  93.                            If j < lines.Length - 1 Then
  94.                                verticalText.Append($" {separatorChar} ")
  95.                            End If
  96.                        Next
  97.                        verticalText.AppendLine()
  98.                    Next
  99.                    Return verticalText.ToString()
  100.  
  101.                Case VerticalFlipTextMode.WordByWord
  102.                    Dim lines As String() = input.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
  103.                    Dim wordsPerLine As New List(Of List(Of String))()
  104.                    For Each line As String In lines
  105.                        Dim words As String() = line.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
  106.                        wordsPerLine.Add(words.ToList())
  107.                    Next
  108.                    Dim maxLength As Integer = wordsPerLine.Max(Function(words) words.Count)
  109.                    Dim verticalText As New StringBuilder()
  110.                    For i As Integer = 0 To maxLength - 1
  111.                        For j As Integer = 0 To wordsPerLine.Count - 1
  112.                            Dim words As List(Of String) = wordsPerLine(j)
  113.                            If i < words.Count Then
  114.                                verticalText.Append(words(i).PadRight(words.Max(Function(word) word.Length)))
  115.                            Else
  116.                                verticalText.Append(" ".PadRight(words.Max(Function(word) word.Length)))
  117.                            End If
  118.                            If j < wordsPerLine.Count - 1 Then
  119.                                verticalText.Append($" {separatorChar} ")
  120.                            End If
  121.                        Next
  122.                        verticalText.AppendLine()
  123.                    Next
  124.                    Return verticalText.ToString()
  125.  
  126.                Case VerticalFlipTextMode.SentenceBySentence
  127.                    Dim GetMaxSentences As Func(Of String(), Integer) =
  128.                    Function(_lines As String()) As Integer
  129.                        Dim _maxSentences As Integer = 0
  130.                        For Each line As String In _lines
  131.                            Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries)
  132.                            _maxSentences = System.Math.Max(_maxSentences, sentences.Length)
  133.                        Next
  134.                        Return _maxSentences
  135.                    End Function
  136.  
  137.                    Dim GetColumnWidths As Func(Of String(), Integer, Integer()) =
  138.                    Function(_lines As String(), _maxSentences As Integer) As Integer()
  139.                        Dim _columnWidths As Integer() = New Integer(_lines.Length - 1) {}
  140.                        For i As Integer = 0 To _lines.Length - 1
  141.                            Dim line As String = _lines(i)
  142.                            Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries)
  143.                            Dim maxWidth As Integer = 0
  144.                            For j As Integer = 0 To System.Math.Min(_maxSentences, sentences.Length) - 1
  145.                                maxWidth = System.Math.Max(maxWidth, sentences(j).Trim().Length)
  146.                            Next
  147.                            _columnWidths(i) = maxWidth
  148.                        Next
  149.                        Return _columnWidths
  150.                    End Function
  151.  
  152.                    Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
  153.                    Dim maxSentences As Integer = GetMaxSentences(lines)
  154.                    Dim columnWidths As Integer() = GetColumnWidths(lines, maxSentences)
  155.                    Dim output As New StringBuilder()
  156.  
  157.                    For i As Integer = 0 To maxSentences - 1
  158.                        For j As Integer = 0 To lines.Length - 1
  159.                            Dim line As String = lines(j)
  160.                            Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries)
  161.                            Dim sentence As String = ""
  162.                            If i < sentences.Length Then
  163.                                sentence = sentences(i).Trim() & "."
  164.                            End If
  165.                            Dim column As String = sentence.PadRight(columnWidths(j) + 1)
  166.                            output.Append(column)
  167.                            If j < lines.Length - 1 Then
  168.                                output.Append($" {separatorChar} ")
  169.                            End If
  170.                        Next
  171.                        output.AppendLine()
  172.                    Next
  173.                    Return output.ToString()
  174.  
  175.                Case Else
  176.                    Throw New InvalidEnumArgumentException(argumentName:=NameOf(flipMode), invalidValue:=flipMode, enumClass:=GetType(VerticalFlipTextMode))
  177.  
  178.            End Select
  179.  
  180.        End Function
  181.  
  182. #End Region
  183.  
  184.    End Class
  185.  
  186. End Namespace
  187.  
  188. #End Region
  189.  



VerticalFlipTextMode.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict Off
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. #End Region
  17.  
  18. #Region " VerticalFlipTextMode "
  19.  
  20. ' ReSharper disable once CheckNamespace
  21.  
  22. Namespace DevCase.Core.DataProcessing.Common
  23.  
  24.    ''' ----------------------------------------------------------------------------------------------------
  25.    ''' <summary>
  26.    ''' Specifies how the text should be flipped when using <see cref="UtilString.FlipTextVertically"/> function.
  27.    ''' </summary>
  28.    ''' ----------------------------------------------------------------------------------------------------
  29.    Public Enum VerticalFlipTextMode As Integer
  30.  
  31.        ''' <summary>
  32.        ''' Divides the text into characters.        
  33.        ''' That is, all the characters from every text row get rearranged in columns.
  34.        ''' </summary>
  35.        CharByChar
  36.  
  37.        ''' <summary>
  38.        ''' Divides the text into words.
  39.        ''' <para></para>
  40.        ''' That is, all the words from every text row get rearranged in columns.
  41.        ''' </summary>
  42.        WordByWord
  43.  
  44.        ''' <summary>
  45.        ''' Divides the text into sentences.
  46.        ''' <para></para>
  47.        ''' That is, if you have several sentences in one line,
  48.        ''' then after rewriting them vertically, they will appear in a single column.
  49.        ''' </summary>
  50.        SentenceBySentence
  51.  
  52.    End Enum
  53.  
  54. End Namespace
  55.  
  56. #End Region
  57.  
12  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 09:20 am
Un algoritmo para justificar un string.

Me he inspirado en este servicio online: https://onlinetexttools.com/justify-text

Ejemplo de uso:
Código
  1. Dim input As String =
  2. "About 20% of oxygen is produced by the Amazon rainforest. The Earth's atmosphere is about 78 percent nitrogen, 21 percent oxygen, and about 1 percent other gases.
  3.  
  4. For the existence of most organisms on the planet, oxygen is a necessary element, it provides the body with energy and removes carbon dioxide. Fortunately, plants constantly replenish the oxygen level of our planet thanks to photosynthesis. During this process, carbon dioxide and water are converted into energy, releasing oxygen as a byproduct.
  5.  
  6. The Amazon rainforest covers 5.5 million square kilometers (2.1 million square miles), recycling much of the Earth's oxygen while absorbing large amounts of carbon dioxide."
  7.  
  8. Dim lineLength As Integer = 50
  9.  
  10. Dim result As String = UtilString.JustifyText(input, lineLength, justifyLastLine:=True)
  11.  
  12. Console.WriteLine(result)

Salida:
Código:
About  20%  of  oxygen  is  produced by the Amazon
rainforest.  The  Earth's  atmosphere  is about 78
percent  nitrogen,  21 percent oxygen, and about 1
percent                other                gases.

For   the   existence   of   most   organisms   on
the  planet,  oxygen  is  a  necessary element, it
provides  the  body with energy and removes carbon
dioxide.  Fortunately, plants constantly replenish
the   oxygen   level   of  our  planet  thanks  to
photosynthesis.   During   this   process,  carbon
dioxide  and  water  are  converted  into  energy,
releasing      oxygen      as     a     byproduct.

The   Amazon   rainforest   covers   5.5   million
square  kilometers  (2.1  million  square  miles),
recycling   much   of  the  Earth's  oxygen  while
absorbing   large   amounts   of  carbon  dioxide.


Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 13-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' JustifyText(String, Integer, Opt: Boolean) As String
  11.  
  12. #End Region
  13.  
  14. #End Region
  15.  
  16. #Region " Option Statements "
  17.  
  18. Option Strict On
  19. Option Explicit On
  20. Option Infer Off
  21.  
  22. #End Region
  23.  
  24. #Region " Imports "
  25.  
  26. Imports System.Collections.ObjectModel
  27. Imports System.Text
  28.  
  29. #End Region
  30.  
  31. #Region " String Util "
  32.  
  33. ' ReSharper disable once CheckNamespace
  34.  
  35. Namespace DevCase.Core.DataProcessing.Common
  36.  
  37.    Partial Public NotInheritable Class UtilString
  38.  
  39. #Region " Public Methods "
  40.  
  41.        ''' ----------------------------------------------------------------------------------------------------
  42.        ''' <summary>
  43.        ''' Justifies the input text by adjusting the line width and spacing between words.
  44.        ''' </summary>
  45.        ''' ----------------------------------------------------------------------------------------------------
  46.        ''' <example> This is a code example.
  47.        ''' <code language="VB.NET">
  48.        ''' Dim input As String =
  49.        ''' "About 20% of oxygen is produced by the Amazon rainforest. The Earth's atmosphere is about 78 percent nitrogen, 21 percent oxygen, and about 1 percent other gases.
  50.        '''
  51.        ''' For the existence of most organisms on the planet, oxygen is a necessary element, it provides the body with energy and removes carbon dioxide. Fortunately, plants constantly replenish the oxygen level of our planet thanks to photosynthesis. During this process, carbon dioxide and water are converted into energy, releasing oxygen as a byproduct.
  52.        '''
  53.        ''' The Amazon rainforest covers 5.5 million square kilometers (2.1 million square miles), recycling much of the Earth's oxygen while absorbing large amounts of carbon dioxide."
  54.        '''
  55.        ''' Dim lineLength As Integer = 50
  56.        '''
  57.        ''' Dim result As String = JustifyText(input, lineLength, justifyLastLine:=True)
  58.        '''
  59.        ''' Console.WriteLine(result)
  60.        ''' </code>
  61.        ''' </example>
  62.        ''' ----------------------------------------------------------------------------------------------------
  63.        ''' <param name="input">
  64.        ''' The input text.
  65.        ''' </param>
  66.        '''
  67.        ''' <param name="length">
  68.        ''' The desired length for each text line.
  69.        ''' </param>
  70.        '''
  71.        ''' <param name="justifyLastLine">
  72.        ''' Optional. Indicates whether to justify the last line of the paragraphs.
  73.        ''' <para></para>
  74.        ''' Default value is: False.
  75.        ''' </param>
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <returns>
  78.        ''' The resulting justified text.
  79.        ''' </returns>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        <DebuggerStepThrough>
  82.        Public Shared Function JustifyText(input As String, length As Integer,
  83.                                           Optional justifyLastLine As Boolean = False) As String
  84.  
  85.  
  86.            Dim paragraphs As String() = input.Split({Environment.NewLine}, StringSplitOptions.None)
  87.            Dim paragraphsCount As Integer = paragraphs.Length
  88.  
  89.            Dim justifiedLines As New Collection(Of String)()
  90.  
  91.            For paragraphIdx As Integer = 0 To paragraphsCount - 1
  92.  
  93.                Dim words As String() = paragraphs(paragraphIdx).Split(" "c)
  94.                Dim lines As New Collection(Of String)()
  95.  
  96.                Dim currentLine As New StringBuilder()
  97.                Dim currentLineLength As Integer = 0
  98.  
  99.                For Each word As String In words
  100.                    Dim wordLength As Integer = word.Length
  101.  
  102.                    If currentLineLength + wordLength <= length Then
  103.                        currentLine.Append(word & " ")
  104.                        currentLineLength += wordLength + 1
  105.  
  106.                    Else
  107.                        lines.Add(currentLine.ToString().Trim())
  108.                        currentLine = New StringBuilder(word & " ")
  109.                        currentLineLength = wordLength + 1
  110.                    End If
  111.  
  112.                    If wordLength > length Then
  113.                        Dim remainingWord As String = word
  114.                        While remainingWord.Length > length
  115.                            lines.Add(remainingWord.Substring(0, length))
  116.                            remainingWord = remainingWord.Substring(length)
  117.                        End While
  118.  
  119.                        If remainingWord.Length > 0 Then
  120.                            lines.Add(remainingWord)
  121.                        End If
  122.                    End If
  123.  
  124.                Next
  125.  
  126.                lines.Add(currentLine.ToString().Trim())
  127.  
  128.                For i As Integer = 0 To lines.Count - 1
  129.                    Dim line As String = lines(i)
  130.  
  131.                    If (i = lines.Count - 1) AndAlso Not justifyLastLine Then
  132.                        justifiedLines.Add(line)
  133.                        Continue For
  134.                    End If
  135.  
  136.                    Dim lineLength As Integer = line.Length
  137.                    Dim wordsInLine As String() = line.Split(" "c)
  138.                    Dim wordsCount As Integer = wordsInLine.Length
  139.  
  140.                    If wordsCount > 1 Then
  141.                        Dim remainingSpaces As Integer = length - line.Replace(" "c, "").Length
  142.                        Dim spacesPerGap As Integer = remainingSpaces \ (wordsCount - 1)
  143.                        Dim extraSpaces As Integer = remainingSpaces Mod (wordsCount - 1)
  144.  
  145.                        Dim justifiedLine As New StringBuilder(wordsInLine(0))
  146.                        For j As Integer = 1 To wordsCount - 1
  147.                            justifiedLine.Append(" "c, spacesPerGap)
  148.                            If j <= extraSpaces Then
  149.                                justifiedLine.Append(" "c)
  150.                            End If
  151.                            justifiedLine.Append(wordsInLine(j))
  152.                        Next
  153.  
  154.                        line = justifiedLine.ToString()
  155.                    End If
  156.  
  157.                    justifiedLines.Add(line)
  158.                Next
  159.  
  160.                If Not justifyLastLine AndAlso justifiedLines.Count > 1 Then
  161.                    justifiedLines(justifiedLines.Count - 1) = justifiedLines(justifiedLines.Count - 1).TrimEnd()
  162.                End If
  163.  
  164.            Next
  165.  
  166.            Return String.Join(Environment.NewLine, justifiedLines)
  167.        End Function
  168.  
  169. #End Region
  170.  
  171.    End Class
  172.  
  173. End Namespace
  174.  
  175. #End Region
  176.  
13  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 09:12 am
Un código para convertir el texto de un string a superscript y vice-versa.

Ejemplos de uso:

Código
  1. Dim input As String = "The ideal temperature for sleeping is 18.3 degrees Celsius (65 degrees Fahrenheit)"
  2. Dim result As String =  ConvertToSuperscript(input)

Código
  1. Dim input As String = "&#7488;&#688;&#7497; &#8305;&#7496;&#7497;&#7491;&#737; &#7511;&#7497;&#7504;&#7510;&#7497;&#691;&#7491;&#7511;&#7512;&#691;&#7497; &#7584;&#7506;&#691; &#738;&#737;&#7497;&#7497;&#7510;&#8305;&#8319;&#7501; &#8305;&#738; ¹&#8312;&#8901;³ &#7496;&#7497;&#7501;&#691;&#7497;&#7497;&#738; &#5222;&#7497;&#737;&#738;&#8305;&#7512;&#738; &#8317;&#8310;&#8309; &#7496;&#7497;&#7501;&#691;&#7497;&#7497;&#738; &#11777;&#7491;&#688;&#691;&#7497;&#8319;&#688;&#7497;&#8305;&#7511;&#8318;"
  2. Dim result As String =  ConvertFromSuperscript(input)





Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' ConvertToSuperscript(String) As String
  11. ' ConvertFromSuperscript(String) As String
  12.  
  13. #End Region
  14.  
  15. #End Region
  16.  
  17. #Region " Option Statements "
  18.  
  19. Option Strict On
  20. Option Explicit On
  21. Option Infer Off
  22.  
  23. #End Region
  24.  
  25. #Region " Imports "
  26.  
  27. Imports System.Collections.Generic
  28. Imports System.ComponentModel
  29. Imports System.Text
  30.  
  31. #End Region
  32.  
  33. #Region " String Util "
  34.  
  35. ' ReSharper disable once CheckNamespace
  36.  
  37. Namespace DevCase.Core.DataProcessing.Common
  38.  
  39.    Partial Public NotInheritable Class UtilString
  40.  
  41. #Region " Private Fields "
  42.  
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        ''' <summary>
  45.        ''' Character map used by functions that converts ASCII characters to its Superscript forms.
  46.        ''' </summary>
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        Private Shared charMapAsciiToSuperscript As Dictionary(Of Char, Char)
  49.  
  50.        ''' ----------------------------------------------------------------------------------------------------
  51.        ''' <summary>
  52.        ''' Character map used by functions that converts Superscript characters to its ASCII forms.
  53.        ''' </summary>
  54.        ''' ----------------------------------------------------------------------------------------------------
  55.        Private Shared charMapSuperscriptToAscii As List(Of KeyValuePair(Of Char, Char))
  56.  
  57. #End Region
  58.  
  59. #Region " Public Methods "
  60.  
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        ''' <summary>
  63.        ''' Converts the characters in the input string to their corresponding superscript forms.
  64.        ''' <para></para>
  65.        ''' Letters in a superscript text are half the normal letter size and are placed above the middle of a text line.
  66.        ''' For example, the word "Sunshine" in superscript looks like this: "&#5382;&#7512;&#8319;&#738;&#688;&#8305;&#8319;&#7497;".
  67.        ''' <para></para>
  68.        ''' Superscripts are often used in mathematics to denote powers of a number, such as "x²" or "y&#7504;".
  69.        ''' They are also often used to write ordinal numbers, for example, 1&#738;&#7511;, 2&#8319;&#7496;, 3&#691;&#7496;, 4&#7511;&#688;, and so on.
  70.        ''' <para></para>
  71.        ''' Superscript (Wikipedia): <see href="https://en.wikipedia.org/wiki/Subscript_and_superscript"/>
  72.        ''' </summary>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        ''' <example> This is a code example.
  75.        ''' <code language="VB.NET">
  76.        ''' Dim input As String = "The ideal temperature for sleeping is 18.3 degrees Celsius (65 degrees Fahrenheit)"
  77.        ''' Dim result As String =  ConvertToSuperscript(input)
  78.        ''' Console.WriteLine(result)
  79.        ''' </code>
  80.        ''' </example>
  81.        ''' ----------------------------------------------------------------------------------------------------
  82.        ''' <param name="input">
  83.        ''' The input string to convert to superscript.
  84.        ''' </param>
  85.        ''' ----------------------------------------------------------------------------------------------------
  86.        ''' <returns>
  87.        ''' The input string converted to their corresponding superscript forms.
  88.        ''' </returns>
  89.        ''' ----------------------------------------------------------------------------------------------------
  90.        <DebuggerStepThrough>
  91.        Public Shared Function ConvertToSuperscript(input As String) As String
  92.  
  93.            If String.IsNullOrWhiteSpace(input) Then
  94.                Throw New ArgumentNullException(paramName:=NameOf(input))
  95.            End If
  96.  
  97.            If UtilString.charMapAsciiToSuperscript Is Nothing Then
  98.                UtilString.charMapAsciiToSuperscript =
  99.                    New Dictionary(Of Char, Char)(EqualityComparer(Of Char).Default) From {
  100.                        {"0"c, "&#8304;"c}, {"1"c, "¹"c}, {"2"c, "²"c}, {"3"c, "³"c}, {"4"c, "&#8308;"c},
  101.                        {"5"c, "&#8309;"c}, {"6"c, "&#8310;"c}, {"7"c, "&#8311;"c}, {"8"c, "&#8312;"c}, {"9"c, "&#8313;"c},
  102.                        {"+"c, "&#8314;"c}, {"-"c, "&#8315;"c}, {"="c, "&#8316;"c}, {"("c, "&#8317;"c}, {")"c, "&#8318;"c},
  103.                        {"."c, "&#8901;"c}, {"·"c, "&#729;"c},
  104.                        {"a"c, "&#7491;"c}, {"b"c, "&#7495;"c}, {"c"c, "&#7580;"c}, {"d"c, "&#7496;"c}, {"e"c, "&#7497;"c},
  105.                        {"f"c, "&#7584;"c}, {"g"c, "&#7501;"c}, {"h"c, "&#688;"c}, {"i"c, "&#8305;"c}, {"j"c, "&#690;"c},
  106.                        {"k"c, "&#7503;"c}, {"l"c, "&#737;"c}, {"m"c, "&#7504;"c}, {"n"c, "&#8319;"c}, {"o"c, "&#7506;"c},
  107.                        {"p"c, "&#7510;"c}, {"q"c, "&#1785;"c}, {"r"c, "&#691;"c}, {"s"c, "&#738;"c}, {"t"c, "&#7511;"c},
  108.                        {"u"c, "&#7512;"c}, {"v"c, "&#7515;"c}, {"w"c, "&#695;"c}, {"x"c, "&#739;"c}, {"y"c, "&#696;"c},
  109.                        {"z"c, "&#7611;"c},
  110.                        {"A"c, "&#7468;"c}, {"B"c, "&#7470;"c}, {"C"c, "&#5222;"c}, {"D"c, "&#7472;"c}, {"E"c, "&#7473;"c},
  111.                        {"F"c, "&#11777;"c}, {"G"c, "&#7475;"c}, {"H"c, "&#7476;"c}, {"I"c, "&#7477;"c}, {"J"c, "&#7478;"c},
  112.                        {"K"c, "&#7479;"c}, {"L"c, "&#7480;"c}, {"M"c, "&#7481;"c}, {"N"c, "&#7482;"c}, {"O"c, "&#7484;"c},
  113.                        {"P"c, "&#7486;"c}, {"Q"c, "&#5227;"c}, {"R"c, "&#7487;"c}, {"S"c, "&#5382;"c}, {"T"c, "&#7488;"c},
  114.                        {"U"c, "&#7489;"c}, {"V"c, "&#11389;"c}, {"W"c, "&#7490;"c}, {"X"c, "&#5501;"c}, {"Y"c, "&#696;"c},
  115.                        {"Z"c, "&#5702;"c}
  116.                    }
  117.            End If
  118.  
  119.            Dim sb As New StringBuilder(input.Length)
  120.            For Each c As Char In input
  121.                Dim value As Char = Nothing
  122.                If UtilString.charMapAsciiToSuperscript.TryGetValue(c, value) Then
  123.                    sb.Append(value)
  124.                Else
  125.                    sb.Append(c)
  126.                End If
  127.            Next
  128.            Return sb.ToString()
  129.        End Function
  130.  
  131.        ''' ----------------------------------------------------------------------------------------------------
  132.        ''' <summary>
  133.        ''' Converts the characters in the input string to their corresponding superscript forms.
  134.        ''' <para></para>
  135.        ''' Letters in a superscript text are half the normal letter size and are placed above the middle of a text line.
  136.        ''' For example, the word "Sunshine" in superscript looks like this: "&#5382;&#7512;&#8319;&#738;&#688;&#8305;&#8319;&#7497;".
  137.        ''' <para></para>
  138.        ''' Superscripts are often used in mathematics to denote powers of a number, such as "x²" or "y&#7504;".
  139.        ''' They are also often used to write ordinal numbers, for example, 1&#738;&#7511;, 2&#8319;&#7496;, 3&#691;&#7496;, 4&#7511;&#688;, and so on.
  140.        ''' <para></para>
  141.        ''' Superscript (Wikipedia): <see href="https://en.wikipedia.org/wiki/Subscript_and_superscript"/>
  142.        ''' </summary>
  143.        ''' ----------------------------------------------------------------------------------------------------
  144.        ''' <example> This is a code example.
  145.        ''' <code language="VB.NET">
  146.        ''' Dim input As String = "&#7488;&#688;&#7497; &#8305;&#7496;&#7497;&#7491;&#737; &#7511;&#7497;&#7504;&#7510;&#7497;&#691;&#7491;&#7511;&#7512;&#691;&#7497; &#7584;&#7506;&#691; &#738;&#737;&#7497;&#7497;&#7510;&#8305;&#8319;&#7501; &#8305;&#738; ¹&#8312;&#8901;³ &#7496;&#7497;&#7501;&#691;&#7497;&#7497;&#738; &#5222;&#7497;&#737;&#738;&#8305;&#7512;&#738; &#8317;&#8310;&#8309; &#7496;&#7497;&#7501;&#691;&#7497;&#7497;&#738; &#11777;&#7491;&#688;&#691;&#7497;&#8319;&#688;&#7497;&#8305;&#7511;&#8318;"
  147.        ''' Dim result As String =  ConvertFromSuperscript(input)
  148.        ''' Console.WriteLine(result)
  149.        ''' </code>
  150.        ''' </example>
  151.        ''' ----------------------------------------------------------------------------------------------------
  152.        ''' <param name="input">
  153.        ''' The input string to convert to superscript.
  154.        ''' </param>
  155.        ''' ----------------------------------------------------------------------------------------------------
  156.        ''' <returns>
  157.        ''' The input string converted to their corresponding superscript forms.
  158.        ''' </returns>
  159.        ''' ----------------------------------------------------------------------------------------------------
  160.        <DebuggerStepThrough>
  161.        Public Shared Function ConvertFromSuperscript(input As String) As String
  162.  
  163.            If String.IsNullOrWhiteSpace(input) Then
  164.                Throw New ArgumentNullException(paramName:=NameOf(input))
  165.            End If
  166.  
  167.            If UtilString.charMapSuperscriptToAscii Is Nothing Then
  168.                UtilString.charMapSuperscriptToAscii =
  169.                    New List(Of KeyValuePair(Of Char, Char)) From {
  170.                        {New KeyValuePair(Of Char, Char)("&#8304;"c, "0"c)},
  171.                        {New KeyValuePair(Of Char, Char)("¹"c, "1"c)},
  172.                        {New KeyValuePair(Of Char, Char)("²"c, "2"c)},
  173.                        {New KeyValuePair(Of Char, Char)("³"c, "3"c)},
  174.                        {New KeyValuePair(Of Char, Char)("&#8308;"c, "4"c)},
  175.                        {New KeyValuePair(Of Char, Char)("&#8309;"c, "5"c)},
  176.                        {New KeyValuePair(Of Char, Char)("&#8310;"c, "6"c)},
  177.                        {New KeyValuePair(Of Char, Char)("&#8311;"c, "7"c)},
  178.                        {New KeyValuePair(Of Char, Char)("&#8312;"c, "8"c)},
  179.                        {New KeyValuePair(Of Char, Char)("&#8313;"c, "9"c)},
  180.                        {New KeyValuePair(Of Char, Char)("&#8314;"c, "+"c)},
  181.                        {New KeyValuePair(Of Char, Char)("&#8315;"c, "-"c)},
  182.                        {New KeyValuePair(Of Char, Char)("&#8316;"c, "="c)},
  183.                        {New KeyValuePair(Of Char, Char)("&#8317;"c, "("c)},
  184.                        {New KeyValuePair(Of Char, Char)("&#8318;"c, ")"c)},
  185.                        {New KeyValuePair(Of Char, Char)("&#8901;"c, "."c)},
  186.                        {New KeyValuePair(Of Char, Char)("&#729;"c, "·"c)},
  187.                        {New KeyValuePair(Of Char, Char)("&#7491;"c, "a"c)},
  188.                        {New KeyValuePair(Of Char, Char)("&#7495;"c, "b"c)},
  189.                        {New KeyValuePair(Of Char, Char)("&#7580;"c, "c"c)},
  190.                        {New KeyValuePair(Of Char, Char)("&#7496;"c, "d"c)},
  191.                        {New KeyValuePair(Of Char, Char)("&#7497;"c, "e"c)},
  192.                        {New KeyValuePair(Of Char, Char)("&#7584;"c, "f"c)},
  193.                        {New KeyValuePair(Of Char, Char)("&#7501;"c, "g"c)},
  194.                        {New KeyValuePair(Of Char, Char)("&#688;"c, "h"c)},
  195.                        {New KeyValuePair(Of Char, Char)("&#8305;"c, "i"c)},
  196.                        {New KeyValuePair(Of Char, Char)("&#690;"c, "j"c)},
  197.                        {New KeyValuePair(Of Char, Char)("&#7503;"c, "k"c)},
  198.                        {New KeyValuePair(Of Char, Char)("&#737;"c, "l"c)},
  199.                        {New KeyValuePair(Of Char, Char)("&#7504;"c, "m"c)},
  200.                        {New KeyValuePair(Of Char, Char)("&#8319;"c, "n"c)},
  201.                        {New KeyValuePair(Of Char, Char)("&#7506;"c, "o"c)},
  202.                        {New KeyValuePair(Of Char, Char)("&#7510;"c, "p"c)},
  203.                        {New KeyValuePair(Of Char, Char)("&#1785;"c, "q"c)},
  204.                        {New KeyValuePair(Of Char, Char)("&#691;"c, "r"c)},
  205.                        {New KeyValuePair(Of Char, Char)("&#738;"c, "s"c)},
  206.                        {New KeyValuePair(Of Char, Char)("&#7511;"c, "t"c)},
  207.                        {New KeyValuePair(Of Char, Char)("&#7512;"c, "u"c)},
  208.                        {New KeyValuePair(Of Char, Char)("&#7515;"c, "v"c)},
  209.                        {New KeyValuePair(Of Char, Char)("&#695;"c, "w"c)},
  210.                        {New KeyValuePair(Of Char, Char)("&#739;"c, "x"c)},
  211.                        {New KeyValuePair(Of Char, Char)("&#696;"c, "y"c)},
  212.                        {New KeyValuePair(Of Char, Char)("&#7611;"c, "z"c)},
  213.                        {New KeyValuePair(Of Char, Char)("&#7468;"c, "A"c)},
  214.                        {New KeyValuePair(Of Char, Char)("&#7470;"c, "B"c)},
  215.                        {New KeyValuePair(Of Char, Char)("&#5222;"c, "C"c)},
  216.                        {New KeyValuePair(Of Char, Char)("&#7472;"c, "D"c)},
  217.                        {New KeyValuePair(Of Char, Char)("&#7473;"c, "E"c)},
  218.                        {New KeyValuePair(Of Char, Char)("&#11777;"c, "F"c)},
  219.                        {New KeyValuePair(Of Char, Char)("&#7475;"c, "G"c)},
  220.                        {New KeyValuePair(Of Char, Char)("&#7476;"c, "H"c)},
  221.                        {New KeyValuePair(Of Char, Char)("&#7477;"c, "I"c)},
  222.                        {New KeyValuePair(Of Char, Char)("&#7478;"c, "J"c)},
  223.                        {New KeyValuePair(Of Char, Char)("&#7479;"c, "K"c)},
  224.                        {New KeyValuePair(Of Char, Char)("&#7480;"c, "L"c)},
  225.                        {New KeyValuePair(Of Char, Char)("&#7481;"c, "M"c)},
  226.                        {New KeyValuePair(Of Char, Char)("&#7482;"c, "N"c)},
  227.                        {New KeyValuePair(Of Char, Char)("&#7484;"c, "O"c)},
  228.                        {New KeyValuePair(Of Char, Char)("&#7486;"c, "P"c)},
  229.                        {New KeyValuePair(Of Char, Char)("&#5227;"c, "Q"c)},
  230.                        {New KeyValuePair(Of Char, Char)("&#7487;"c, "R"c)},
  231.                        {New KeyValuePair(Of Char, Char)("&#5382;"c, "S"c)},
  232.                        {New KeyValuePair(Of Char, Char)("&#7488;"c, "T"c)},
  233.                        {New KeyValuePair(Of Char, Char)("&#7489;"c, "U"c)},
  234.                        {New KeyValuePair(Of Char, Char)("&#11389;"c, "V"c)},
  235.                        {New KeyValuePair(Of Char, Char)("&#7490;"c, "W"c)},
  236.                        {New KeyValuePair(Of Char, Char)("&#5501;"c, "X"c)},
  237.                        {New KeyValuePair(Of Char, Char)("&#696;"c, "Y"c)},
  238.                        {New KeyValuePair(Of Char, Char)("&#5702;"c, "Z"c)}
  239.                    }
  240.            End If
  241.  
  242.            Dim defaultPair As New KeyValuePair(Of Char, Char)
  243.            Dim sb As New StringBuilder(input.Length)
  244.            For Each c As Char In input
  245.                Dim pair As KeyValuePair(Of Char, Char) = charMapSuperscriptToAscii.Find(Function(kv) kv.Key = c)
  246.                If Not pair.Equals(defaultPair) Then
  247.                    sb.Append(pair.Value)
  248.                Else
  249.                    sb.Append(c)
  250.                End If
  251.            Next
  252.            Return sb.ToString()
  253.        End Function
  254.  
  255. #End Region
  256.  
  257.    End Class
  258.  
  259. End Namespace
  260.  
  261. #End Region
  262.  
14  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 09:05 am
CONTINUACIÓN DEL CÓDIGO DE ARRIBA ☝️☝️☝️



UnicodeAlphabeticCharacterSets.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-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 " UnicodeAlphabeticCharacterSets "
  15.  
  16. ' ReSharper disable once CheckNamespace
  17.  
  18. Namespace DevCase.Core.DataProcessing.Common
  19.  
  20.    ''' ----------------------------------------------------------------------------------------------------
  21.    ''' <summary>
  22.    ''' Specifies a Unicode alphabetic character set.
  23.    ''' <para></para>
  24.    ''' This enum is used by <see cref="UtilString.ConvertToUnicodeLetters"/> function.
  25.    ''' </summary>
  26.    ''' ----------------------------------------------------------------------------------------------------
  27.    ''' <remarks>
  28.    ''' The Unicode character sets are standardized sets of characters that cover
  29.    ''' various scripts and symbols used in written languages worldwide.
  30.    ''' <para></para>
  31.    ''' Unicode provides a unique code point for each character, ensuring interoperability and
  32.    ''' compatibility across different platforms and systems.
  33.    ''' <para></para>
  34.    ''' The alphabetic character sets defined in this enumeration represent
  35.    ''' specific stylistic variations of alphabetic characters used in mathematics and typography.
  36.    ''' <para></para>
  37.    ''' These character sets are commonly used in scientific and mathematical contexts,
  38.    ''' as well as in typography and font design.
  39.    ''' <para></para>
  40.    ''' They allow for precise representation of stylized alphabetic characters
  41.    ''' in various mathematical equations, formulas, and text layouts.
  42.    ''' </remarks>
  43.    ''' ----------------------------------------------------------------------------------------------------
  44.    Public Enum UnicodeAlphabeticCharacterSets
  45.  
  46.        ''' <summary>
  47.        ''' Unicode symbols from the 'Mathematical Bold Italic' character set
  48.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B),
  49.        ''' representing the alphabet letters from 'a' to 'Z'.
  50.        ''' <para></para>
  51.        ''' e.g., 'A': '&#119912;', 'a': '&#119938;'.
  52.        ''' </summary>
  53.        MathematicalBoldItalic
  54.  
  55.        ''' <summary>
  56.        ''' Unicode symbols from the 'Mathematical Bold Script' character set
  57.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503),
  58.        ''' representing the alphabet letters from 'a' to 'Z'.
  59.        ''' <para></para>
  60.        ''' e.g., 'A': '&#120016;', 'a': '&#120042;'.
  61.        ''' </summary>
  62.        MathematicalBoldScript
  63.  
  64.        ''' <summary>
  65.        ''' Unicode symbols from the 'Mathematical Italic' character set
  66.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467),
  67.        ''' representing the alphabet letters from 'a' to 'Z'.
  68.        ''' <para></para>
  69.        ''' e.g., 'A': '&#119860;', 'a': '&#119886;'.
  70.        ''' </summary>
  71.        MathematicalItalic
  72.  
  73.        ''' <summary>
  74.        ''' Unicode symbols from the 'Sans-Serif Bold Italic' character set
  75.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F),
  76.        ''' representing the alphabet letters from 'a' to 'Z'.
  77.        ''' <para></para>
  78.        ''' e.g., 'A': '&#120380;', 'a': '&#120406;'.
  79.        ''' </summary>
  80.        SansSerifBoldItalic
  81.  
  82.        ''' <summary>
  83.        ''' Unicode symbols from the 'Sans-Serif Italic' character set
  84.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B),
  85.        ''' representing the alphabet letters from 'a' to 'Z'.
  86.        ''' <para></para>
  87.        ''' e.g., 'A': '&#120328;', 'a': '&#120354;'.
  88.        ''' </summary>
  89.        SansSerifItalic
  90.  
  91.    End Enum
  92.  
  93. End Namespace
  94.  
  95. #End Region
  96.  



UnicodeAlphanumericCharacterSets.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-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 " UnicodeAlphanumericCharacterSets "
  15.  
  16. ' ReSharper disable once CheckNamespace
  17.  
  18. Namespace DevCase.Core.DataProcessing.Common
  19.  
  20.    ''' ----------------------------------------------------------------------------------------------------
  21.    ''' <summary>
  22.    ''' Specifies a Unicode alphanumeric character set.
  23.    ''' <para></para>
  24.    ''' This enum is used by <see cref="UtilString.ConvertToUnicodeLetters"/> function.
  25.    ''' </summary>
  26.    ''' ----------------------------------------------------------------------------------------------------
  27.    ''' <remarks>
  28.    ''' The Unicode character sets are standardized sets of characters that cover
  29.    ''' various scripts and symbols used in written languages worldwide.
  30.    ''' <para></para>
  31.    ''' Unicode provides a unique code point for each character, ensuring interoperability and
  32.    ''' compatibility across different platforms and systems.
  33.    ''' <para></para>
  34.    ''' The alphanumeric character sets defined in this enumeration represent
  35.    ''' specific stylistic variations of alphabetic characters used in mathematics and typography.
  36.    ''' <para></para>
  37.    ''' These character sets are commonly used in scientific and mathematical contexts,
  38.    ''' as well as in typography and font design.
  39.    ''' <para></para>
  40.    ''' They allow for precise representation of stylized alphabetic characters
  41.    ''' in various mathematical equations, formulas, and text layouts.
  42.    ''' </remarks>
  43.    ''' ----------------------------------------------------------------------------------------------------
  44.    Public Enum UnicodeAlphanumericCharacterSets
  45.  
  46.        ''' <summary>
  47.        ''' Unicode symbols from the 'Mathematical Bold' character set
  48.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433),
  49.        ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'.
  50.        ''' <para></para>
  51.        ''' e.g., 'A': '&#119808;', 'a': '&#119834;'.
  52.        ''' </summary>
  53.        MathematicalBold
  54.  
  55.        ''' <summary>
  56.        ''' Unicode symbols from the 'Monospace' character set
  57.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3),
  58.        ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'.
  59.        ''' <para></para>
  60.        ''' e.g., 'A': '&#120432;', 'a': '&#120458;'.
  61.        ''' </summary>
  62.        MonoSpace
  63.  
  64.        ''' <summary>
  65.        ''' Unicode symbols from the 'Sans-Serif' character set
  66.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3),
  67.        ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'.
  68.        ''' <para></para>
  69.        ''' e.g., 'A': '&#120224;', 'a': '&#120250;'.
  70.        ''' </summary>
  71.        SansSerif
  72.  
  73.        ''' <summary>
  74.        ''' Unicode symbols from the 'Sans-Serif Bold' character set
  75.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607),
  76.        ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'.
  77.        ''' <para></para>
  78.        ''' e.g., 'A': '&#120276;', 'a': '&#120302;'.
  79.        ''' </summary>
  80.        SansSerifBold
  81.  
  82.    End Enum
  83.  
  84. End Namespace
  85.  
  86. #End Region
  87.  



UtilString.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' ConvertToUnicodeLetters(String, UnicodeAlphabeticCharacterSets) As String
  11. ' ConvertToUnicodeLetters(String, UnicodeAlphanumericCharacterSets) As String
  12.  
  13. #End Region
  14.  
  15. #End Region
  16.  
  17. #Region " Option Statements "
  18.  
  19. Option Strict On
  20. Option Explicit On
  21. Option Infer Off
  22.  
  23. #End Region
  24.  
  25. #Region " Imports "
  26.  
  27. Imports System.Collections.Generic
  28. Imports System.ComponentModel
  29. Imports System.Text
  30.  
  31. #End Region
  32.  
  33. #Region " String Util "
  34.  
  35. ' ReSharper disable once CheckNamespace
  36.  
  37. Namespace DevCase.Core.DataProcessing.Common
  38.  
  39.    Partial Public NotInheritable Class UtilString
  40.  
  41. #Region " Public Methods "
  42.  
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        ''' <summary>
  45.        ''' Converts the alphabetic characters in the input string to their corresponding
  46.        ''' Unicode representations based on the specified character set.
  47.        ''' </summary>
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        ''' <param name="input">
  50.        ''' The input string to convert.
  51.        ''' </param>
  52.        '''
  53.        ''' <param name="charSet">
  54.        ''' The Unicode character set to use for the character conversion.
  55.        ''' </param>
  56.        ''' ----------------------------------------------------------------------------------------------------
  57.        ''' <returns>
  58.        ''' The input string with alphabetic characters replaced by their Unicode counterparts.
  59.        ''' </returns>
  60.        ''' ----------------------------------------------------------------------------------------------------
  61.        <DebuggerStepThrough>
  62.        Public Shared Function ConvertToUnicodeLetters(input As String, charSet As UnicodeAlphabeticCharacterSets) As String
  63.  
  64.            If String.IsNullOrWhiteSpace(input) Then
  65.                Return input
  66.            End If
  67.  
  68.            Dim charMap As Dictionary(Of Char, String)
  69.            Select Case charSet
  70.  
  71.                Case UnicodeAlphabeticCharacterSets.MathematicalBoldItalic
  72.                    charMap = UnicodeCharacterMaps.MathematicalBoldItalic
  73.  
  74.                Case UnicodeAlphabeticCharacterSets.MathematicalBoldScript
  75.                    charMap = UnicodeCharacterMaps.MathematicalBoldScript
  76.  
  77.                Case UnicodeAlphabeticCharacterSets.MathematicalItalic
  78.                    charMap = UnicodeCharacterMaps.MathematicalItalic
  79.  
  80.                Case UnicodeAlphabeticCharacterSets.SansSerifBoldItalic
  81.                    charMap = UnicodeCharacterMaps.SansSerifBoldItalic
  82.  
  83.                Case UnicodeAlphabeticCharacterSets.SansSerifItalic
  84.                    charMap = UnicodeCharacterMaps.SansSerifItalic
  85.  
  86.                Case Else
  87.                    Throw New InvalidEnumArgumentException(argumentName:=NameOf(charSet),
  88.                                                       invalidValue:=charSet,
  89.                                                       enumClass:=GetType(UnicodeAlphabeticCharacterSets))
  90.            End Select
  91.  
  92.            Dim sb As New StringBuilder(input.Length)
  93.            For Each c As Char In input
  94.                Dim value As String = Nothing
  95.                If charMap.TryGetValue(c, value) Then
  96.                    sb.Append(value)
  97.                Else
  98.                    sb.Append(c)
  99.                End If
  100.            Next
  101.  
  102.            Return sb.ToString()
  103.        End Function
  104.  
  105.        ''' ----------------------------------------------------------------------------------------------------
  106.        ''' <summary>
  107.        ''' Converts the alphanumeric characters in the input string to their corresponding
  108.        ''' Unicode representations based on the specified character set.
  109.        ''' </summary>
  110.        ''' ----------------------------------------------------------------------------------------------------
  111.        ''' <param name="input">
  112.        ''' The input string to convert.
  113.        ''' </param>
  114.        '''
  115.        ''' <param name="charSet">
  116.        ''' The Unicode character set to use for the character conversion.
  117.        ''' </param>
  118.        ''' ----------------------------------------------------------------------------------------------------
  119.        ''' <returns>
  120.        ''' The input string with alphanumeric characters replaced by their Unicode counterparts.
  121.        ''' </returns>
  122.        ''' ----------------------------------------------------------------------------------------------------
  123.        <DebuggerStepThrough>
  124.        Public Shared Function ConvertToUnicodeLetters(input As String, charSet As UnicodeAlphanumericCharacterSets) As String
  125.  
  126.            If String.IsNullOrWhiteSpace(input) Then
  127.                Return input
  128.            End If
  129.  
  130.            Dim charMap As Dictionary(Of Char, String)
  131.            Select Case charSet
  132.  
  133.                Case UnicodeAlphanumericCharacterSets.MathematicalBold
  134.                    charMap = UnicodeCharacterMaps.MathematicalBold
  135.  
  136.                Case UnicodeAlphanumericCharacterSets.MonoSpace
  137.                    charMap = UnicodeCharacterMaps.MonoSpace
  138.  
  139.                Case UnicodeAlphanumericCharacterSets.SansSerif
  140.                    charMap = UnicodeCharacterMaps.SansSerif
  141.  
  142.                Case UnicodeAlphanumericCharacterSets.SansSerifBold
  143.                    charMap = UnicodeCharacterMaps.SansSerifBold
  144.  
  145.                Case Else
  146.                    Throw New InvalidEnumArgumentException(argumentName:=NameOf(charSet),
  147.                                                       invalidValue:=charSet,
  148.                                                       enumClass:=GetType(UnicodeAlphanumericCharacterSets))
  149.            End Select
  150.  
  151.            Dim sb As New StringBuilder(input.Length)
  152.            For Each c As Char In input
  153.                Dim value As String = Nothing
  154.                If charMap.TryGetValue(c, value) Then
  155.                    sb.Append(value)
  156.                Else
  157.                    sb.Append(c)
  158.                End If
  159.            Next
  160.            Return sb.ToString()
  161.        End Function
  162.  
  163. #End Region
  164.  
  165.    End Class
  166.  
  167. End Namespace
  168.  
  169. #End Region
  170.  
15  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 09:03 am
Un código para convertir el texto de un String a sets de caracteres Unicode.

Nota: como resultará evidente, no es posible añadir soporte para los caracteres que carecen de un equivalente.





UnicodeCharacterMaps.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict Off
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Public Members Summary "
  15.  
  16. #Region " Properties "
  17.  
  18. ' MathematicalBold As Dictionary(Of Char, String)
  19. ' MathematicalBoldItalic As Dictionary(Of Char, String)
  20. ' MathematicalBoldScript As Dictionary(Of Char, String)
  21. ' MathematicalItalic As Dictionary(Of Char, String)
  22. ' MonoSpace As Dictionary(Of Char, String)
  23. ' SansSerif As Dictionary(Of Char, String)
  24. ' SansSerifBold As Dictionary(Of Char, String)
  25. ' SansSerifBoldItalic As Dictionary(Of Char, String)
  26. ' SansSerifItalic As Dictionary(Of Char, String)
  27.  
  28. #End Region
  29.  
  30. #End Region
  31.  
  32. #Region " Imports "
  33.  
  34. Imports System.Collections.Generic
  35.  
  36. #End Region
  37.  
  38. #Region " UnicodeCharacterMaps "
  39.  
  40. ' ReSharper disable once CheckNamespace
  41.  
  42. Namespace DevCase.Core.DataProcessing.Common
  43.  
  44.    ''' ----------------------------------------------------------------------------------------------------
  45.    ''' <summary>
  46.    ''' Provides access to predefined alphabetic and alphanumeric character maps for a range of Unicode character sets.
  47.    ''' </summary>
  48.    ''' ----------------------------------------------------------------------------------------------------
  49.    ''' <remarks>
  50.    ''' The Unicode character sets are standardized sets of characters that cover
  51.    ''' various scripts and symbols used in written languages worldwide.
  52.    ''' <para></para>
  53.    ''' Unicode provides a unique code point for each character, ensuring interoperability and
  54.    ''' compatibility across different platforms and systems.
  55.    ''' <para></para>
  56.    ''' The character sets defined in this class represent specific stylistic variations
  57.    ''' of alphabetic characters used in mathematics and typography.
  58.    ''' <para></para>
  59.    ''' These character sets are commonly used in scientific and mathematical contexts,
  60.    ''' as well as in typography and font design.
  61.    ''' <para></para>
  62.    ''' They allow for precise representation of stylized alphabetic characters
  63.    ''' in various mathematical equations, formulas, and text layouts.
  64.    ''' </remarks>
  65.    ''' ----------------------------------------------------------------------------------------------------
  66.    Public Class UnicodeCharacterMaps
  67.  
  68. #Region " Private Fields "
  69.  
  70.        ''' <summary>
  71.        ''' (Backing Field)
  72.        ''' <para></para>
  73.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9',
  74.        ''' and the values are their corresponding symbols from the 'Mathematical Bold' character set
  75.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433).
  76.        ''' <para></para>
  77.        ''' e.g., dictionary key: 'A' gets value: '&#119808;', and dictionary key: 'a' gets value: '&#119834;'.
  78.        ''' </summary>
  79.        Private Shared _mathematicalBold As Dictionary(Of Char, String)
  80.  
  81.        ''' <summary>
  82.        ''' (Backing Field)
  83.        ''' <para></para>
  84.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z',
  85.        ''' and the values are their corresponding symbols from the 'Mathematical Italic' character set
  86.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467).
  87.        ''' <para></para>
  88.        ''' e.g., dictionary key: 'A' gets value: '&#119860;', and dictionary key: 'a' gets value: '&#119886;'.
  89.        ''' </summary>
  90.        Private Shared _mathematicalItalic As Dictionary(Of Char, String)
  91.  
  92.        ''' <summary>
  93.        ''' (Backing Field)
  94.        ''' <para></para>
  95.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z',
  96.        ''' and the values are their corresponding symbols from the 'Mathematical Bold Italic' character set
  97.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B).
  98.        ''' <para></para>
  99.        ''' e.g., dictionary key: 'A' gets value: '&#119912;', and dictionary key: 'a' gets value: '&#119938;'.
  100.        ''' </summary>
  101.        Private Shared _mathematicalBoldItalic As Dictionary(Of Char, String)
  102.  
  103.        ''' <summary>
  104.        ''' (Backing Field)
  105.        ''' <para></para>
  106.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z',
  107.        ''' and the values are their corresponding symbols from the 'Mathematical Bold Script' character set
  108.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503).
  109.        ''' <para></para>
  110.        ''' e.g., dictionary key: 'A' gets value: '&#120016;', and dictionary key: 'a' gets value: '&#120042;'.
  111.        ''' </summary>
  112.        Private Shared _mathematicalBoldScript As Dictionary(Of Char, String)
  113.  
  114.        ''' <summary>
  115.        ''' (Backing Field)
  116.        ''' <para></para>
  117.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9',
  118.        ''' and the values are their corresponding symbols from the 'Sans-Serif' character set
  119.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3).
  120.        ''' <para></para>
  121.        ''' e.g., dictionary key: 'A' gets value: '&#120224;', and dictionary key: 'a' gets value: '&#120250;'.
  122.        ''' </summary>
  123.        Private Shared _sansSerif As Dictionary(Of Char, String)
  124.  
  125.        ''' <summary>
  126.        ''' (Backing Field)
  127.        ''' <para></para>
  128.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9',
  129.        ''' and the values are their corresponding symbols from the 'Sans-Serif Bold' character set
  130.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607).
  131.        ''' <para></para>
  132.        ''' e.g., dictionary key: 'A' gets value: '&#120276;', and dictionary key: 'a' gets value: '&#120302;'.
  133.        ''' </summary>
  134.        Private Shared _sansSerifBold As Dictionary(Of Char, String)
  135.  
  136.        ''' <summary>
  137.        ''' (Backing Field)
  138.        ''' <para></para>
  139.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z',
  140.        ''' and the values are their corresponding symbols from the 'Sans-Serif Italic' character set
  141.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B).
  142.        ''' <para></para>
  143.        ''' e.g., dictionary key: 'A' gets value: '&#120328;', and dictionary key: 'a' gets value: '&#120354;'.
  144.        ''' </summary>
  145.        Private Shared _sansSerifItalic As Dictionary(Of Char, String)
  146.  
  147.        ''' <summary>
  148.        ''' (Backing Field)
  149.        ''' <para></para>
  150.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z',
  151.        ''' and the values are their corresponding symbols from the 'Sans-Serif Bold Italic' character set
  152.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F).
  153.        ''' <para></para>
  154.        ''' e.g., dictionary key: 'A' gets value: '&#120380;', and dictionary key: 'a' gets value: '&#120406;'.
  155.        ''' </summary>
  156.        Private Shared _sansSerifBoldItalic As Dictionary(Of Char, String)
  157.  
  158.        ''' <summary>
  159.        ''' (Backing Field)
  160.        ''' <para></para>
  161.        ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9',
  162.        ''' and the values are their corresponding symbols from the 'Monospace' character set
  163.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3).
  164.        ''' <para></para>
  165.        ''' e.g., dictionary key: 'A' gets value: '&#120432;', and dictionary key: 'a' gets value: '&#120458;'.
  166.        ''' </summary>
  167.        Private Shared _monoSpace As Dictionary(Of Char, String)
  168.  
  169. #End Region
  170.  
  171. #Region " Properties "
  172.  
  173.        ''' ----------------------------------------------------------------------------------------------------
  174.        ''' <summary>
  175.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9',
  176.        ''' and the values are their corresponding symbols from the 'Mathematical Bold' character set
  177.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433).
  178.        ''' <para></para>
  179.        ''' e.g., dictionary key: 'A' gets value: '&#119808;', and dictionary key: 'a' gets value: '&#119834;'.
  180.        ''' </summary>
  181.        ''' ----------------------------------------------------------------------------------------------------
  182.        Public Shared ReadOnly Property MathematicalBold As Dictionary(Of Char, String)
  183.            Get
  184.                If UnicodeCharacterMaps._mathematicalBold Is Nothing Then
  185.                    UnicodeCharacterMaps._mathematicalBold = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  186.                           {"A"c, "&#119808;"}, {"B"c, "&#119809;"}, {"C"c, "&#119810;"}, {"D"c, "&#119811;"}, {"E"c, "&#119812;"},
  187.                           {"F"c, "&#119813;"}, {"G"c, "&#119814;"}, {"H"c, "&#119815;"}, {"I"c, "&#119816;"}, {"J"c, "&#119817;"},
  188.                           {"K"c, "&#119818;"}, {"L"c, "&#119819;"}, {"M"c, "&#119820;"}, {"N"c, "&#119821;"}, {"O"c, "&#119822;"},
  189.                           {"P"c, "&#119823;"}, {"Q"c, "&#119824;"}, {"R"c, "&#119825;"}, {"S"c, "&#119826;"}, {"T"c, "&#119827;"},
  190.                           {"U"c, "&#119828;"}, {"V"c, "&#119829;"}, {"W"c, "&#119830;"}, {"X"c, "&#119831;"}, {"Y"c, "&#119832;"},
  191.                           {"Z"c, "&#119833;"},
  192.                           {"a"c, "&#119834;"}, {"b"c, "&#119835;"}, {"c"c, "&#119836;"}, {"d"c, "&#119837;"}, {"e"c, "&#119838;"},
  193.                           {"f"c, "&#119839;"}, {"g"c, "&#119840;"}, {"h"c, "&#119841;"}, {"i"c, "&#119842;"}, {"j"c, "&#119843;"},
  194.                           {"k"c, "&#119844;"}, {"l"c, "&#119845;"}, {"m"c, "&#119846;"}, {"n"c, "&#119847;"}, {"o"c, "&#119848;"},
  195.                           {"p"c, "&#119849;"}, {"q"c, "&#119850;"}, {"r"c, "&#119851;"}, {"s"c, "&#119852;"}, {"t"c, "&#119853;"},
  196.                           {"u"c, "&#119854;"}, {"v"c, "&#119855;"}, {"w"c, "&#119856;"}, {"x"c, "&#119857;"}, {"y"c, "&#119858;"},
  197.                           {"z"c, "&#119859;"},
  198.                           {"0"c, "&#120782;"}, {"1"c, "&#120783;"}, {"2"c, "&#120784;"}, {"3"c, "&#120785;"}, {"4"c, "&#120786;"},
  199.                           {"5"c, "&#120787;"}, {"6"c, "&#120788;"}, {"7"c, "&#120789;"}, {"8"c, "&#120790;"}, {"9"c, "&#120791;"}
  200.                       }
  201.                End If
  202.                Return UnicodeCharacterMaps._mathematicalBold
  203.            End Get
  204.        End Property
  205.  
  206.        ''' ----------------------------------------------------------------------------------------------------
  207.        ''' <summary>
  208.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z',
  209.        ''' and the values are their corresponding symbols from the 'Mathematical Italic' character set
  210.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467).
  211.        ''' <para></para>
  212.        ''' e.g., dictionary key: 'A' gets value: '&#119860;', and dictionary key: 'a' gets value: '&#119886;'.
  213.        ''' </summary>
  214.        ''' ----------------------------------------------------------------------------------------------------
  215.        Public Shared ReadOnly Property MathematicalItalic As Dictionary(Of Char, String)
  216.            Get
  217.                If UnicodeCharacterMaps._mathematicalItalic Is Nothing Then
  218.                    UnicodeCharacterMaps._mathematicalItalic = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  219.                           {"A"c, "&#119860;"}, {"B"c, "&#119861;"}, {"C"c, "&#119862;"}, {"D"c, "&#119863;"}, {"E"c, "&#119864;"},
  220.                           {"F"c, "&#119865;"}, {"G"c, "&#119866;"}, {"H"c, "&#119867;"}, {"I"c, "&#119868;"}, {"J"c, "&#119869;"},
  221.                           {"K"c, "&#119870;"}, {"L"c, "&#119871;"}, {"M"c, "&#119872;"}, {"N"c, "&#119873;"}, {"O"c, "&#119874;"},
  222.                           {"P"c, "&#119875;"}, {"Q"c, "&#119876;"}, {"R"c, "&#119877;"}, {"S"c, "&#119878;"}, {"T"c, "&#119879;"},
  223.                           {"U"c, "&#119880;"}, {"V"c, "&#119881;"}, {"W"c, "&#119882;"}, {"X"c, "&#119883;"}, {"Y"c, "&#119884;"},
  224.                           {"Z"c, "&#119885;"},
  225.                           {"a"c, "&#119886;"}, {"b"c, "&#119887;"}, {"c"c, "&#119888;"}, {"d"c, "&#119889;"}, {"e"c, "&#119890;"},
  226.                           {"f"c, "&#119891;"}, {"g"c, "&#119892;"}, {"h"c, "&#120361;"}, {"i"c, "&#119894;"}, {"j"c, "&#119895;"},
  227.                           {"k"c, "&#119896;"}, {"l"c, "&#119897;"}, {"m"c, "&#119898;"}, {"n"c, "&#119899;"}, {"o"c, "&#119900;"},
  228.                           {"p"c, "&#119901;"}, {"q"c, "&#119902;"}, {"r"c, "&#119903;"}, {"s"c, "&#119904;"}, {"t"c, "&#119905;"},
  229.                           {"u"c, "&#119906;"}, {"v"c, "&#119907;"}, {"w"c, "&#119908;"}, {"x"c, "&#119909;"}, {"y"c, "&#119910;"},
  230.                           {"z"c, "&#119911;"}
  231.                       }
  232.                End If
  233.                Return UnicodeCharacterMaps._mathematicalItalic
  234.            End Get
  235.        End Property
  236.  
  237.        ''' ----------------------------------------------------------------------------------------------------
  238.        ''' <summary>
  239.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z',
  240.        ''' and the values are their corresponding symbols from the 'Mathematical Bold Italic' character set
  241.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B).
  242.        ''' <para></para>
  243.        ''' e.g., dictionary key: 'A' gets value: '&#119912;', and dictionary key: 'a' gets value: '&#119938;'.
  244.        ''' </summary>
  245.        ''' ----------------------------------------------------------------------------------------------------
  246.        Public Shared ReadOnly Property MathematicalBoldItalic As Dictionary(Of Char, String)
  247.            Get
  248.                If UnicodeCharacterMaps._mathematicalBoldItalic Is Nothing Then
  249.                    UnicodeCharacterMaps._mathematicalBoldItalic = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  250.                           {"A"c, "&#119912;"}, {"B"c, "&#119913;"}, {"C"c, "&#119914;"}, {"D"c, "&#119915;"}, {"E"c, "&#119916;"},
  251.                           {"F"c, "&#119917;"}, {"G"c, "&#119918;"}, {"H"c, "&#119919;"}, {"I"c, "&#119920;"}, {"J"c, "&#119921;"},
  252.                           {"K"c, "&#119922;"}, {"L"c, "&#119923;"}, {"M"c, "&#119924;"}, {"N"c, "&#119925;"}, {"O"c, "&#119926;"},
  253.                           {"P"c, "&#119927;"}, {"Q"c, "&#119928;"}, {"R"c, "&#119929;"}, {"S"c, "&#119930;"}, {"T"c, "&#119931;"},
  254.                           {"U"c, "&#119932;"}, {"V"c, "&#119933;"}, {"W"c, "&#119934;"}, {"X"c, "&#119935;"}, {"Y"c, "&#119936;"},
  255.                           {"Z"c, "&#119937;"},
  256.                           {"a"c, "&#119938;"}, {"b"c, "&#119939;"}, {"c"c, "&#119940;"}, {"d"c, "&#119941;"}, {"e"c, "&#119942;"},
  257.                           {"f"c, "&#119943;"}, {"g"c, "&#119944;"}, {"h"c, "&#119945;"}, {"i"c, "&#119946;"}, {"j"c, "&#119947;"},
  258.                           {"k"c, "&#119948;"}, {"l"c, "&#119949;"}, {"m"c, "&#119950;"}, {"n"c, "&#119951;"}, {"o"c, "&#119952;"},
  259.                           {"p"c, "&#119953;"}, {"q"c, "&#119954;"}, {"r"c, "&#119955;"}, {"s"c, "&#119956;"}, {"t"c, "&#119957;"},
  260.                           {"u"c, "&#119958;"}, {"v"c, "&#119959;"}, {"w"c, "&#119960;"}, {"x"c, "&#119961;"}, {"y"c, "&#119962;"},
  261.                           {"z"c, "&#119963;"}
  262.                       }
  263.                End If
  264.                Return UnicodeCharacterMaps._mathematicalBoldItalic
  265.            End Get
  266.        End Property
  267.  
  268.        ''' ----------------------------------------------------------------------------------------------------
  269.        ''' <summary>
  270.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z',
  271.        ''' and the values are their corresponding symbols from the 'Mathematical Bold Script' character set
  272.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503).
  273.        ''' <para></para>
  274.        ''' e.g., dictionary key: 'A' gets value: '&#120016;', and dictionary key: 'a' gets value: '&#120042;'.
  275.        ''' </summary>
  276.        ''' ----------------------------------------------------------------------------------------------------
  277.        Public Shared ReadOnly Property MathematicalBoldScript As Dictionary(Of Char, String)
  278.            Get
  279.                If UnicodeCharacterMaps._mathematicalBoldScript Is Nothing Then
  280.                    UnicodeCharacterMaps._mathematicalBoldScript = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  281.                           {"A"c, "&#120016;"}, {"B"c, "&#120017;"}, {"C"c, "&#120018;"}, {"D"c, "&#120019;"}, {"E"c, "&#120020;"},
  282.                           {"F"c, "&#120021;"}, {"G"c, "&#120022;"}, {"H"c, "&#120023;"}, {"I"c, "&#120024;"}, {"J"c, "&#120025;"},
  283.                           {"K"c, "&#120026;"}, {"L"c, "&#120027;"}, {"M"c, "&#120028;"}, {"N"c, "&#120029;"}, {"O"c, "&#120030;"},
  284.                           {"P"c, "&#120031;"}, {"Q"c, "&#120032;"}, {"R"c, "&#120033;"}, {"S"c, "&#120034;"}, {"T"c, "&#120035;"},
  285.                           {"U"c, "&#120036;"}, {"V"c, "&#120037;"}, {"W"c, "&#120038;"}, {"X"c, "&#120039;"}, {"Y"c, "&#120040;"},
  286.                           {"Z"c, "&#120041;"},
  287.                           {"a"c, "&#120042;"}, {"b"c, "&#120043;"}, {"c"c, "&#120044;"}, {"d"c, "&#120045;"}, {"e"c, "&#120046;"},
  288.                           {"f"c, "&#120047;"}, {"g"c, "&#120048;"}, {"h"c, "&#120049;"}, {"i"c, "&#120050;"}, {"j"c, "&#120051;"},
  289.                           {"k"c, "&#120052;"}, {"l"c, "&#120053;"}, {"m"c, "&#120054;"}, {"n"c, "&#120055;"}, {"o"c, "&#120056;"},
  290.                           {"p"c, "&#120057;"}, {"q"c, "&#120058;"}, {"r"c, "&#120059;"}, {"s"c, "&#120060;"}, {"t"c, "&#120061;"},
  291.                           {"u"c, "&#120062;"}, {"v"c, "&#120063;"}, {"w"c, "&#120064;"}, {"x"c, "&#120065;"}, {"y"c, "&#120066;"},
  292.                           {"z"c, "&#120067;"}
  293.                       }
  294.                End If
  295.                Return UnicodeCharacterMaps._mathematicalBoldScript
  296.            End Get
  297.        End Property
  298.  
  299.        ''' ----------------------------------------------------------------------------------------------------
  300.        ''' <summary>
  301.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9',
  302.        ''' and the values are their corresponding symbols from the 'Sans-Serif' character set
  303.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3).
  304.        ''' <para></para>
  305.        ''' e.g., dictionary key: 'A' gets value: '&#120224;', and dictionary key: 'a' gets value: '&#120250;'.
  306.        ''' </summary>
  307.        ''' ----------------------------------------------------------------------------------------------------
  308.        Public Shared ReadOnly Property SansSerif As Dictionary(Of Char, String)
  309.            Get
  310.                If UnicodeCharacterMaps._sansSerif Is Nothing Then
  311.                    UnicodeCharacterMaps._sansSerif = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  312.                           {"A"c, "&#120224;"}, {"B"c, "&#120225;"}, {"C"c, "&#120226;"}, {"D"c, "&#120227;"}, {"E"c, "&#120228;"},
  313.                           {"F"c, "&#120229;"}, {"G"c, "&#120230;"}, {"H"c, "&#120231;"}, {"I"c, "&#120232;"}, {"J"c, "&#120233;"},
  314.                           {"K"c, "&#120234;"}, {"L"c, "&#120235;"}, {"M"c, "&#120236;"}, {"N"c, "&#120237;"}, {"O"c, "&#120238;"},
  315.                           {"P"c, "&#120239;"}, {"Q"c, "&#120240;"}, {"R"c, "&#120241;"}, {"S"c, "&#120242;"}, {"T"c, "&#120243;"},
  316.                           {"U"c, "&#120244;"}, {"V"c, "&#120245;"}, {"W"c, "&#120246;"}, {"X"c, "&#120247;"}, {"Y"c, "&#120248;"},
  317.                           {"Z"c, "&#120249;"},
  318.                           {"a"c, "&#120250;"}, {"b"c, "&#120251;"}, {"c"c, "&#120252;"}, {"d"c, "&#120253;"}, {"e"c, "&#120254;"},
  319.                           {"f"c, "&#120255;"}, {"g"c, "&#120256;"}, {"h"c, "&#120257;"}, {"i"c, "&#120258;"}, {"j"c, "&#120259;"},
  320.                           {"k"c, "&#120260;"}, {"l"c, "&#120261;"}, {"m"c, "&#120262;"}, {"n"c, "&#120263;"}, {"o"c, "&#120264;"},
  321.                           {"p"c, "&#120265;"}, {"q"c, "&#120266;"}, {"r"c, "&#120267;"}, {"s"c, "&#120268;"}, {"t"c, "&#120269;"},
  322.                           {"u"c, "&#120270;"}, {"v"c, "&#120271;"}, {"w"c, "&#120272;"}, {"x"c, "&#120273;"}, {"y"c, "&#120274;"},
  323.                           {"z"c, "&#120275;"},
  324.                           {"0"c, "&#120802;"}, {"1"c, "&#120803;"}, {"2"c, "&#120804;"}, {"3"c, "&#120805;"}, {"4"c, "&#120806;"},
  325.                           {"5"c, "&#120807;"}, {"6"c, "&#120808;"}, {"7"c, "&#120809;"}, {"8"c, "&#120810;"}, {"9"c, "&#120811;"}
  326.                       }
  327.                End If
  328.                Return UnicodeCharacterMaps._sansSerif
  329.            End Get
  330.        End Property
  331.  
  332.        ''' ----------------------------------------------------------------------------------------------------
  333.        ''' <summary>
  334.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9',
  335.        ''' and the values are their corresponding symbols from the 'Sans-Serif Bold' character set
  336.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607).
  337.        ''' <para></para>
  338.        ''' e.g., dictionary key: 'A' gets value: '&#120276;', and dictionary key: 'a' gets value: '&#120302;'.
  339.        ''' </summary>
  340.        ''' ----------------------------------------------------------------------------------------------------
  341.        Public Shared ReadOnly Property SansSerifBold As Dictionary(Of Char, String)
  342.            Get
  343.                If UnicodeCharacterMaps._sansSerifBold Is Nothing Then
  344.                    UnicodeCharacterMaps._sansSerifBold = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  345.                           {"A"c, "&#120276;"}, {"B"c, "&#120277;"}, {"C"c, "&#120278;"}, {"D"c, "&#120279;"}, {"E"c, "&#120280;"},
  346.                           {"F"c, "&#120281;"}, {"G"c, "&#120282;"}, {"H"c, "&#120283;"}, {"I"c, "&#120284;"}, {"J"c, "&#120285;"},
  347.                           {"K"c, "&#120286;"}, {"L"c, "&#120287;"}, {"M"c, "&#120288;"}, {"N"c, "&#120289;"}, {"O"c, "&#120290;"},
  348.                           {"P"c, "&#120291;"}, {"Q"c, "&#120292;"}, {"R"c, "&#120293;"}, {"S"c, "&#120294;"}, {"T"c, "&#120295;"},
  349.                           {"U"c, "&#120296;"}, {"V"c, "&#120297;"}, {"W"c, "&#120298;"}, {"X"c, "&#120299;"}, {"Y"c, "&#120300;"},
  350.                           {"Z"c, "&#120301;"},
  351.                           {"a"c, "&#120302;"}, {"b"c, "&#120303;"}, {"c"c, "&#120304;"}, {"d"c, "&#120305;"}, {"e"c, "&#120306;"},
  352.                           {"f"c, "&#120307;"}, {"g"c, "&#120308;"}, {"h"c, "&#120309;"}, {"i"c, "&#120310;"}, {"j"c, "&#120311;"},
  353.                           {"k"c, "&#120312;"}, {"l"c, "&#120313;"}, {"m"c, "&#120314;"}, {"n"c, "&#120315;"}, {"o"c, "&#120316;"},
  354.                           {"p"c, "&#120317;"}, {"q"c, "&#120318;"}, {"r"c, "&#120319;"}, {"s"c, "&#120320;"}, {"t"c, "&#120321;"},
  355.                           {"u"c, "&#120322;"}, {"v"c, "&#120323;"}, {"w"c, "&#120324;"}, {"x"c, "&#120325;"}, {"y"c, "&#120326;"},
  356.                           {"z"c, "&#120327;"},
  357.                           {"0"c, "&#120812;"}, {"1"c, "&#120813;"}, {"2"c, "&#120814;"}, {"3"c, "&#120815;"}, {"4"c, "&#120816;"},
  358.                           {"5"c, "&#120817;"}, {"6"c, "&#120818;"}, {"7"c, "&#120819;"}, {"8"c, "&#120820;"}, {"9"c, "&#120821;"}
  359.                       }
  360.                End If
  361.                Return UnicodeCharacterMaps._sansSerifBold
  362.            End Get
  363.        End Property
  364.  
  365.        ''' ----------------------------------------------------------------------------------------------------
  366.        ''' <summary>
  367.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z',
  368.        ''' and the values are their corresponding symbols from the 'Sans-Serif Italic' character set
  369.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B).
  370.        ''' <para></para>
  371.        ''' e.g., dictionary key: 'A' gets value: '&#120328;', and dictionary key: 'a' gets value: '&#120354;'.
  372.        ''' </summary>
  373.        ''' ----------------------------------------------------------------------------------------------------
  374.        Public Shared ReadOnly Property SansSerifItalic As Dictionary(Of Char, String)
  375.            Get
  376.                If UnicodeCharacterMaps._sansSerifItalic Is Nothing Then
  377.                    UnicodeCharacterMaps._sansSerifItalic = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  378.                           {"A"c, "&#120328;"}, {"B"c, "&#120329;"}, {"C"c, "&#120330;"}, {"D"c, "&#120331;"}, {"E"c, "&#120332;"},
  379.                           {"F"c, "&#120333;"}, {"G"c, "&#120334;"}, {"H"c, "&#120335;"}, {"I"c, "&#120336;"}, {"J"c, "&#120337;"},
  380.                           {"K"c, "&#120338;"}, {"L"c, "&#120339;"}, {"M"c, "&#120340;"}, {"N"c, "&#120341;"}, {"O"c, "&#120342;"},
  381.                           {"P"c, "&#120343;"}, {"Q"c, "&#120344;"}, {"R"c, "&#120345;"}, {"S"c, "&#120346;"}, {"T"c, "&#120347;"},
  382.                           {"U"c, "&#120348;"}, {"V"c, "&#120349;"}, {"W"c, "&#120350;"}, {"X"c, "&#120351;"}, {"Y"c, "&#120352;"},
  383.                           {"Z"c, "&#120353;"},
  384.                           {"a"c, "&#120354;"}, {"b"c, "&#120355;"}, {"c"c, "&#120356;"}, {"d"c, "&#120357;"}, {"e"c, "&#120358;"},
  385.                           {"f"c, "&#120359;"}, {"g"c, "&#120360;"}, {"h"c, "&#120361;"}, {"i"c, "&#120362;"}, {"j"c, "&#120363;"},
  386.                           {"k"c, "&#120364;"}, {"l"c, "&#120365;"}, {"m"c, "&#120366;"}, {"n"c, "&#120367;"}, {"o"c, "&#120368;"},
  387.                           {"p"c, "&#120369;"}, {"q"c, "&#120370;"}, {"r"c, "&#120371;"}, {"s"c, "&#120372;"}, {"t"c, "&#120373;"},
  388.                           {"u"c, "&#120374;"}, {"v"c, "&#120375;"}, {"w"c, "&#120376;"}, {"x"c, "&#120377;"}, {"y"c, "&#120378;"},
  389.                           {"z"c, "&#120379;"}
  390.                       }
  391.                End If
  392.                Return UnicodeCharacterMaps._sansSerifItalic
  393.            End Get
  394.        End Property
  395.  
  396.        ''' ----------------------------------------------------------------------------------------------------
  397.        ''' <summary>
  398.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z',
  399.        ''' and the values are their corresponding symbols from the 'Sans-Serif Bold Italic' character set
  400.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F).
  401.        ''' <para></para>
  402.        ''' e.g., dictionary key: 'A' gets value: '&#120380;', and dictionary key: 'a' gets value: '&#120406;'.
  403.        ''' </summary>
  404.        ''' ----------------------------------------------------------------------------------------------------
  405.        Public Shared ReadOnly Property SansSerifBoldItalic As Dictionary(Of Char, String)
  406.            Get
  407.                If UnicodeCharacterMaps._sansSerifBoldItalic Is Nothing Then
  408.                    UnicodeCharacterMaps._sansSerifBoldItalic = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  409.                           {"A"c, "&#120380;"}, {"B"c, "&#120381;"}, {"C"c, "&#120382;"}, {"D"c, "&#120383;"}, {"E"c, "&#120384;"},
  410.                           {"F"c, "&#120385;"}, {"G"c, "&#120386;"}, {"H"c, "&#120387;"}, {"I"c, "&#120388;"}, {"J"c, "&#120389;"},
  411.                           {"K"c, "&#120390;"}, {"L"c, "&#120391;"}, {"M"c, "&#120392;"}, {"N"c, "&#120393;"}, {"O"c, "&#120394;"},
  412.                           {"P"c, "&#120395;"}, {"Q"c, "&#120396;"}, {"R"c, "&#120397;"}, {"S"c, "&#120398;"}, {"T"c, "&#120399;"},
  413.                           {"U"c, "&#120400;"}, {"V"c, "&#120401;"}, {"W"c, "&#120402;"}, {"X"c, "&#120403;"}, {"Y"c, "&#120404;"},
  414.                           {"Z"c, "&#120405;"},
  415.                           {"a"c, "&#120406;"}, {"b"c, "&#120407;"}, {"c"c, "&#120408;"}, {"d"c, "&#120409;"}, {"e"c, "&#120410;"},
  416.                           {"f"c, "&#120411;"}, {"g"c, "&#120412;"}, {"h"c, "&#120413;"}, {"i"c, "&#120414;"}, {"j"c, "&#120415;"},
  417.                           {"k"c, "&#120416;"}, {"l"c, "&#120417;"}, {"m"c, "&#120418;"}, {"n"c, "&#120419;"}, {"o"c, "&#120420;"},
  418.                           {"p"c, "&#120421;"}, {"q"c, "&#120422;"}, {"r"c, "&#120423;"}, {"s"c, "&#120424;"}, {"t"c, "&#120425;"},
  419.                           {"u"c, "&#120426;"}, {"v"c, "&#120427;"}, {"w"c, "&#120428;"}, {"x"c, "&#120429;"}, {"y"c, "&#120430;"},
  420.                           {"z"c, "&#120431;"}
  421.                       }
  422.                End If
  423.                Return UnicodeCharacterMaps._sansSerifBoldItalic
  424.            End Get
  425.        End Property
  426.  
  427.        ''' ----------------------------------------------------------------------------------------------------
  428.        ''' <summary>
  429.        ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9',
  430.        ''' and the values are their corresponding symbols from the 'Monospace' character set
  431.        ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3).
  432.        ''' <para></para>
  433.        ''' e.g., dictionary key: 'A' gets value: '&#120432;', and dictionary key: 'a' gets value: '&#120458;'.
  434.        ''' </summary>
  435.        ''' ----------------------------------------------------------------------------------------------------
  436.        Public Shared ReadOnly Property MonoSpace As Dictionary(Of Char, String)
  437.            Get
  438.                If UnicodeCharacterMaps._monoSpace Is Nothing Then
  439.                    UnicodeCharacterMaps._monoSpace = New Dictionary(Of Char, String)(EqualityComparer(Of Char).Default) From {
  440.                           {"A"c, "&#120432;"}, {"B"c, "&#120433;"}, {"C"c, "&#120434;"}, {"D"c, "&#120435;"}, {"E"c, "&#120436;"},
  441.                           {"F"c, "&#120437;"}, {"G"c, "&#120438;"}, {"H"c, "&#120439;"}, {"I"c, "&#120440;"}, {"J"c, "&#120441;"},
  442.                           {"K"c, "&#120442;"}, {"L"c, "&#120443;"}, {"M"c, "&#120444;"}, {"N"c, "&#120445;"}, {"O"c, "&#120446;"},
  443.                           {"P"c, "&#120447;"}, {"Q"c, "&#120448;"}, {"R"c, "&#120449;"}, {"S"c, "&#120450;"}, {"T"c, "&#120451;"},
  444.                           {"U"c, "&#120452;"}, {"V"c, "&#120453;"}, {"W"c, "&#120454;"}, {"X"c, "&#120455;"}, {"Y"c, "&#120456;"},
  445.                           {"Z"c, "&#120457;"},
  446.                           {"a"c, "&#120458;"}, {"b"c, "&#120459;"}, {"c"c, "&#120460;"}, {"d"c, "&#120461;"}, {"e"c, "&#120462;"},
  447.                           {"f"c, "&#120463;"}, {"g"c, "&#120464;"}, {"h"c, "&#120465;"}, {"i"c, "&#120466;"}, {"j"c, "&#120467;"},
  448.                           {"k"c, "&#120468;"}, {"l"c, "&#120469;"}, {"m"c, "&#120470;"}, {"n"c, "&#120471;"}, {"o"c, "&#120472;"},
  449.                           {"p"c, "&#120473;"}, {"q"c, "&#120474;"}, {"r"c, "&#120475;"}, {"s"c, "&#120476;"}, {"t"c, "&#120477;"},
  450.                           {"u"c, "&#120478;"}, {"v"c, "&#120479;"}, {"w"c, "&#120480;"}, {"x"c, "&#120481;"}, {"y"c, "&#120482;"},
  451.                           {"z"c, "&#120483;"},
  452.                           {"0"c, "&#120822;"}, {"1"c, "&#120823;"}, {"2"c, "&#120824;"}, {"3"c, "&#120825;"}, {"4"c, "&#120826;"},
  453.                           {"5"c, "&#120827;"}, {"6"c, "&#120828;"}, {"7"c, "&#120829;"}, {"8"c, "&#120830;"}, {"9"c, "&#120831;"}
  454.                       }
  455.                End If
  456.                Return UnicodeCharacterMaps._monoSpace
  457.            End Get
  458.        End Property
  459.  
  460. #End Region
  461.  
  462. #Region " Constructors "
  463.  
  464.        ''' ----------------------------------------------------------------------------------------------------
  465.        ''' <summary>
  466.        ''' Prevents a default instance of the <see cref="UnicodeCharacterMaps"/> class from being created.
  467.        ''' </summary>
  468.        ''' ----------------------------------------------------------------------------------------------------
  469.        <DebuggerNonUserCode>
  470.        Private Sub New()
  471.        End Sub
  472.  
  473. #End Region
  474.  
  475.    End Class
  476.  
  477. End Namespace
  478.  
  479. #End Region
  480.  



EL CÓDIGO CONTINÚA EN EL SIGUIENTE POST 👇👇👇
16  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 08:57 am
Un código para calcular la entropía de un String, basado en la fórmula de Shannon: https://en.wikipedia.org/wiki/Entropy_(information_theory)

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' CalculateStringEntropy(String) As Double
  11.  
  12. #End Region
  13.  
  14. #End Region
  15.  
  16. #Region " Option Statements "
  17.  
  18. Option Strict On
  19. Option Explicit On
  20. Option Infer Off
  21.  
  22. #End Region
  23.  
  24. #Region " Imports "
  25.  
  26. #End Region
  27.  
  28. #Region " String Util "
  29.  
  30. ' ReSharper disable once CheckNamespace
  31.  
  32. Namespace DevCase.Core.DataProcessing.Common
  33.  
  34.    Partial Public NotInheritable Class UtilString
  35.  
  36. #Region " Public Methods "
  37.  
  38.        ''' ----------------------------------------------------------------------------------------------------
  39.        ''' <summary>
  40.        ''' Calculates the entropy of a string based on the Shannon's entropy formula.
  41.        ''' <para></para>
  42.        ''' The entropy is a measure of the amount of uncertainty or randomness in a set of characters.
  43.        ''' </summary>
  44.        ''' ----------------------------------------------------------------------------------------------------
  45.        ''' <seealso href="https://en.wikipedia.org/wiki/Entropy_(information_theory)"/>
  46.        ''' ----------------------------------------------------------------------------------------------------
  47.        ''' <param name="str">
  48.        ''' The input string.
  49.        ''' </param>
  50.        ''' ----------------------------------------------------------------------------------------------------
  51.        ''' <returns>
  52.        ''' A number representing the entropy value of the input string.
  53.        ''' <para></para>
  54.        ''' A higher entropy value indicates that the text contains more randomness or unpredictability,
  55.        ''' while a lower entropy value indicates that the text is more structured or predictable.
  56.        ''' </returns>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <remarks>
  59.        ''' To calculate the entropy of the given text, the algorithm first counts the frequency of each character in the text.
  60.        ''' It then uses these frequencies to calculate the probability of each character appearing in the text.
  61.        ''' Once the probability of each character is known, the algorithm applies Shannon's entropy formula,
  62.        ''' which looks like this: H = -&#931;p(x)log2p(x), where H is the entropy, p(x) is the probability that
  63.        ''' character x will appear in the text, and log2 is the base 2 logarithm.
  64.        ''' </remarks>
  65.        ''' ----------------------------------------------------------------------------------------------------
  66.        <DebuggerStepThrough>
  67.        Public Shared Function CalculateStringEntropy(str As String) As Double
  68.            Dim map As New Dictionary(Of Char, Integer)()
  69.            For Each c As Char In str
  70.                If Not map.ContainsKey(c) Then
  71.                    map.Add(c, 1)
  72.                Else
  73.                    map(c) += 1
  74.                End If
  75.            Next c
  76.  
  77.            Dim result As Double = 0.0
  78.            Dim len As Integer = str.Length
  79.            For Each item As KeyValuePair(Of Char, Integer) In map
  80.                Dim frequency As Double = item.Value / len
  81.                result -= frequency * (System.Math.Log(frequency) / System.Math.Log(2))
  82.            Next item
  83.  
  84.            Return result
  85.        End Function
  86.  
  87. #End Region
  88.  
  89.    End Class
  90.  
  91. End Namespace
  92.  
  93. #End Region
  94.  
17  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 08:50 am
Aquí un código para generar las páginas de impresión (para la impresora) del contenido de un control DataGridView.

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



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

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

Ejemplos de uso:

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

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

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

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



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

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

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

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

Las reglas son las siguientes:

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

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

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

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

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

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

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



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



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



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

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