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

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 5 Visitantes están viendo este tema.
Páginas: 1 ... 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 [57] 58 59 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 529,051 veces)
Elektro Enjuto

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #560 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.  


En línea

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

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #561 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 👇👇👇


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

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

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #562 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.  
En línea

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

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #563 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.  
En línea

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

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #564 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.  
« Última modificación: 10 Septiembre 2023, 09:21 am por Elektro Enjuto » En línea

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

Desconectado Desconectado

Mensajes: 121



Ver Perfil WWW
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #565 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.  
En línea

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

Desconectado Desconectado

Mensajes: 121



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

Un algoritmo para envolver de forma decorativa los caracteres de un string.

Inspirado en este servicio: https://onlinetexttools.com/add-symbols-around-letters

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



...con opciones de personalización.



Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 11-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' WrapCharacters(String, Char, Char, Opt: Boolean, 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.Linq
  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.        ''' Decorates the input string by wrapping each character with the specified decorative symbols
  44.        ''' for its left and right sides.
  45.        ''' <para></para>
  46.        ''' For example, if the input string is 'ABC', the resulting string could be similar to this: '{A}{B}{C}'.
  47.        ''' </summary>
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        ''' <param name="input">
  50.        ''' The input string to decorate.
  51.        ''' </param>
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        ''' <param name="leftChar">
  54.        ''' The character used for decorating the left side of the characters in the input string.
  55.        ''' </param>
  56.        '''
  57.        ''' <param name="rightChar">
  58.        ''' The character used for decorating the right side of the characters in the input string.
  59.        ''' </param>
  60.        '''
  61.        ''' <param name="surroundNonAlphanumeric">
  62.        ''' If true, also decorates non-alphanumeric characters.
  63.        ''' <para></para>
  64.        ''' Default value is: False.
  65.        ''' </param>
  66.        '''
  67.        ''' <param name="squishRepeatedDecorationChars">
  68.        ''' If true, and if <paramref name="leftChar"/> and <paramref name="rightChar"/> are the same characters,
  69.        ''' only draws the decorative symbol for the left side of the characters in the input string.
  70.        ''' <para></para>
  71.        ''' Default value is: False.
  72.        ''' </param>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        ''' <returns>
  75.        ''' The resulting decorated string.
  76.        ''' </returns>
  77.        ''' ----------------------------------------------------------------------------------------------------
  78.        <DebuggerStepThrough>
  79.        Public Shared Function WrapCharacters(input As String, leftChar As Char, rightChar As Char,
  80.                                              Optional surroundNonAlphanumeric As Boolean = False,
  81.                                              Optional squishRepeatedDecorationChars As Boolean = False) As String
  82.  
  83.            If String.IsNullOrEmpty(input) Then
  84.                Throw New ArgumentNullException(paramName:=NameOf(input))
  85.            End If
  86.  
  87.            If leftChar.Equals(Nothing) Then
  88.                Throw New ArgumentNullException(paramName:=NameOf(leftChar))
  89.            End If
  90.  
  91.            If rightChar.Equals(Nothing) Then
  92.                Throw New ArgumentNullException(paramName:=NameOf(rightChar))
  93.            End If
  94.  
  95.            Dim areSameDecorationChars As Boolean = (leftChar = rightChar)
  96.  
  97.            Dim sb As New StringBuilder()
  98.            For Each c As Char In input
  99.                Dim decoratedChar As String =
  100.                If(Char.IsLetterOrDigit(c) OrElse (surroundNonAlphanumeric AndAlso Not Char.IsWhiteSpace(c)),
  101.                   If(squishRepeatedDecorationChars AndAlso areSameDecorationChars,
  102.                      $"{leftChar}{c}",
  103.                      $"{leftChar}{c}{rightChar}"),
  104.                   c)
  105.  
  106.                sb.Append(decoratedChar)
  107.            Next
  108.  
  109.            Return sb.ToString()
  110.        End Function
  111.  
  112. #End Region
  113.  
  114.    End Class
  115.  
  116. End Namespace
  117.  
  118. #End Region
  119.  
  120.  
En línea

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

Desconectado Desconectado

Mensajes: 121



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

Un algoritmo para dibujar cajas unicode envolviendo un texto. Útil para decorar la interfaz de aplicaciones de consola.

Inspirado en este servicio: https://onlinetexttools.com/draw-box-around-text
( el resultado debería ser idéntico. )

Ejemplo de uso:

Código
  1. Dim input As String = "Push this button!"
  2. Dim verticalPadding As Integer = 1
  3. Dim horizontalPadding As Integer = 2
  4. Dim fillChar As Char = "&#9608;"c
  5. Dim drawingStyle As New BoxDrawingStyle With {
  6.        .Top = "&#9552;"c, .Bottom = "&#9552;"c,
  7.        .Left = "&#9553;"c, .Right = "&#9553;"c,
  8.        .TopLeft = "&#9556;"c,
  9.        .TopRight = "&#9559;"c,
  10.        .BottomLeft = "&#9562;"c,
  11.        .BottomRight = "&#9565;"c
  12.    }
  13.  
  14. Dim result As String = DrawTextBox(input, verticalPadding, horizontalPadding, fillChar, drawingStyle)
  15.  
  16. Console.WriteLine(result)
  17. IO.File.WriteAllText("\box.txt", result, Encoding.Unicode)
  18.  

Salida:




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. ' DrawTextBox(String, Opt: Integer, Opt: Integer, Opt: Char, Opt: BoxDrawingStyle) 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.Linq
  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.        ''' Draws a box around the specified text, that is, a text-box.
  44.        ''' </summary>
  45.        ''' ----------------------------------------------------------------------------------------------------
  46.        ''' <example> This is a code example.
  47.        ''' <code language="VB.NET">
  48.        ''' Dim input As String = "Push this button!"
  49.        ''' Dim verticalPadding As Integer = 1
  50.        ''' Dim horizontalPadding As Integer = 2
  51.        ''' Dim fillChar As Char = "&#9608;"c
  52.        ''' Dim drawingStyle As New BoxDrawingStyle With {
  53.        '''         .Top = "&#9552;"c, .Bottom = "&#9552;"c,
  54.        '''         .Left = "&#9553;"c, .Right = "&#9553;"c,
  55.        '''         .TopLeft = "&#9556;"c,
  56.        '''         .TopRight = "&#9559;"c,
  57.        '''         .BottomLeft = "&#9562;"c,
  58.        '''         .BottomRight = "&#9565;"c
  59.        '''     }
  60.        '''
  61.        ''' Dim result As String = DrawTextBox(input, verticalPadding, horizontalPadding, fillChar, drawingStyle)
  62.        '''
  63.        ''' Console.WriteLine(result)
  64.        ''' IO.File.WriteAllText("\box.txt", result, Encoding.Unicode)
  65.        ''' ' Output:
  66.        ''' ' &#9556;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9559;
  67.        ''' ' &#9553;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9553;
  68.        ''' ' &#9553;&#9608;&#9608;Push this button!&#9608;&#9608;&#9553;
  69.        ''' ' &#9553;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9553;
  70.        ''' ' &#9562;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9565;
  71.        ''' </code>
  72.        ''' </example>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        ''' <param name="input">
  75.        ''' The input text to be boxed.
  76.        ''' </param>
  77.        '''
  78.        ''' <param name="verticalPadding">
  79.        ''' Optional. The number of vertical padding lines. Default value is: '0'.
  80.        ''' </param>
  81.        '''
  82.        ''' <param name="horizontalPadding">
  83.        ''' Optional. The number of horizontal padding characters. Default value is: '0'.
  84.        ''' </param>
  85.        '''
  86.        ''' <param name="fillChar">
  87.        ''' Optional. The character used to fill the empty space in the box. Default value is: " " (white-space).
  88.        ''' </param>
  89.        '''
  90.        ''' <param name="drawingStyle">
  91.        ''' Optional. The style of the box drawing. If not specified, a default style will be used.
  92.        ''' <para></para>
  93.        ''' If this value is null, "-" character is used for vertical sides,
  94.        ''' "|" for horizontal sides and "+" for all corners.
  95.        ''' <para></para>
  96.        ''' Default value is: null.
  97.        ''' </param>
  98.        ''' ----------------------------------------------------------------------------------------------------
  99.        ''' <returns>
  100.        ''' The resulting string containing the text enclosed in the box.
  101.        ''' </returns>
  102.        ''' --------------------------------------------------------------------------------------------------
  103.        <DebuggerStepThrough>
  104.        Public Shared Function DrawTextBox(input As String,
  105.                                           Optional verticalPadding As Integer = 0,
  106.                                           Optional horizontalPadding As Integer = 0,
  107.                                           Optional fillChar As Char = " "c,
  108.                                           Optional drawingStyle As BoxDrawingStyle = Nothing) As String
  109.  
  110.  
  111.            If String.IsNullOrEmpty(input) Then
  112.                Throw New ArgumentNullException(paramName:=NameOf(input))
  113.            End If
  114.  
  115.            If verticalPadding < 0 Then
  116.                Throw New ArgumentException("Value can't be less than zero.", paramName:=NameOf(input))
  117.            End If
  118.  
  119.            If horizontalPadding < 0 Then
  120.                Throw New ArgumentException("Value can't be less than zero.", paramName:=NameOf(input))
  121.            End If
  122.  
  123.            If fillChar.Equals(Nothing) Then
  124.                Throw New ArgumentNullException(paramName:=NameOf(fillChar))
  125.            End If
  126.  
  127.            If drawingStyle = BoxDrawingStyle.Empty Then
  128.                drawingStyle = New BoxDrawingStyle With {
  129.                .Top = "-"c, .Bottom = "-"c,
  130.                .Left = "|"c, .Right = "|"c,
  131.                .TopLeft = "+"c,
  132.                .TopRight = "+"c,
  133.                .BottomLeft = "+"c,
  134.                .BottomRight = "+"c
  135.            }
  136.            End If
  137.  
  138.            Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.None)
  139.            Dim linesLength As Integer = lines.Length
  140.            Dim maxLength As Integer = lines.Max(Function(line As String) line.Length)
  141.            Dim boxWidth As Integer = maxLength + (horizontalPadding * 2)
  142.            Dim boxHeight As Integer = linesLength + (verticalPadding * 2)
  143.  
  144.            Dim sb As New StringBuilder()
  145.  
  146.            ' Draw top line.
  147.            sb.AppendLine(drawingStyle.TopLeft & New String(drawingStyle.Top, boxWidth) & drawingStyle.TopRight)
  148.  
  149.            ' Draw top padding line(s).
  150.            For i As Integer = 0 To verticalPadding - 1
  151.                sb.AppendLine(drawingStyle.Left & New String(fillChar, boxWidth) & drawingStyle.Right)
  152.            Next
  153.  
  154.            ' Draw inner line(s).
  155.            For i As Integer = 0 To lines.Length - 1
  156.                Dim paddedLine As String = lines(i).PadRight(maxLength, fillChar)
  157.                sb.AppendLine(drawingStyle.Left & New String(fillChar, horizontalPadding) & paddedLine & New String(fillChar, horizontalPadding) & drawingStyle.Right)
  158.            Next
  159.  
  160.            ' Draw bottom padding line(s).
  161.            For i As Integer = 0 To verticalPadding - 1
  162.                sb.AppendLine(drawingStyle.Left & New String(fillChar, boxWidth) & drawingStyle.Right)
  163.            Next
  164.  
  165.            ' Draw bottom line.
  166.            sb.AppendLine(drawingStyle.BottomLeft & New String(drawingStyle.Bottom, boxWidth) & drawingStyle.BottomRight)
  167.            Return sb.ToString()
  168.        End Function
  169.  
  170. #End Region
  171.  
  172.    End Class
  173.  
  174. End Namespace
  175.  
  176. #End Region
  177.  



BoxDrawingStyle.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 " Usage Examples "
  15.  
  16. #End Region
  17.  
  18. #Region " Imports "
  19.  
  20. Imports System.Runtime.InteropServices
  21. Imports System.Xml.Serialization
  22.  
  23. #End Region
  24.  
  25. #Region " BoxDrawingStyle "
  26.  
  27. ' ReSharper disable once CheckNamespace
  28.  
  29. Namespace DevCase.Core.DataProcessing.Common
  30.  
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    ''' <summary>
  33.    ''' Defines the characters used to draw the sides and corners of a box.
  34.    ''' </summary>
  35.    ''' --------------------------------------------------------------------------------------------------
  36.    <Serializable>
  37.    <XmlRoot(NameOf(BoxDrawingStyle))>
  38.    <StructLayout(LayoutKind.Sequential)>
  39.    Public Structure BoxDrawingStyle
  40.  
  41. #Region " Fields "
  42.  
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        ''' <summary>
  45.        ''' The character used for the top line of the box.
  46.        ''' </summary>
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        Public Top As Char
  49.  
  50.        ''' ----------------------------------------------------------------------------------------------------
  51.        ''' <summary>
  52.        ''' The character used for the bottom line of the box.
  53.        ''' </summary>
  54.        ''' ----------------------------------------------------------------------------------------------------
  55.        Public Bottom As Char
  56.  
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <summary>
  59.        ''' The character used for the left border of the box.
  60.        ''' </summary>
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        Public Left As Char
  63.  
  64.        ''' ----------------------------------------------------------------------------------------------------
  65.        ''' <summary>
  66.        ''' The character used for the right border of the box.
  67.        ''' </summary>
  68.        ''' ----------------------------------------------------------------------------------------------------
  69.        Public Right As Char
  70.  
  71.        ''' ----------------------------------------------------------------------------------------------------
  72.        ''' <summary>
  73.        ''' The character used for the top-left corner of the box.
  74.        ''' </summary>
  75.        ''' ----------------------------------------------------------------------------------------------------
  76.        Public TopLeft As Char
  77.  
  78.        ''' ----------------------------------------------------------------------------------------------------
  79.        ''' <summary>
  80.        ''' The character used for the top-right corner of the box.
  81.        ''' </summary>
  82.        ''' ----------------------------------------------------------------------------------------------------
  83.        Public TopRight As Char
  84.  
  85.        ''' ----------------------------------------------------------------------------------------------------
  86.        ''' <summary>
  87.        ''' The character used for the bottom-left corner of the box.
  88.        ''' </summary>
  89.        ''' ----------------------------------------------------------------------------------------------------
  90.        Public BottomLeft As Char
  91.  
  92.        ''' ----------------------------------------------------------------------------------------------------
  93.        ''' <summary>
  94.        ''' The character used for the bottom-right corner of the box.
  95.        ''' </summary>
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        Public BottomRight As Char
  98.  
  99. #End Region
  100.  
  101. #Region " Properties "
  102.  
  103.        ''' ----------------------------------------------------------------------------------------------------
  104.        ''' <summary>
  105.        ''' Gets a <see cref="BoxDrawingStyle"/> with all characters set to null.
  106.        ''' </summary>
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        Public Shared ReadOnly Property Empty As BoxDrawingStyle
  109.            Get
  110.                Return New BoxDrawingStyle()
  111.            End Get
  112.        End Property
  113.  
  114. #End Region
  115.  
  116. #Region " Public Methods "
  117.  
  118.        ''' ----------------------------------------------------------------------------------------------------
  119.        ''' <summary>
  120.        ''' Determines whether this instance of <see cref="BoxDrawingStyle"/> is equal to another object.
  121.        ''' </summary>
  122.        ''' ----------------------------------------------------------------------------------------------------
  123.        ''' <param name="obj">
  124.        ''' The object to compare with this instance.
  125.        ''' </param>
  126.        ''' ----------------------------------------------------------------------------------------------------
  127.        ''' <returns>
  128.        ''' <see langword="true"/> if the specified object is equal to this instance;
  129.        ''' otherwise, <see langword="false"/>.
  130.        ''' </returns>
  131.        ''' ----------------------------------------------------------------------------------------------------
  132.        Public Overrides Function Equals(obj As Object) As Boolean
  133.            If TypeOf obj Is BoxDrawingStyle Then
  134.                Dim otherStyle As BoxDrawingStyle = DirectCast(obj, BoxDrawingStyle)
  135.                Return Me.Top = otherStyle.Top AndAlso
  136.                       Me.Bottom = otherStyle.Bottom AndAlso
  137.                       Me.Left = otherStyle.Left AndAlso
  138.                       Me.Right = otherStyle.Right AndAlso
  139.                       Me.TopLeft = otherStyle.TopLeft AndAlso
  140.                       Me.TopRight = otherStyle.TopRight AndAlso
  141.                       Me.BottomLeft = otherStyle.BottomLeft AndAlso
  142.                       Me.BottomRight = otherStyle.BottomRight
  143.            End If
  144.            Return False
  145.        End Function
  146.  
  147. #End Region
  148.  
  149. #Region " Operators "
  150.  
  151.        ''' ----------------------------------------------------------------------------------------------------
  152.        ''' <summary>
  153.        ''' Determines whether two instances of <see cref="BoxDrawingStyle"/> are equal.
  154.        ''' </summary>
  155.        ''' ----------------------------------------------------------------------------------------------------
  156.        ''' <param name="style1">
  157.        ''' The first <see cref="BoxDrawingStyle"/> to compare.
  158.        ''' </param>
  159.        '''
  160.        ''' <param name="style2">
  161.        ''' The second <see cref="BoxDrawingStyle"/> to compare.
  162.        ''' </param>
  163.        ''' ----------------------------------------------------------------------------------------------------
  164.        ''' <returns>
  165.        ''' <see langword="true"/> if the specified instances are equal; otherwise, <see langword="false"/>.
  166.        ''' </returns>
  167.        ''' ----------------------------------------------------------------------------------------------------
  168.        Public Shared Operator =(style1 As BoxDrawingStyle, style2 As BoxDrawingStyle) As Boolean
  169.            Return style1.Top = style2.Top AndAlso
  170.                       style1.Bottom = style2.Bottom AndAlso
  171.                       style1.Left = style2.Left AndAlso
  172.                       style1.Right = style2.Right AndAlso
  173.                       style1.TopLeft = style2.TopLeft AndAlso
  174.                       style1.TopRight = style2.TopRight AndAlso
  175.                       style1.BottomLeft = style2.BottomLeft AndAlso
  176.                       style1.BottomRight = style2.BottomRight
  177.        End Operator
  178.  
  179.        ''' ----------------------------------------------------------------------------------------------------
  180.        ''' <summary>
  181.        ''' Determines whether two instances of <see cref="BoxDrawingStyle"/> are not equal.
  182.        ''' </summary>
  183.        ''' ----------------------------------------------------------------------------------------------------
  184.        ''' <param name="style1">
  185.        ''' The first <see cref="BoxDrawingStyle"/> to compare.
  186.        ''' </param>
  187.        '''
  188.        ''' <param name="style2">
  189.        ''' The second <see cref="BoxDrawingStyle"/> to compare.
  190.        ''' </param>
  191.        ''' ----------------------------------------------------------------------------------------------------
  192.        ''' <returns>
  193.        ''' <see langword="true"/> if the specified instances are not equal; otherwise, <see langword="false"/>.
  194.        ''' </returns>
  195.        ''' ----------------------------------------------------------------------------------------------------
  196.        Public Shared Operator <>(style1 As BoxDrawingStyle, style2 As BoxDrawingStyle) As Boolean
  197.            Return Not (style1 = style2)
  198.        End Operator
  199.  
  200. #End Region
  201.  
  202.    End Structure
  203.  
  204. End Namespace
  205.  
  206. #End Region
  207.  
En línea

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

Desconectado Desconectado

Mensajes: 121



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

Algunos atajos a modo de extensiones de métodos para simplificar la generación de excepciones al cumplir cierta condición en un objeto.

Ejemplos de uso:

- Object.ThrowIf
Código
  1. Dim value As Integer = 0
  2. ' value.ThrowIf(Of ArgumentOutOfRangeException)(Function(x) x = 0)
  3. value.ThrowIf(Function(x) x = 0, New ArgumentOutOfRangeException(paramName:=NameOf(value)))

- Object.ThrowIfNotInRange
Código
  1. Dim value As Integer = 10
  2. ' value.ThrowIfNotInRange(min:=1, max:=9)
  3. value.ThrowIfNotInRange(min:=1, max:=9, message:="Value is not within the allowed range.", paramName:=NameOf(value))

- Object.ThrowIfNull
Código
  1. Dim obj As Object = Nothing
  2. ' obj.ThrowIfNull(Of ArgumentNullException)
  3. obj.ThrowIfNull(New ArgumentNullException(paramName:=NameOf(obj)))

- Object.ThrowIfDefault
Código
  1. Dim obj As Integer = 0
  2. ' obj.ThrowIfDefault(Of ArgumentNullException)
  3. obj.ThrowIfDefault(New ArgumentNullException(paramName:=NameOf(obj)))



Y para un valor booleano:

- Boolean.ThrowIfFalse
Código
  1. Dim value As Boolean = False
  2. ' value.ThrowIfFalse(Of ArgumentException)
  3. value.ThrowIfFalse(New ArgumentException(message:="'true' expected.", paramName:=NameOf(value)))

- Boolean.ThrowIfTrue
Código
  1. Dim value As Boolean = True
  2. ' value.ThrowIfTrue(Of ArgumentException)
  3. value.ThrowIfTrue(New ArgumentException(message:="'false' expected.", paramName:=NameOf(value)))



ObjectExtensions.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 09-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' Object.ThrowIf(Of TObject, TException As Exception)(Func(Of TObject, Boolean), Opt: TException)
  9. ' Object.ThrowIfNull(Of TException As Exception)(Opt: TException)
  10. ' Object.ThrowIfDefault(Of TException As Exception)(Opt: TException)
  11. ' Object.ThrowIfNotInRange(T, T, Opt: String, Opt: String)
  12.  
  13. ' Object.IsDefault As Boolean
  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.ComponentModel
  28. Imports System.Reflection
  29. Imports System.Runtime.CompilerServices
  30.  
  31. #End Region
  32.  
  33. #Region " Object Extensions "
  34.  
  35. ' ReSharper disable once CheckNamespace
  36.  
  37. Namespace DevCase.Extensions.ObjectExtensions
  38.  
  39.    ''' ----------------------------------------------------------------------------------------------------
  40.    ''' <summary>
  41.    ''' Contains custom extension methods to use with the <see cref="Object"/> type.
  42.    ''' </summary>
  43.    ''' ----------------------------------------------------------------------------------------------------
  44.    <ImmutableObject(True)>
  45.    <HideModuleName>
  46.    Public Module ObjectExtensions
  47.  
  48. #Region " Public Extension Methods "
  49.  
  50.        ''' ----------------------------------------------------------------------------------------------------
  51.        ''' <summary>
  52.        ''' Throws the specified exception if the given condition in the source object is true.
  53.        ''' </summary>
  54.        ''' ----------------------------------------------------------------------------------------------------
  55.        ''' <example> This is a code example.
  56.        ''' <code language="VB.NET">
  57.        ''' Dim value As Integer = 0
  58.        ''' ' value.ThrowIf(Of ArgumentOutOfRangeException)(Function(x) x = 0)
  59.        ''' value.ThrowIf(Function(x) x = 0, New ArgumentOutOfRangeException(paramName:=NameOf(value)))
  60.        ''' </code>
  61.        ''' </example>
  62.        ''' ----------------------------------------------------------------------------------------------------
  63.        ''' <typeparam name="TObject">
  64.        ''' The type of object to evaluate.
  65.        ''' </typeparam>
  66.        '''
  67.        ''' <typeparam name="TException">
  68.        ''' The type of exception to throw.
  69.        ''' </typeparam>
  70.        '''
  71.        ''' <param name="obj">
  72.        ''' The object to evaluate.
  73.        ''' </param>
  74.        '''
  75.        ''' <param name="predicate">
  76.        ''' The predicate function to evaluate the object.
  77.        ''' </param>
  78.        '''
  79.        ''' <param name="ex">
  80.        ''' Optionally, a instance of the exception to throw when
  81.        ''' the <paramref name="predicate"/> condition is true.
  82.        ''' <para></para>
  83.        ''' If this value is null, a default instance of the exception type will be used.
  84.        ''' </param>
  85.        ''' ----------------------------------------------------------------------------------------------------
  86.        <DebuggerStepThrough>
  87.        <Extension>
  88.        <EditorBrowsable(EditorBrowsableState.Always)>
  89.        Public Sub ThrowIf(Of TObject, TException As Exception)(obj As TObject,
  90.                                                                predicate As Func(Of TObject, Boolean),
  91.                                                                Optional ex As TException = Nothing)
  92.  
  93.            If predicate(obj) Then
  94.                If ex Is Nothing Then
  95.                    ex = Activator.CreateInstance(Of TException)
  96.                End If
  97.                Throw ex
  98.            End If
  99.        End Sub
  100.  
  101.        ''' ----------------------------------------------------------------------------------------------------
  102.        ''' <summary>
  103.        ''' Throws the specified exception if the source object is null.
  104.        ''' </summary>
  105.        ''' ----------------------------------------------------------------------------------------------------
  106.        ''' <example> This is a code example.
  107.        ''' <code language="VB.NET">
  108.        ''' Dim obj As Object = Nothing
  109.        ''' ' obj.ThrowIfNull(Of ArgumentNullException)
  110.        ''' obj.ThrowIfNull(New ArgumentNullException(paramName:=NameOf(obj)))
  111.        ''' </code>
  112.        ''' </example>
  113.        ''' ----------------------------------------------------------------------------------------------------
  114.        ''' <typeparam name="TException">
  115.        ''' The type of exception to throw.
  116.        ''' </typeparam>
  117.        '''
  118.        ''' <param name="obj">
  119.        ''' The object to check for null.
  120.        ''' </param>
  121.        '''
  122.        ''' <param name="ex">
  123.        ''' Optionally, a instance of the exception to throw when the source object is null.
  124.        ''' <para></para>
  125.        ''' If this value is null, a default instance of the exception type will be used.
  126.        ''' </param>
  127.        ''' ----------------------------------------------------------------------------------------------------
  128.        <DebuggerStepThrough>
  129.        <Extension>
  130.        <EditorBrowsable(EditorBrowsableState.Always)>
  131.        Public Sub ThrowIfNull(Of TException As Exception)(obj As Object, Optional ex As TException = Nothing)
  132.  
  133.            If obj Is Nothing Then
  134.                If ex Is Nothing Then
  135.                    ex = Activator.CreateInstance(Of TException)
  136.                End If
  137.                Throw ex
  138.            End If
  139.  
  140.        End Sub
  141.  
  142.        ''' ----------------------------------------------------------------------------------------------------
  143.        ''' <summary>
  144.        ''' Throws the specified exception if the source object is the default value of its type.
  145.        ''' </summary>
  146.        ''' ----------------------------------------------------------------------------------------------------
  147.        ''' <example> This is a code example.
  148.        ''' <code language="VB.NET">
  149.        ''' Dim obj As Integer = 0
  150.        ''' ' obj.ThrowIfDefault(Of ArgumentNullException)
  151.        ''' obj.ThrowIfDefault(New ArgumentNullException(paramName:=NameOf(obj)))
  152.        ''' </code>
  153.        ''' </example>
  154.        ''' ----------------------------------------------------------------------------------------------------
  155.        ''' <typeparam name="TException">
  156.        ''' The type of exception to throw.
  157.        ''' </typeparam>
  158.        '''
  159.        ''' <param name="obj">
  160.        ''' The object to evaluate.
  161.        ''' </param>
  162.        '''
  163.        ''' <param name="ex">
  164.        ''' Optionally, a instance of the exception to throw when the source object is the default value of its type.
  165.        ''' <para></para>
  166.        ''' If this value is null, a default instance of the exception type will be used.
  167.        ''' </param>
  168.        ''' ----------------------------------------------------------------------------------------------------
  169.        <DebuggerStepThrough>
  170.        <Extension>
  171.        <EditorBrowsable(EditorBrowsableState.Always)>
  172.        Public Sub ThrowIfDefault(Of TObject, TException As Exception)(obj As TObject, Optional ex As TException = Nothing)
  173.            If obj.IsDefault() Then
  174.                If ex Is Nothing Then
  175.                    ex = Activator.CreateInstance(Of TException)
  176.                End If
  177.                Throw ex
  178.            End If
  179.        End Sub
  180.  
  181.        ''' ----------------------------------------------------------------------------------------------------
  182.        ''' <summary>
  183.        ''' Throws an <see cref="ArgumentOutOfRangeException"/> if the
  184.        ''' source value is not within the specified range.
  185.        ''' </summary>
  186.        ''' ----------------------------------------------------------------------------------------------------
  187.        ''' <example> This is a code example.
  188.        ''' <code language="VB.NET">
  189.        ''' Dim value As Integer = 10
  190.        ''' ' value.ThrowIfNotInRange(min:=1, max:=9)
  191.        ''' value.ThrowIfNotInRange(min:=1, max:=9, message:="Value is not within the allowed range.", paramName:=NameOf(value))
  192.        ''' </code>
  193.        ''' </example>
  194.        ''' ----------------------------------------------------------------------------------------------------
  195.        ''' <typeparam name="T">
  196.        ''' The type of value to evaluate.
  197.        ''' </typeparam>
  198.        '''
  199.        ''' <param name="value">
  200.        ''' The value to evaluate.
  201.        ''' </param>
  202.        '''
  203.        ''' <param name="min">
  204.        ''' The minimum allowed value (inclusive).
  205.        ''' </param>
  206.        '''
  207.        ''' <param name="max">
  208.        ''' The maximum allowed value (inclusive).
  209.        ''' </param>
  210.        '''
  211.        ''' <param name="message">
  212.        ''' Optionally, the custom error message for the <see cref="ArgumentOutOfRangeException"/>.
  213.        ''' </param>
  214.        '''
  215.        ''' <param name="paramName">
  216.        ''' Optionally, the name of the parameter that caused the <see cref="ArgumentOutOfRangeException"/>.
  217.        ''' </param>
  218.        ''' ----------------------------------------------------------------------------------------------------
  219.        ''' <exception cref="ArgumentOutOfRangeException">
  220.        ''' Thrown when the value is not within the specified range.
  221.        ''' </exception>
  222.        ''' ----------------------------------------------------------------------------------------------------
  223.        <DebuggerStepThrough>
  224.        <Extension>
  225.        <EditorBrowsable(EditorBrowsableState.Always)>
  226.        Public Sub ThrowIfNotInRange(Of T As {IComparable(Of T), IConvertible, IEquatable(Of T), IFormattable})(value As T, min As T, max As T,
  227.                                                                                                                Optional message As String = Nothing,
  228.                                                                                                                Optional paramName As String = Nothing)
  229.  
  230.            If value.CompareTo(min) < 0 OrElse value.CompareTo(max) > 0 Then
  231. #Disable Warning CA2208 ' Instantiate argument exceptions correctly
  232.                Dim ex As New ArgumentOutOfRangeException()
  233. #Enable Warning CA2208 ' Instantiate argument exceptions correctly
  234.                Dim messageField As FieldInfo = Nothing
  235.                Dim actualValueField As FieldInfo = Nothing
  236.                Dim paramNameField As FieldInfo = Nothing
  237.                Dim bindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic
  238.  
  239.                Dim exType As Type = ex.GetType()
  240.                If actualValueField Is Nothing Then
  241.                    actualValueField = exType.GetField("m_actualValue", bindingFlags)
  242.                End If
  243.  
  244.                Do While exType IsNot Nothing AndAlso
  245.                        ((message IsNot Nothing AndAlso messageField Is Nothing) OrElse
  246.                         (paramName IsNot Nothing AndAlso paramNameField Is Nothing))
  247.  
  248.                    If actualValueField Is Nothing Then
  249.                        actualValueField = exType.GetField("m_actualValue", bindingFlags)
  250.                    End If
  251.  
  252.                    If message IsNot Nothing AndAlso messageField Is Nothing Then
  253.                        messageField = exType.GetField("_message", bindingFlags)
  254.                    End If
  255.  
  256.                    If paramName IsNot Nothing AndAlso paramNameField Is Nothing Then
  257.                        paramNameField = exType.GetField("m_paramName", bindingFlags)
  258.                    End If
  259.  
  260.                    exType = exType.BaseType
  261.                Loop
  262.  
  263.                actualValueField?.SetValue(ex, value)
  264.                messageField?.SetValue(ex, message)
  265.                paramNameField?.SetValue(ex, paramName)
  266.                Throw ex
  267.            End If
  268.        End Sub
  269.  
  270.        ''' ----------------------------------------------------------------------------------------------------
  271.        ''' <summary>
  272.        ''' Determines whether the source object is the default value of its type.
  273.        ''' </summary>
  274.        ''' ----------------------------------------------------------------------------------------------------
  275.        ''' <typeparam name="T">
  276.        ''' The type of the objectto evaluate.
  277.        ''' </typeparam>
  278.        '''
  279.        ''' <param name="obj">
  280.        ''' The object to evaluate.
  281.        ''' </param>
  282.        ''' ----------------------------------------------------------------------------------------------------
  283.        ''' <returns>
  284.        ''' Returns True if the source object is the default value of its type; otherwise, False.
  285.        ''' </returns>
  286.        ''' ----------------------------------------------------------------------------------------------------
  287.        <DebuggerStepThrough>
  288.        <Extension>
  289.        <EditorBrowsable(EditorBrowsableState.Always)>
  290.        Public Function IsDefault(Of T)(obj As T) As Boolean
  291.            Return EqualityComparer(Of T).Default.Equals(obj, Nothing)
  292.        End Function
  293.  
  294. #End Region
  295.  
  296.    End Module
  297.  
  298. End Namespace
  299.  
  300. #End Region
  301.  




BooleanExtensions.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 09-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' Boolean.ThrowIfTrue(Of TException As Exception)(Opt: TException)
  9. ' Boolean.ThrowIfFalse(Of TException As Exception)(Opt: TException)
  10.  
  11. #End Region
  12.  
  13. #Region " Option Statements "
  14.  
  15. Option Strict On
  16. Option Explicit On
  17. Option Infer Off
  18.  
  19. #End Region
  20.  
  21. #Region " Imports "
  22.  
  23. Imports System.ComponentModel
  24. Imports System.Runtime.CompilerServices
  25.  
  26. #End Region
  27.  
  28. #Region " Boolean Extensions "
  29.  
  30. ' ReSharper disable once CheckNamespace
  31.  
  32. Namespace DevCase.Extensions.BooleanExtensions
  33.  
  34.    ''' ----------------------------------------------------------------------------------------------------
  35.    ''' <summary>
  36.    ''' Contains custom extension methods to use with <see cref="Boolean"/> datatype.
  37.    ''' </summary>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    <HideModuleName>
  40.    Public Module BooleanExtensions
  41.  
  42. #Region " Public Extension Methods "
  43.  
  44.        ''' ----------------------------------------------------------------------------------------------------
  45.        ''' <summary>
  46.        ''' Throws an exception if the source value is true.
  47.        ''' </summary>
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        ''' <example> This is a code example.
  50.        ''' <code language="VB.NET">
  51.        ''' Dim value As Boolean = True
  52.        ''' ' value.ThrowIfTrue(Of ArgumentException)
  53.        ''' value.ThrowIfTrue(New ArgumentException(message:="'false' expected.", paramName:=NameOf(value)))
  54.        ''' </code>
  55.        ''' </example>
  56.        ''' ----------------------------------------------------------------------------------------------------        '''
  57.        ''' <typeparam name="TException">
  58.        ''' The type of exception to throw.
  59.        ''' </typeparam>
  60.        '''
  61.        ''' <param name="value">
  62.        ''' The value to evaluate.
  63.        ''' </param>
  64.        '''
  65.        ''' <param name="ex">
  66.        ''' Optionally, a instance of the exception to throw if the source <paramref name="value"/> is true.
  67.        ''' <para></para>
  68.        ''' If this value is null, a default instance of the exception type will be used.
  69.        ''' </param>
  70.        ''' ----------------------------------------------------------------------------------------------------
  71.        <DebuggerStepThrough>
  72.        <Extension>
  73.        <EditorBrowsable(EditorBrowsableState.Always)>
  74.        Public Sub ThrowIfTrue(Of TException As Exception)(value As Boolean, Optional ex As TException = Nothing)
  75.  
  76.            If value Then
  77.                If ex Is Nothing Then
  78.                    ex = Activator.CreateInstance(Of TException)
  79.                End If
  80.                Throw ex
  81.            End If
  82.  
  83.        End Sub
  84.  
  85.        ''' ----------------------------------------------------------------------------------------------------
  86.        ''' <summary>
  87.        ''' Throws an exception if the source value is false.
  88.        ''' </summary>
  89.        ''' ----------------------------------------------------------------------------------------------------
  90.        ''' <example> This is a code example.
  91.        ''' <code language="VB.NET">
  92.        ''' Dim value As Boolean = False
  93.        ''' ' value.ThrowIfFalse(Of ArgumentException)
  94.        ''' value.ThrowIfFalse(New ArgumentException(message:="'true' expected.", paramName:=NameOf(value)))
  95.        ''' </code>
  96.        ''' </example>
  97.        ''' ----------------------------------------------------------------------------------------------------        '''
  98.        ''' <typeparam name="TException">
  99.        ''' The type of exception to throw.
  100.        ''' </typeparam>
  101.        '''
  102.        ''' <param name="value">
  103.        ''' The value to evaluate.
  104.        ''' </param>
  105.        '''
  106.        ''' <param name="ex">
  107.        ''' Optionally, a instance of the exception to throw if the source <paramref name="value"/> is false.
  108.        ''' <para></para>
  109.        ''' If this value is null, a default instance of the exception type will be used.
  110.        ''' </param>
  111.        ''' ----------------------------------------------------------------------------------------------------
  112.        <DebuggerStepThrough>
  113.        <Extension>
  114.        <EditorBrowsable(EditorBrowsableState.Always)>
  115.        Public Sub ThrowIfFalse(Of TException As Exception)(value As Boolean, Optional ex As TException = Nothing)
  116.  
  117.            If Not value Then
  118.                If ex Is Nothing Then
  119.                    ex = Activator.CreateInstance(Of TException)
  120.                End If
  121.                Throw ex
  122.            End If
  123.  
  124.        End Sub
  125.  
  126. #End Region
  127.  
  128.    End Module
  129.  
  130. End Namespace
  131.  
  132. #End Region
  133.  
En línea

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

Desconectado Desconectado

Mensajes: 121



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

Un código para forzar la eliminación de un directorio (que tenga el atributo de 'solo lectura') y sus subdirectorios.

Y también para forzar la eliminación o el reciclado de un archivo (que tenga el atributo de 'solo lectura').

Nota: este código no modifica los permisos de usuario de archivos ni de carpetas.



DirectoryInfoExtensions.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 09-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' DirectoryInfo.ForceDelete()
  9. ' DirectoryInfo.ForceDelete(Boolean)
  10.  
  11. #End Region
  12.  
  13. #Region " Option Statements "
  14.  
  15. Option Strict On
  16. Option Explicit On
  17. Option Infer Off
  18.  
  19. #End Region
  20.  
  21. #Region " Imports "
  22.  
  23. Imports System.ComponentModel
  24. Imports System.IO
  25. Imports System.Runtime.CompilerServices
  26. Imports System.Security
  27.  
  28. Imports DevCase.Win32
  29.  
  30. #End Region
  31.  
  32. #Region " DirectoryInfo Extensions "
  33.  
  34. ' ReSharper disable once CheckNamespace
  35.  
  36. Namespace DevCase.Extensions.DirectoryInfoExtensions
  37.  
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    ''' <summary>
  40.    ''' Contains custom extension methods to use with <see cref="Global.System.IO.DirectoryInfo"/> type.
  41.    ''' </summary>
  42.    ''' ----------------------------------------------------------------------------------------------------
  43.    <HideModuleName>
  44.    Public Module DirectoryInfoExtensions
  45.  
  46. #Region " Public Extension Methods "
  47.  
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        ''' <summary>
  50.        ''' Forces the deletion of the specified directory if it is empty,
  51.        ''' by removing the read-only attribute and deleting it.
  52.        ''' </summary>
  53.        ''' ----------------------------------------------------------------------------------------------------
  54.        ''' <param name="directory">
  55.        ''' The directory to be deleted.
  56.        ''' </param>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        <DebuggerStepThrough>
  59.        <Extension>
  60.        <EditorBrowsable(EditorBrowsableState.Always)>
  61.        Public Sub ForceDelete(directory As DirectoryInfo)
  62.  
  63.            If directory.IsRootVolume Then
  64.                Throw New InvalidOperationException($"An attempt to delete the root directory of a volume (""{directory.FullName}"").")
  65.            End If
  66.  
  67.            If directory.IsReadOnly Then
  68.                directory.Attributes = directory.Attributes And Not FileAttributes.ReadOnly
  69.            End If
  70.  
  71.            directory.Delete(recursive:=False)
  72.  
  73.        End Sub
  74.  
  75.        ''' ----------------------------------------------------------------------------------------------------
  76.        ''' <summary>
  77.        ''' Forces the deletion of the specified directory, specifying whether to delete subdirectories and files
  78.        ''' by removing the read-only attribute and deleting them.
  79.        ''' </summary>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <param name="directory">
  82.        ''' The directory to be deleted.
  83.        ''' </param>
  84.        '''
  85.        ''' <param name="recursive">
  86.        ''' True to delete this directory, its subdirectories, and all files; otherwise, False.
  87.        ''' </param>
  88.        ''' ----------------------------------------------------------------------------------------------------
  89.        <DebuggerStepThrough>
  90.        <Extension>
  91.        <EditorBrowsable(EditorBrowsableState.Always)>
  92.        <SecuritySafeCritical>
  93.        Public Sub ForceDelete(directory As DirectoryInfo, recursive As Boolean)
  94.  
  95.            If directory.IsRootVolume Then
  96.                Throw New InvalidOperationException($"An attempt to delete the root directory of a volume (""{directory.FullName}"").")
  97.            End If
  98.  
  99.            If Not recursive AndAlso Not directory.IsEmpty Then
  100.                ' recursive value is False and the user is attempting to delete
  101.                ' a directory that is not empty (it needs recursive deletion).
  102.                '
  103.                ' We let the built-in "Delete" method to throw the exception for us.
  104.                IO.Directory.Delete(directory.FullName, recursive:=False)
  105.            End If
  106.  
  107.            If directory.IsReadOnly Then
  108.                directory.Attributes = directory.Attributes And Not FileAttributes.ReadOnly
  109.            End If
  110.  
  111.            ' Try recursive deletion.
  112.            Try
  113.                For Each subdirectory As DirectoryInfo In directory.GetDirectories("*", SearchOption.AllDirectories)
  114.                    If subdirectory.IsReadOnly Then
  115.                        subdirectory.Attributes = subdirectory.Attributes And Not FileAttributes.ReadOnly
  116.                    End If
  117.                Next
  118.                For Each file As FileInfo In directory.GetFiles("*", SearchOption.AllDirectories)
  119.                    If file.IsReadOnly Then
  120.                        file.Attributes = file.Attributes And Not FileAttributes.ReadOnly
  121.                    End If
  122.                Next
  123.                directory.Delete(recursive:=True)
  124.  
  125.            Catch ex As Exception
  126.                Throw
  127.  
  128.            End Try
  129.  
  130.        End Sub
  131.  
  132.        ''' ----------------------------------------------------------------------------------------------------
  133.        ''' <summary>
  134.        ''' Determines whether the source directory is read-only,
  135.        ''' i.e., it has the <see cref="FileAttributes.ReadOnly"/> attribute.
  136.        ''' </summary>
  137.        ''' ----------------------------------------------------------------------------------------------------
  138.        ''' <param name="directory">
  139.        ''' The directory to check.
  140.        ''' </param>
  141.        ''' ----------------------------------------------------------------------------------------------------
  142.        ''' <returns>
  143.        ''' True if the directory is read-only; otherwise, False.
  144.        ''' </returns>
  145.        ''' ----------------------------------------------------------------------------------------------------
  146.        <DebuggerStepThrough>
  147.        <Extension>
  148.        <EditorBrowsable(EditorBrowsableState.Always)>
  149.        Public Function IsReadOnly(directory As DirectoryInfo) As Boolean
  150.            Return (directory.Attributes And FileAttributes.ReadOnly) <> 0
  151.        End Function
  152.  
  153.        ''' ----------------------------------------------------------------------------------------------------
  154.        ''' <summary>
  155.        ''' Determines whether the <see cref="DirectoryInfo.FullName"/> path
  156.        ''' in the source directory refers to the root of a volume (e.g "C:\").
  157.        ''' </summary>
  158.        ''' ----------------------------------------------------------------------------------------------------
  159.        ''' <param name="directory">
  160.        ''' The directory to check.
  161.        ''' </param>
  162.        ''' ----------------------------------------------------------------------------------------------------
  163.        ''' <returns>
  164.        ''' True if the <see cref="DirectoryInfo.FullName"/> path
  165.        ''' in the source directory refers to the root of a volume (e.g "C:\");
  166.        ''' otherwise, False.
  167.        ''' </returns>
  168.        ''' ----------------------------------------------------------------------------------------------------
  169.        <DebuggerStepThrough>
  170.        <Extension>
  171.        <EditorBrowsable(EditorBrowsableState.Always)>
  172.        Public Function IsRootVolume(directory As DirectoryInfo) As Boolean
  173.            Return NativeMethods.PathCchIsRoot(directory.FullName)
  174.        End Function
  175.  
  176.        ''' ----------------------------------------------------------------------------------------------------
  177.        ''' <summary>
  178.        ''' Determines whether the source directory is empty (contains no files and no directories).
  179.        ''' </summary>
  180.        ''' ----------------------------------------------------------------------------------------------------
  181.        ''' <param name="sender">
  182.        ''' The source <see cref="Global.System.IO.DirectoryInfo"/>.
  183.        ''' </param>
  184.        ''' ----------------------------------------------------------------------------------------------------
  185.        ''' <returns>
  186.        ''' <see langword="True"/> if the directory is empty (contains no files and no directories),
  187.        ''' otherwise, <see langword="False"/>.
  188.        ''' </returns>
  189.        ''' ----------------------------------------------------------------------------------------------------
  190.        <DebuggerStepThrough>
  191.        <Extension>
  192.        <EditorBrowsable(EditorBrowsableState.Always)>
  193.        Public Function IsEmpty(sender As Global.System.IO.DirectoryInfo) As Boolean
  194.  
  195.            Return Not sender.EnumerateFileSystemInfos().Any()
  196.  
  197.        End Function
  198.  
  199. #End Region
  200.  
  201.    End Module
  202.  
  203. End Namespace
  204.  
  205. #End Region
  206.  



KernelBase.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 01-July-2019
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. Imports System.Runtime.InteropServices
  17. Imports System.Security
  18.  
  19. #End Region
  20.  
  21. #Region " P/Invoking "
  22.  
  23. ' ReSharper disable once CheckNamespace
  24.  
  25. Namespace DevCase.Win32.NativeMethods
  26.  
  27.    ''' ----------------------------------------------------------------------------------------------------
  28.    ''' <summary>
  29.    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
  30.    ''' <para></para>
  31.    ''' KernelBase.dll.
  32.    ''' </summary>
  33.    ''' ----------------------------------------------------------------------------------------------------
  34.    <HideModuleName>
  35.    <SuppressUnmanagedCodeSecurity>
  36.    <CodeAnalysis.SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification:="Required to migrate this code to .NET Core")>
  37.    <CodeAnalysis.SuppressMessage("Interoperability", "CA1401:P/Invokes should not be visible", Justification:="")>
  38.    Public Module KernelBase
  39.  
  40. #Region " KernelBase.dll "
  41.  
  42.        ''' ----------------------------------------------------------------------------------------------------
  43.        ''' <summary>
  44.        ''' Determines whether a path string refers to the root of a volume.
  45.        ''' <para></para>
  46.        ''' This function differs from <see cref="NativeMethods.PathIsRoot"/> in that it accepts paths with "\", "\?" and "\?\UNC" prefixes.
  47.        ''' </summary>
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        ''' <remarks>
  50.        ''' <see href="https://docs.microsoft.com/en-us/windows/desktop/api/pathcch/nf-pathcch-pathcchisroot"/>
  51.        ''' </remarks>
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        ''' <param name="path">
  54.        ''' A pointer to the path string.
  55.        ''' </param>
  56.        ''' ----------------------------------------------------------------------------------------------------
  57.        ''' <returns>
  58.        ''' Returns <see langword="True"/> if the specified path is a root, or <see langword="False"/> otherwise.
  59.        ''' </returns>
  60.        ''' ----------------------------------------------------------------------------------------------------
  61.        <DllImport("KernelBase.dll", SetLastError:=True, CharSet:=CharSet.Auto, BestFitMapping:=False, ThrowOnUnmappableChar:=True)>
  62.        Public Function PathCchIsRoot(path As String
  63.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  64.        End Function
  65.  
  66. #End Region
  67.  
  68.    End Module
  69.  
  70. End Namespace
  71.  
  72. #End Region
  73.  



FileInfoExtensions.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 10-September-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' FileInfo.ForceDelete()
  9. ' FileInfo.ForceRecycle(UIOption)
  10.  
  11. #End Region
  12.  
  13. #Region " Option Statements "
  14.  
  15. Option Strict On
  16. Option Explicit On
  17. Option Infer Off
  18.  
  19. #End Region
  20.  
  21. #Region " Imports "
  22.  
  23. Imports System.ComponentModel
  24. Imports System.IO
  25. Imports System.Runtime.CompilerServices
  26. Imports System.Security
  27.  
  28. #End Region
  29.  
  30. #Region " FileInfo Extensions "
  31.  
  32. ' ReSharper disable once CheckNamespace
  33.  
  34. Namespace DevCase.Extensions.FileInfoExtensions
  35.  
  36.    ''' ----------------------------------------------------------------------------------------------------
  37.    ''' <summary>
  38.    ''' Contains custom extension methods to use with <see cref="Global.System.IO.FileInfo"/> type.
  39.    ''' </summary>
  40.    ''' ----------------------------------------------------------------------------------------------------
  41.    <HideModuleName>
  42.    Public Module FileInfoExtensions
  43.  
  44. #Region " Public Extension Methods "
  45.  
  46.        ''' ----------------------------------------------------------------------------------------------------
  47.        ''' <summary>
  48.        ''' Sends the source file to the Recycle Bin.
  49.        ''' </summary>
  50.        ''' ----------------------------------------------------------------------------------------------------
  51.        ''' <example> This is a code example.
  52.        ''' <code language="VB.NET">
  53.        ''' Dim file As New FileInfo("C:\File.ext")
  54.        ''' file.Recycle(UIOption.OnlyErrorDialogs)
  55.        ''' </code>
  56.        ''' </example>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <param name="sender">
  59.        ''' The source <see cref="Global.System.IO.FileInfo"/>.
  60.        ''' </param>
  61.        '''
  62.        ''' <param name="dialog">
  63.        ''' Specifies which dialog boxes to show when recycling.
  64.        ''' </param>
  65.        ''' ----------------------------------------------------------------------------------------------------
  66.        <DebuggerStepThrough>
  67.        <Extension>
  68.        <EditorBrowsable(EditorBrowsableState.Always)>
  69.        <SecuritySafeCritical>
  70.        Public Sub Recycle(sender As Global.System.IO.FileInfo, dialog As FileIO.UIOption)
  71.  
  72.            Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(sender.FullName, dialog, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
  73.  
  74.        End Sub
  75.  
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <summary>
  78.        ''' Forces the permanent deletion of the specified file by removing the read-only attribute and deleting it.
  79.        ''' </summary>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <param name="file">
  82.        ''' The file to be permanently deleted.
  83.        ''' </param>
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        <DebuggerStepThrough>
  86.        <Extension>
  87.        <EditorBrowsable(EditorBrowsableState.Always)>
  88.        <SecuritySafeCritical>
  89.        Public Sub ForceDelete(file As FileInfo)
  90.  
  91.            If file.IsReadOnly Then
  92.                file.Attributes = file.Attributes And Not FileAttributes.ReadOnly
  93.            End If
  94.  
  95.            file.Delete()
  96.  
  97.        End Sub
  98.  
  99.        ''' ----------------------------------------------------------------------------------------------------
  100.        ''' <summary>
  101.        ''' Forces the recycling of the specified file by removing the read-only attribute and sending it to the recycle bin.
  102.        ''' </summary>
  103.        ''' ----------------------------------------------------------------------------------------------------
  104.        ''' <param name="file">
  105.        ''' The file to be permanently deleted.
  106.        ''' </param>
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        <DebuggerStepThrough>
  109.        <Extension>
  110.        <EditorBrowsable(EditorBrowsableState.Always)>
  111.        <SecuritySafeCritical>
  112.        Public Sub ForceRecycle(file As FileInfo, dialog As FileIO.UIOption)
  113.  
  114.            If file.IsReadOnly Then
  115.                file.Attributes = file.Attributes And Not FileAttributes.ReadOnly
  116.            End If
  117.  
  118.            file.Recycle(dialog)
  119.  
  120.        End Sub
  121.  
  122. #End Region
  123.  
  124.    End Module
  125.  
  126. End Namespace
  127.  
  128. #End Region
  129.  
En línea

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

Ir a:  

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