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

 

 


Tema destacado: Estamos en la red social de Mastodon


  Mostrar Mensajes
Páginas: [1] 2 3 4 5 6 7 8 9 10 11 12 13 14
1  Foros Generales / Foro Libre / Re: Las personas nos amamos y respetamos? en: 10 Septiembre 2023, 13:47 pm
Citar
Las personas nos amamos y respetamos?

Una sociedad que inculca el poliamor, y el vivir soltera sintiéndote muy feminista sin un hombre en tu vida, sin hijos pero con tus diez gatos, y donde se permite el matrimonio entre un humano y un animal y un robot, etc, eso no es una sociedad hecha para fomentar sentimientos como el amor.

Tan solo tienes que darte cuenta en que ha convertido el estado francés a París - "la ciudad del amor" - desde hace aproximadamente 15 años, con hileras kilométricas de tiendas de campaña en las calles de las principales zonas más turísticas, filas y filas habitadas por una sola clase de personas, donde se palpa en el ambiente el hambre y la miseria causada por el globalismo.

O los barrios de EEUU donde la droga conocida como Fentanilo es la razón por la cual las personas viven su día a día, por y para esa droga, barrios enteros llenos de "zombies" adictos a su consumo, mires a donde mires se siente algo parecido a la asfixia, por que lo que se respira ahí no es aire, y se siente lástima, mucha lástima, y también miedo de que te roben o algo peor, solo de pensar en caminar por esas calles... ¿cuanto amor ves ahí?, solo hay hambre, miseria y desesperación una vez más. Y esta droga ha llegado a España, en Madrid, ojito de aquí a unos años...

Y Cuba, Argentina, Venezuela... España va por el mismo camino que todos ellos.



Lo que vemos en la actualidad en occidente son los resquicios de una sociedad de generaciones pasadas, una sociedad compuesta por una mayoría de personas adultas que siguen conservando valores tradicionales, que son capaces de amar, pero amar de verdad sintiendo un cosquilleo profundo en el estómago por primera vez, y eso es algo que poco a poco se irá extinguiendo debido a las agendas globales de conducta y de pensamiento que se aplican a las nuevas generaciones.

Y el respeto hacia los demás se ha cambiado por la dictadura silenciosa de la censura.

Saludos.
2  Foros Generales / Noticias / Re: Elon Musk ordenó cortar internet a Ucrania en plena ofensiva contra la flota rusa en: 10 Septiembre 2023, 13:34 pm
Típico caso de ofrecerle la mano a alguien, para que te acaben agarrando del brazo y no te quieran soltar.

Elon Musk no es alguien de mi confianza (ser rico no implica ser buena persona, y la élite mundial de multimillonarios no son conocidos precisamente por sus bondades sino más bien por sus atrocidades carentes de escrúpulos), pero su posicionamiento neutral es claro y admirable, le ofenda a quien le ofenda en las redes sociales. Elon Musk no tiene por que hacer lo que hace, y aun así lo ha hecho por que al parecer es buena gente.

Pero Elon Musk sigue siendo un especulador de manual en cuestiones como las inversiones y criptomonedas, digno discipulo de George Soros en sus buenos tiempos quebrando el banco de Inglaterra.

Un saludo.
3  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 11:30 am
Se me ocurrió desarrollar este curioso y simple método con el que utilizar el sintetizador de voz del sistema operativo para pronunciar cualquier objeto.

Nota: se requiere añadir una referencia al ensamblado System.Speech

Ejemplos de uso:
Código
  1. Dim obj As Color = Color.LightGoldenrodYellow
  2. obj.Speak("Microsoft Zira Desktop", rate:=-2, volume:=100)

Código
  1. Dim obj As String = "Hola Mundo!"
  2. obj.Speak("Microsoft Helena Desktop", rate:=-2, volume:=100)

Si intentamos leer un array no va a leer los elementos, para ello podemos iterar los elementos uno a uno para pronunciarlos, o podriamos concatenarlos en un string:

Código
  1. Dim array As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  2. Dim humanReadable As String = String.Join(" ", array)
  3. humanReadable.Speak("Microsoft Helena Desktop", rate:=-1, volume:=100)

Lo ideal es que el objeto en cuestión implemente la función ToString para convertirlo a una cadena de texto legible por humanos. Aquí un ejemplo:

Código
  1. Public Class MyType
  2.  
  3.    Public Property Property1 As String
  4.    Public Property Property2 As String
  5.  
  6.    Public Overrides Function ToString() As String
  7.        Return $"{Me.Property1}, {Me.Property2}"
  8.    End Function
  9.  
  10. End Class
  11.  

Código
  1. Dim obj As New MyType()
  2. obj.Property1 = "Valor de la propiedad 1"
  3. obj.Property2 = "Valor de la propiedad 2"
  4.  
  5. obj.Speak("Microsoft Helena Desktop", rate:=-1, volume:=100)



Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 09-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' Object.Speak(Opt: String, Opt: Integer, Opt: Integer)
  9. ' Object.Speak(Opt: InstalledVoice, Opt: Integer, Opt: Integer)
  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.Globalization
  25. Imports System.Runtime.CompilerServices
  26. Imports System.Speech.Synthesis
  27.  
  28. #End Region
  29.  
  30. #Region " Object Extensions "
  31.  
  32. ' ReSharper disable once CheckNamespace
  33.  
  34. Namespace DevCase.Extensions.ObjectExtensions
  35.  
  36.    ''' ----------------------------------------------------------------------------------------------------
  37.    ''' <summary>
  38.    ''' Contains custom extension methods to use with the <see cref="Object"/> type.
  39.    ''' </summary>
  40.    ''' ----------------------------------------------------------------------------------------------------
  41.    <ImmutableObject(True)>
  42.    <HideModuleName>
  43.    Public Module ObjectExtensions
  44.  
  45. #Region " Public Extension Methods "
  46.  
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        ''' <summary>
  49.        ''' Speaks the string representation of the source object by using the
  50.        ''' operating system integrated text-to-speech synthesizer.
  51.        ''' </summary>
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        ''' <example> This is a code example.
  54.        ''' <code language="VB.NET">
  55.        ''' Dim c As Color = Color.LightGoldenrodYellow
  56.        ''' c.Speak(name:="Microsoft Zira Desktop", rate:=1, volume:=100)
  57.        ''' </code>
  58.        ''' </example>
  59.        ''' ----------------------------------------------------------------------------------------------------
  60.        ''' <param name="obj">
  61.        ''' The object to be spoken.
  62.        ''' </param>
  63.        '''
  64.        ''' <param name="voiceName">
  65.        ''' Optional. Selects the voice to use, such as "Microsoft Zira Desktop" or "Microsoft Helena Desktop".
  66.        ''' <para></para>
  67.        ''' Note: If this value is null, the default voice is the one for the current culture
  68.        ''' specified in the <see cref="CultureInfo.CurrentCulture"/> property.
  69.        ''' </param>
  70.        '''
  71.        ''' <param name="rate">
  72.        ''' Optional. Sets the speaking rate of the selected voice.
  73.        ''' <para></para>
  74.        ''' Allowed values are in the range of -10 (slowest) to +10 (fastest).
  75.        ''' <para></para>
  76.        ''' Default value: 0 (normal rate).
  77.        ''' </param>
  78.        '''
  79.        ''' <param name="volume">
  80.        ''' Optional. Sets the output volume of the synthesizer.
  81.        ''' <para></para>
  82.        ''' Allowed values are in the range of 0 (minimum) to 100 (maximum).
  83.        ''' <para></para>
  84.        ''' Default value: 100 (maximum volume)
  85.        ''' </param>
  86.        ''' ----------------------------------------------------------------------------------------------------
  87.        <DebuggerStepThrough>
  88.        <Extension>
  89.        <EditorBrowsable(EditorBrowsableState.Always)>
  90.        Public Sub Speak(obj As Object, Optional voiceName As String = "",
  91.                                        Optional rate As Integer = 0,
  92.                                        Optional volume As Integer = 100)
  93.  
  94.            Using synth As New SpeechSynthesizer()
  95.                If Not String.IsNullOrEmpty(voiceName) Then
  96.                    synth.SelectVoice(voiceName)
  97.                Else
  98.                    Dim voice As InstalledVoice = synth.GetInstalledVoices(CultureInfo.CurrentCulture).FirstOrDefault()
  99.                    If voice IsNot Nothing Then
  100.                        synth.SelectVoice(voice.VoiceInfo.Name)
  101.                    End If
  102.                End If
  103.  
  104.                synth.Rate = rate
  105.                synth.Volume = volume
  106.                synth.Speak(obj.ToString())
  107.            End Using
  108.  
  109.        End Sub
  110.  
  111.        ''' ----------------------------------------------------------------------------------------------------
  112.        ''' <summary>
  113.        ''' Speaks the string representation of the source object by using the
  114.        ''' operating system integrated text-to-speech synthesizer.
  115.        ''' </summary>
  116.        ''' ----------------------------------------------------------------------------------------------------
  117.        ''' <example> This is a code example.
  118.        ''' <code language="VB.NET">
  119.        ''' Dim c As Color = Color.LightGoldenrodYellow
  120.        ''' Dim voice As InstalledVoice = New SpeechSynthesizer().GetInstalledVoices(CultureInfo.CurrentCulture).FirstOrDefault()
  121.        ''' c.Speak(voice:=voice, rate:=1, volume:=100)
  122.        ''' </code>
  123.        ''' </example>
  124.        ''' ----------------------------------------------------------------------------------------------------
  125.        ''' <param name="obj">
  126.        ''' The object to be spoken.
  127.        ''' </param>
  128.        '''
  129.        ''' <param name="voice">
  130.        ''' Optional. Selects the voice to use, such as "Microsoft Zira Desktop" or "Microsoft Helena Desktop".
  131.        ''' <para></para>
  132.        ''' Note: If this value is null, the default voice is the one for the current culture
  133.        ''' specified in the <see cref="CultureInfo.CurrentCulture"/> property.
  134.        ''' </param>
  135.        '''
  136.        ''' <param name="rate">
  137.        ''' Optional. Sets the speaking rate of the selected voice.
  138.        ''' <para></para>
  139.        ''' Allowed values are in the range of -10 (slowest) to +10 (fastest).
  140.        ''' <para></para>
  141.        ''' Default value: 0 (normal rate).
  142.        ''' </param>
  143.        '''
  144.        ''' <param name="volume">
  145.        ''' Optional. Sets the output volume of the synthesizer.
  146.        ''' <para></para>
  147.        ''' Allowed values are in the range of 0 (minimum) to 100 (maximum).
  148.        ''' <para></para>
  149.        ''' Default value: 100 (maximum volume)
  150.        ''' </param>
  151.        ''' ----------------------------------------------------------------------------------------------------
  152.        <DebuggerStepThrough>
  153.        <Extension>
  154.        <EditorBrowsable(EditorBrowsableState.Always)>
  155.        Public Sub Speak(obj As Object, Optional voice As InstalledVoice = Nothing,
  156.                                        Optional rate As Integer = 0,
  157.                                        Optional volume As Integer = 100)
  158.  
  159.            If voice Is Nothing Then
  160.                Throw New ArgumentNullException(paramName:=NameOf(voice))
  161.            End If
  162.  
  163.            Speak(obj, voice.VoiceInfo.Name, rate, volume)
  164.  
  165.        End Sub
  166.  
  167. #End Region
  168.  
  169.    End Module
  170.  
  171. End Namespace
  172.  
  173. #End Region
  174.  



De paso les dejo este método
4  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 11:05 am
Dos funciones para truncar un string, al final del string o en medio.

Ejemplo:



Nota: para evitar mal entendidos, en este ejemplo visual se ha utilizado el caracter "…" como caracter separador de cadena truncada, que no son tres caracteres de puntos sino un solo caracter ("…".Length = 1).



Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 13-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' String.Truncate(Integer, Opt: String) As String
  9. ' String.TruncateMiddle(Integer, Opt: String) As String
  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 " String Extensions "
  29.  
  30. ' ReSharper disable once CheckNamespace
  31.  
  32. Namespace DevCase.Extensions.StringExtensions
  33.  
  34.    ''' ----------------------------------------------------------------------------------------------------
  35.    ''' <summary>
  36.    ''' Contains custom extension methods to use with a <see cref="String"/> type.
  37.    ''' </summary>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    <HideModuleName>
  40.    Public Module StringExtensions
  41.  
  42.        ''' ----------------------------------------------------------------------------------------------------
  43.        ''' <summary>
  44.        ''' Truncates the source string to a specified length
  45.        ''' and replaces the truncated part with an ellipsis.
  46.        ''' </summary>
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        ''' <example> This is a code example.
  49.        ''' <code language="VB.NET">
  50.        ''' Dim text As String = "123456789"
  51.        ''' Dim truncated As String = Truncate(text, 5)
  52.        ''' Console.WriteLine(truncated)
  53.        ''' </code>
  54.        ''' </example>
  55.        ''' ----------------------------------------------------------------------------------------------------
  56.        ''' <param name="text">
  57.        ''' The string that will be truncated.
  58.        ''' </param>
  59.        '''
  60.        ''' <param name="maxLength">
  61.        ''' The maximum length of characters to maintain before truncation occurs.
  62.        ''' </param>
  63.        '''
  64.        ''' <param name="elipsis">
  65.        ''' Optional. The ellipsis string to use as the replacement.
  66.        ''' <para></para>
  67.        ''' Default value is: "…" (U+2026)
  68.        ''' </param>
  69.        ''' ----------------------------------------------------------------------------------------------------
  70.        ''' <returns>
  71.        ''' The truncated string with the ellipsis in the end.
  72.        ''' </returns>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        <DebuggerStepThrough>
  75.        <Extension>
  76.        <EditorBrowsable(EditorBrowsableState.Always)>
  77.        Public Function Truncate(text As String, maxLength As Integer, Optional elipsis As String = "…") As String
  78.            If maxLength < 1 Then
  79.                Throw New ArgumentException("Value can't be less than 1.", paramName:=NameOf(maxLength))
  80.            End If
  81.  
  82.            If String.IsNullOrEmpty(text) Then
  83.                Throw New ArgumentNullException(paramName:=NameOf(text))
  84.            End If
  85.  
  86. #If NETCOREAPP Then
  87.            Return If(text.Length <= maxLength, text, String.Concat(text.AsSpan(0, maxLength), elipsis))
  88. #Else
  89.            Return If(text.Length <= maxLength, text, text.Substring(0, maxLength) & elipsis)
  90. #End If
  91.  
  92.        End Function
  93.  
  94.        ''' ----------------------------------------------------------------------------------------------------
  95.        ''' <summary>
  96.        ''' Truncates the source string to a specified length by stripping out the center
  97.        ''' and replacing it with an ellipsis, so that the beginning and end of the string are retained.
  98.        ''' </summary>
  99.        ''' ----------------------------------------------------------------------------------------------------
  100.        ''' <example> This is a code example.
  101.        ''' <code language="VB.NET">
  102.        ''' Dim text As String = "123456789"
  103.        ''' Dim truncated As String = TruncateMiddle(text, 6)
  104.        ''' Console.WriteLine(truncated)
  105.        ''' </code>
  106.        ''' </example>
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        ''' <param name="text">
  109.        ''' The string that will be truncated.
  110.        ''' </param>
  111.        '''
  112.        ''' <param name="maxLength">
  113.        ''' The maximum length of characters to maintain before truncation occurs.
  114.        ''' </param>
  115.        '''
  116.        ''' <param name="elipsis">
  117.        ''' Optional. The ellipsis string to use as the replacement.
  118.        ''' <para></para>
  119.        ''' Default value is: "…" (U+2026)
  120.        ''' </param>
  121.        ''' ----------------------------------------------------------------------------------------------------
  122.        ''' <returns>
  123.        ''' The truncated string with the ellipsis in the middle.
  124.        ''' </returns>
  125.        ''' ----------------------------------------------------------------------------------------------------
  126.        <DebuggerStepThrough>
  127.        <Extension>
  128.        <EditorBrowsable(EditorBrowsableState.Always)>
  129.        Public Function TruncateMiddle(text As String, maxLength As Integer, Optional elipsis As String = "…") As String
  130.            If maxLength < 1 Then
  131.                Throw New ArgumentException("Value can't be less than 1.", paramName:=NameOf(maxLength))
  132.            End If
  133.  
  134.            If String.IsNullOrEmpty(text) Then
  135.                Throw New ArgumentNullException(paramName:=NameOf(text))
  136.            End If
  137.  
  138.            Dim charsInEachHalf As Integer = maxLength \ 2
  139.            Dim right As String = text.Substring(text.Length - charsInEachHalf, charsInEachHalf)
  140.            Dim left As String = text.Substring(0, maxLength - right.Length)
  141.  
  142.            Return $"{left}{elipsis}{right}"
  143.        End Function
  144.  
  145.    End Module
  146.  
  147. End Namespace
  148.  
  149. #End Region
5  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 10:50 am
Implementación de una colección genérica SortableObservableCollection<T>, que hereda de ObservableCollection<T>.

Esta colección tiene la capacidad de ordenar de forma automática los elementos de la colección - en ascendente o descendente - mediante el método de ordenación especificado en la propiedad SortableObservableCollection.SortingSelector.

Nota: código original en C# https://stackoverflow.com/a/44401860/1248295



Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 08-June-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " imports "
  15.  
  16. Imports System.Collections.Generic
  17. Imports System.Collections.ObjectModel
  18. Imports System.Collections.Specialized
  19. Imports System.ComponentModel
  20. Imports System.Linq
  21.  
  22. #End Region
  23.  
  24. Namespace DevCase.Runtime.Collections
  25.  
  26.    ''' ----------------------------------------------------------------------------------------------------
  27.    ''' <summary>
  28.    ''' Represents a sortable, dynamic data collection that provides notifications when items get added,
  29.    ''' removed, or when the whole list is refreshed.
  30.    ''' <para></para>
  31.    ''' The items in the collection are automatically sorted by the selector method specified in
  32.    ''' <see cref="SortableObservableCollection(Of T).SortingSelector"/> property.
  33.    ''' </summary>
  34.    ''' ----------------------------------------------------------------------------------------------------
  35.    ''' <example> This is a code example.
  36.    ''' <code language="VB">
  37.    ''' Dim collection As New SortableObservableCollection(Of KeyValuePair(Of Integer, String)) With {
  38.    '''     .SortingSelector = Function(pair As KeyValuePair(Of Integer, String)) pair.Key,
  39.    '''     .IsDescending = True
  40.    ''' }
  41.    '''
  42.    ''' collection.Add(New KeyValuePair(Of Integer, String)(7, "abc"))
  43.    ''' collection.Add(New KeyValuePair(Of Integer, String)(3, "xey"))
  44.    ''' collection.Add(New KeyValuePair(Of Integer, String)(6, "ftu"))
  45.    '''
  46.    ''' For Each pair As KeyValuePair(Of Integer, String) In collection
  47.    '''     Console.WriteLine(pair)
  48.    ''' Next pair
  49.    ''' </code>
  50.    ''' </example>
  51.    ''' ----------------------------------------------------------------------------------------------------
  52.    ''' <typeparam name="T">
  53.    ''' </typeparam>
  54.    ''' ----------------------------------------------------------------------------------------------------
  55.    ''' <seealso cref="ObservableCollection(Of T)"/>
  56.    ''' ----------------------------------------------------------------------------------------------------
  57.    Public Class SortableObservableCollection(Of T) : Inherits ObservableCollection(Of T)
  58.  
  59. #Region " Private Fields "
  60.  
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        ''' <summary>
  63.        ''' The selector method to sort the items in the collection.
  64.        ''' </summary>
  65.        ''' ----------------------------------------------------------------------------------------------------
  66.        Private _sortingSelector As Func(Of T, Object)
  67.  
  68.        ''' ----------------------------------------------------------------------------------------------------
  69.        ''' <summary>
  70.        ''' A value that determine whether the sorting method is ascending or descending.
  71.        ''' </summary>
  72.        ''' ----------------------------------------------------------------------------------------------------
  73.        Private _isDescending As Boolean
  74.  
  75. #End Region
  76.  
  77. #Region " Properties "
  78.  
  79.        ''' ----------------------------------------------------------------------------------------------------
  80.        ''' <summary>
  81.        ''' Gets or sets the selector method to sort the items in the collection.
  82.        ''' </summary>
  83.        ''' ----------------------------------------------------------------------------------------------------
  84.        Public Overridable Property SortingSelector() As Func(Of T, Object)
  85.            Get
  86.                Return Me._sortingSelector
  87.            End Get
  88.            Set(value As Func(Of T, Object))
  89.                If Me._sortingSelector = value Then
  90.                    Return
  91.                End If
  92.  
  93.                Me._sortingSelector = value
  94.                Me.OnPropertyChanged(New PropertyChangedEventArgs(NameOf(SortingSelector)))
  95.                Me.OnPropertyChanged(New PropertyChangedEventArgs("Items[]"))
  96.                Me.OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))
  97.            End Set
  98.        End Property
  99.  
  100.        ''' ----------------------------------------------------------------------------------------------------
  101.        ''' <summary>
  102.        ''' Gets or sets a value indicating whether the sorting method is ascending or descending.
  103.        ''' </summary>
  104.        ''' ----------------------------------------------------------------------------------------------------
  105.        Public Overridable Property IsDescending() As Boolean
  106.            Get
  107.                Return Me._isDescending
  108.            End Get
  109.            Set(value As Boolean)
  110.                If Me._isDescending = value Then
  111.                    Return
  112.                End If
  113.  
  114.                Me._isDescending = value
  115.                Me.OnPropertyChanged(New PropertyChangedEventArgs(NameOf(SortableObservableCollection(Of T).IsDescending)))
  116.                Me.OnPropertyChanged(New PropertyChangedEventArgs("Items[]"))
  117.                Me.OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))
  118.            End Set
  119.        End Property
  120.  
  121. #End Region
  122.  
  123. #Region " Event Raisers "
  124.  
  125.        ''' ----------------------------------------------------------------------------------------------------
  126.        ''' <summary>
  127.        ''' Raises the <see cref="SortableObservableCollection(Of T).CollectionChanged" /> event
  128.        ''' with the provided arguments.
  129.        ''' </summary>
  130.        ''' ----------------------------------------------------------------------------------------------------
  131.        ''' <param name="e">
  132.        ''' The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.
  133.        ''' </param>
  134.        ''' ----------------------------------------------------------------------------------------------------
  135.        Protected Overrides Sub OnCollectionChanged(ByVal e As NotifyCollectionChangedEventArgs)
  136.            MyBase.OnCollectionChanged(e)
  137.            If (Me.SortingSelector Is Nothing) OrElse
  138.                (e.Action = NotifyCollectionChangedAction.Remove) OrElse
  139.                (e.Action = NotifyCollectionChangedAction.Reset) Then
  140.                Return
  141.            End If
  142.  
  143.            Dim query As IEnumerable(Of (Item As T, index As Integer)) = Me.Select(Function(item, index) (item, index))
  144.            query = If(Me.IsDescending, query.OrderByDescending(Function(tuple) Me.SortingSelector()(tuple.Item)), query.OrderBy(Function(tuple) Me.SortingSelector()(tuple.Item)))
  145.            Dim map As IEnumerable(Of (OldIndex As Integer, NewIndex As Integer)) = query.Select(Function(tuple, index) (OldIndex:=tuple.index, NewIndex:=index)).Where(Function(o) o.OldIndex <> o.NewIndex)
  146.            Using enumerator As IEnumerator(Of (OldIndex As Integer, NewIndex As Integer)) = map.GetEnumerator()
  147.                If enumerator.MoveNext() Then
  148.                    Me.Move(enumerator.Current.OldIndex, enumerator.Current.NewIndex)
  149.                End If
  150.            End Using
  151.        End Sub
  152.  
  153. #End Region
  154.  
  155.    End Class
  156.  
  157. End Namespace
  158.  
6  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 10 Septiembre 2023, 10:35 am
Esta es mi implementación de una colección por nombre NameObjectCollection que hereda del tipo NameObjectCollectionBase.

El uso es idéntico a una colección de tipo NameValueCollection (key:String, value:String) pero con la diferencia de que el valor es de tipo Object (key:String, value:Object).

Casos de uso: convertir un JSON donde el valor no es del tipo String.

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 08-July-2023
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. Imports System.Collections.Specialized
  17. Imports System.Runtime.Serialization
  18.  
  19. #End Region
  20.  
  21. Namespace DevCase.Runtime.Collections
  22.  
  23.    ''' ----------------------------------------------------------------------------------------------------
  24.    ''' <summary>
  25.    ''' Similarly to a <see cref="NameValueCollection"/>, this class represents a
  26.    ''' collection of associated <see cref="String"/> keys and <see cref="Object"/> values
  27.    ''' that can be accessed either with the name or with the index.
  28.    ''' </summary>
  29.    ''' ----------------------------------------------------------------------------------------------------
  30.    <Serializable>
  31.    Public Class NameObjectCollection : Inherits NameObjectCollectionBase
  32.  
  33. #Region " Private MethFieldsods "
  34.  
  35.        ''' ----------------------------------------------------------------------------------------------------
  36.        ''' <summary>
  37.        ''' Cached array of values in this <see cref="NameObjectCollection"/>.
  38.        ''' </summary>
  39.        ''' ----------------------------------------------------------------------------------------------------
  40.        Private _all() As Object
  41.  
  42.        ''' ----------------------------------------------------------------------------------------------------
  43.        ''' <summary>
  44.        ''' Cached array of keys in this <see cref="NameObjectCollection"/>.
  45.        ''' </summary>
  46.        ''' ----------------------------------------------------------------------------------------------------
  47.        Private _allKeys() As String
  48.  
  49. #End Region
  50.  
  51. #Region " Properties "
  52.  
  53.        ''' ----------------------------------------------------------------------------------------------------
  54.        ''' <summary>
  55.        ''' Gets or sets the entry with the specified key in this <see cref="NameObjectCollection"/>.
  56.        ''' </summary>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <param name="name">
  59.        ''' The <see cref="String"/> key of the entry to locate. The key can be null.
  60.        ''' </param>
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        ''' <returns>
  63.        ''' A <see cref="Object"/> that contains the comma-separated list of values associated with
  64.        ''' the specified key, if found; otherwise, null.
  65.        ''' </returns>
  66.        ''' ----------------------------------------------------------------------------------------------------
  67.        Default Public Property Item(name As String) As Object
  68.            Get
  69.                Return Me.[Get](name)
  70.            End Get
  71.            Set(value As Object)
  72.                Me.[Set](name, value)
  73.            End Set
  74.        End Property
  75.  
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <summary>
  78.        ''' Gets the entry at the specified index of this <see cref="NameObjectCollection"/>.
  79.        ''' </summary>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <param name="index">
  82.        ''' The zero-based index of the entry to locate in the collection.
  83.        ''' </param>
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        ''' <returns>
  86.        ''' A <see cref="Object"/> that contains the comma-separated list of values at the specified
  87.        ''' index of the collection.
  88.        ''' </returns>
  89.        ''' ----------------------------------------------------------------------------------------------------
  90.        Default Public ReadOnly Property Item(index As Integer) As Object
  91.            Get
  92.                Return Me.[Get](index)
  93.            End Get
  94.        End Property
  95.  
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        ''' <summary>
  98.        ''' Gets all the keys in this <see cref="NameObjectCollection"/>.
  99.        ''' </summary>
  100.        ''' ----------------------------------------------------------------------------------------------------
  101.        ''' <returns>
  102.        ''' A <see cref="String"/> array that contains all the keys of this <see cref="NameObjectCollection"/>.
  103.        ''' </returns>
  104.        ''' ----------------------------------------------------------------------------------------------------
  105.        Public Overridable ReadOnly Property AllKeys() As String()
  106.            Get
  107.                If Me._allKeys Is Nothing Then
  108.                    Me._allKeys = Me.BaseGetAllKeys()
  109.                End If
  110.  
  111.                Return Me._allKeys
  112.            End Get
  113.        End Property
  114.  
  115. #End Region
  116.  
  117. #Region " Constructors "
  118.  
  119.        ''' ----------------------------------------------------------------------------------------------------
  120.        ''' <summary>
  121.        ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
  122.        ''' class that is empty, has the default initial capacity and uses the default case-insensitive
  123.        ''' hash code provider and the default case-insensitive comparer.
  124.        ''' </summary>
  125.        ''' ----------------------------------------------------------------------------------------------------
  126.        Public Sub New()
  127.        End Sub
  128.  
  129.        ''' ----------------------------------------------------------------------------------------------------
  130.        ''' <summary>
  131.        ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
  132.        ''' class that is empty, has the specified initial capacity and uses the specified
  133.        ''' hash code provider and the specified comparer.
  134.        ''' </summary>
  135.        ''' ----------------------------------------------------------------------------------------------------
  136.        ''' <param name="hashProvider">
  137.        ''' The <see cref="System.Collections.IHashCodeProvider"/> that will supply the hash codes for
  138.        ''' all keys in this <see cref="NameObjectCollection"/>.
  139.        ''' </param>
  140.        ''' ----------------------------------------------------------------------------------------------------
  141.        ''' <param name="comparer">
  142.        ''' The <see cref="System.Collections.IComparer"/> to use to determine whether two keys are equal.
  143.        ''' </param>
  144.        ''' ----------------------------------------------------------------------------------------------------
  145.        <Obsolete("Please use NameObjectCollection(IEqualityComparer) instead.")>
  146.        Public Sub New(hashProvider As IHashCodeProvider, comparer As IComparer)
  147.            MyBase.New(hashProvider, comparer)
  148.        End Sub
  149.  
  150.        ''' ----------------------------------------------------------------------------------------------------
  151.        ''' <summary>
  152.        ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
  153.        ''' class that is empty, has the specified initial capacity and uses the default
  154.        ''' case-insensitive hash code provider and the default case-insensitive comparer.
  155.        ''' </summary>
  156.        ''' ----------------------------------------------------------------------------------------------------
  157.        ''' <param name="capacity">
  158.        ''' The initial number of entries that this <see cref="NameObjectCollection"/>
  159.        ''' can contain.
  160.        ''' </param>
  161.        ''' ----------------------------------------------------------------------------------------------------
  162.        Public Sub New(capacity As Integer)
  163.            MyBase.New(capacity)
  164.        End Sub
  165.  
  166.        ''' ----------------------------------------------------------------------------------------------------
  167.        ''' <summary>
  168.        ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
  169.        ''' class that is empty, has the default initial capacity, and uses the specified
  170.        ''' <see cref="System.Collections.IEqualityComparer"/> object.
  171.        ''' </summary>
  172.        ''' ----------------------------------------------------------------------------------------------------
  173.        ''' <param name="equalityComparer">
  174.        ''' The <see cref="System.Collections.IEqualityComparer"/> object to use to determine whether two
  175.        ''' keys are equal and to generate hash codes for the keys in the collection.
  176.        ''' </param>
  177.        ''' ----------------------------------------------------------------------------------------------------
  178.        Public Sub New(equalityComparer As IEqualityComparer)
  179.            MyBase.New(equalityComparer)
  180.        End Sub
  181.  
  182.        ''' ----------------------------------------------------------------------------------------------------
  183.        ''' <summary>
  184.        ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
  185.        ''' class that is empty, has the specified initial capacity, and uses the specified
  186.        ''' <see cref="System.Collections.IEqualityComparer"/> object.
  187.        ''' </summary>
  188.        ''' ----------------------------------------------------------------------------------------------------
  189.        ''' <param name="capacity">
  190.        ''' The initial number of entries that this <see cref="NameObjectCollection"/>
  191.        ''' object can contain.
  192.        ''' </param>
  193.        '''
  194.        ''' <param name="equalityComparer">
  195.        ''' The <see cref="System.Collections.IEqualityComparer"/> object to use to determine whether two
  196.        ''' keys are equal and to generate hash codes for the keys in the collection.
  197.        ''' </param>
  198.        ''' ----------------------------------------------------------------------------------------------------
  199.        Public Sub New(capacity As Integer, equalityComparer As IEqualityComparer)
  200.            MyBase.New(capacity, equalityComparer)
  201.        End Sub
  202.  
  203.        ''' ----------------------------------------------------------------------------------------------------
  204.        ''' <summary>
  205.        ''' Copies the entries from the specified <see cref="NameObjectCollection"/>
  206.        ''' to a new <see cref="NameObjectCollection"/> with the specified
  207.        ''' initial capacity or the same initial capacity as the number of entries copied,
  208.        ''' whichever is greater, and using the default case-insensitive hash code provider
  209.        ''' and the default case-insensitive comparer.
  210.        ''' </summary>
  211.        ''' ----------------------------------------------------------------------------------------------------
  212.        ''' <param name="capacity">
  213.        ''' The initial number of entries that this <see cref="NameObjectCollection"/>
  214.        ''' can contain.
  215.        ''' </param>
  216.        '''
  217.        ''' <param name="col">
  218.        ''' this <see cref="NameObjectCollection"/> to copy to the new <see cref="NameObjectCollection"/>
  219.        ''' instance.
  220.        ''' </param>
  221.        ''' ----------------------------------------------------------------------------------------------------
  222.        Public Sub New(capacity As Integer, col As NameObjectCollection)
  223.            MyBase.New(capacity)
  224.            If col Is Nothing Then
  225.                Throw New ArgumentNullException(NameOf(col))
  226.            End If
  227.  
  228.            Me.Add(col)
  229.        End Sub
  230.  
  231.        ''' ----------------------------------------------------------------------------------------------------
  232.        ''' <summary>
  233.        ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
  234.        ''' class that is empty, has the specified initial capacity and uses the specified
  235.        ''' hash code provider and the specified comparer.
  236.        ''' </summary>
  237.        ''' ----------------------------------------------------------------------------------------------------
  238.        ''' <param name="capacity">
  239.        ''' The initial number of entries that this <see cref="NameObjectCollection"/>
  240.        ''' can contain.
  241.        ''' </param>
  242.        '''
  243.        ''' <param name="hashProvider">
  244.        ''' The <see cref="System.Collections.IHashCodeProvider"/> that will supply the hash codes for
  245.        ''' all keys in this <see cref="NameObjectCollection"/>.
  246.        ''' </param>
  247.        '''
  248.        ''' <param name="comparer">
  249.        ''' The <see cref="System.Collections.IComparer"/> to use to determine whether two keys are equal.
  250.        ''' </param>
  251.        ''' ----------------------------------------------------------------------------------------------------
  252.        <Obsolete("Please use NameObjectCollection(Int32, IEqualityComparer) instead.")>
  253.        Public Sub New(capacity As Integer, hashProvider As IHashCodeProvider, comparer As IComparer)
  254.            MyBase.New(capacity, hashProvider, comparer)
  255.        End Sub
  256.  
  257.        ''' ----------------------------------------------------------------------------------------------------
  258.        ''' <summary>
  259.        ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
  260.        ''' class that is serializable and uses the specified <see cref="System.Runtime.Serialization.SerializationInfo"/>
  261.        ''' and <see cref="System.Runtime.Serialization.StreamingContext"/>.
  262.        ''' </summary>
  263.        ''' ----------------------------------------------------------------------------------------------------
  264.        ''' <param name="info">
  265.        ''' A <see cref="System.Runtime.Serialization.SerializationInfo"/> object that contains the information
  266.        ''' required to serialize the new <see cref="NameObjectCollection"/>
  267.        ''' instance.
  268.        ''' </param>
  269.        '''
  270.        ''' <param name="context">
  271.        ''' A <see cref="System.Runtime.Serialization.StreamingContext"/> object that contains the source
  272.        ''' and destination of the serialized stream associated with the new <see cref="NameObjectCollection"/>
  273.        ''' instance.
  274.        ''' </param>
  275.        ''' ----------------------------------------------------------------------------------------------------
  276.        Protected Sub New(info As SerializationInfo, context As StreamingContext)
  277.            MyBase.New(info, context)
  278.        End Sub
  279.  
  280. #End Region
  281.  
  282. #Region " Public Methods "
  283.  
  284.        ''' ----------------------------------------------------------------------------------------------------
  285.        ''' <summary>
  286.        ''' Copies the entries in the specified <see cref="NameObjectCollection"/>
  287.        ''' to the current <see cref="NameObjectCollection"/>.
  288.        ''' </summary>
  289.        ''' ----------------------------------------------------------------------------------------------------
  290.        ''' <param name="c">
  291.        ''' this <see cref="NameObjectCollection"/> to copy to the current
  292.        ''' <see cref="NameObjectCollection"/>.
  293.        ''' </param>
  294.        ''' ----------------------------------------------------------------------------------------------------
  295.        Public Sub Add(c As NameObjectCollection)
  296.            If c Is Nothing Then
  297.                Throw New ArgumentNullException(NameOf(c))
  298.            End If
  299.  
  300.            Me.InvalidateCachedArrays()
  301.            Dim count As Integer = c.Count
  302.            For i As Integer = 0 To count - 1
  303.                Dim key As String = c.GetKey(i)
  304.                Dim values() As Object = c.GetValues(i)
  305.                If values IsNot Nothing Then
  306.                    For j As Integer = 0 To values.Length - 1
  307.                        Me.Add(key, values(j))
  308.                    Next j
  309.                Else
  310.                    Me.Add(key, Nothing)
  311.                End If
  312.            Next i
  313.        End Sub
  314.  
  315.        ''' ----------------------------------------------------------------------------------------------------
  316.        ''' <summary>
  317.        ''' Invalidates the cached arrays and removes all entries from this <see cref="NameObjectCollection"/>.
  318.        ''' </summary>
  319.        ''' ----------------------------------------------------------------------------------------------------
  320.        Public Overridable Sub Clear()
  321.            If MyBase.IsReadOnly Then
  322.                Throw New NotSupportedException("CollectionReadOnly")
  323.            End If
  324.  
  325.            Me.InvalidateCachedArrays()
  326.            MyBase.BaseClear()
  327.        End Sub
  328.  
  329.        ''' ----------------------------------------------------------------------------------------------------
  330.        ''' <summary>
  331.        ''' Copies the entire <see cref="NameObjectCollection"/> to a compatible
  332.        ''' one-dimensional <see cref="System.Array"/>, starting at the specified index of the target array.
  333.        ''' </summary>
  334.        ''' ----------------------------------------------------------------------------------------------------
  335.        ''' <param name="dest">
  336.        ''' The one-dimensional <see cref="System.Array"/> that is the destination of the elements copied
  337.        ''' from <see cref="NameObjectCollection"/>. The <see cref="System.Array"/> must
  338.        ''' have zero-based indexing.
  339.        ''' </param>
  340.        '''
  341.        ''' <param name="index">
  342.        ''' The zero-based index in dest at which copying begins.
  343.        ''' </param>
  344.        ''' ----------------------------------------------------------------------------------------------------
  345.        Public Sub CopyTo(dest As System.Array, index As Integer)
  346.            If dest Is Nothing Then
  347.                Throw New ArgumentNullException(NameOf(dest))
  348.            End If
  349.  
  350.            If dest.Rank <> 1 Then
  351.                Throw New ArgumentException("Arg_MultiRank")
  352.            End If
  353.  
  354.            If index < 0 Then
  355.                Throw New ArgumentOutOfRangeException(NameOf(index), "IndexOutOfRange")
  356.            End If
  357.  
  358.            Dim count As Integer = Me.Count
  359.            If dest.Length - index < count Then
  360.                Throw New ArgumentException("Arg_InsufficientSpace")
  361.            End If
  362.  
  363.            If Me._all Is Nothing Then
  364.                Dim array(count - 1) As Object
  365.                For i As Integer = 0 To count - 1
  366.                    array(i) = Me.[Get](i)
  367.                    dest.SetValue(array(i), i + index)
  368.                Next i
  369.  
  370.                Me._all = array
  371.            Else
  372.                For j As Integer = 0 To count - 1
  373.                    dest.SetValue(_all(j), j + index)
  374.                Next j
  375.            End If
  376.        End Sub
  377.  
  378.        ''' ----------------------------------------------------------------------------------------------------
  379.        ''' <summary>
  380.        ''' Gets a value indicating whether this <see cref="NameObjectCollection"/>
  381.        ''' contains keys that are not null.
  382.        ''' </summary>
  383.        ''' ----------------------------------------------------------------------------------------------------
  384.        ''' <returns>
  385.        ''' true if this <see cref="NameObjectCollection"/> contains keys
  386.        ''' that are not null; otherwise, false.
  387.        ''' </returns>
  388.        ''' ----------------------------------------------------------------------------------------------------
  389.        Public Function HasKeys() As Boolean
  390.            Return Me.InternalHasKeys()
  391.        End Function
  392.  
  393.        ''' ----------------------------------------------------------------------------------------------------
  394.        ''' <summary>
  395.        ''' Adds an entry with the specified name and value to this <see cref="NameObjectCollection"/>.
  396.        ''' </summary>
  397.        ''' ----------------------------------------------------------------------------------------------------
  398.        ''' <param name="name">
  399.        ''' The <see cref="String"/> key of the entry to add. The key can be null.
  400.        ''' </param>
  401.        '''
  402.        ''' <param name="value">
  403.        ''' The <see cref="String"/> value of the entry to add. The value can be null.
  404.        ''' </param>
  405.        ''' ----------------------------------------------------------------------------------------------------
  406.        Public Overridable Sub Add(name As String, value As Object)
  407.            If MyBase.IsReadOnly Then
  408.                Throw New NotSupportedException("CollectionReadOnly")
  409.            End If
  410.  
  411.            Me.InvalidateCachedArrays()
  412.            Dim arrayList As ArrayList = DirectCast(MyBase.BaseGet(name), ArrayList)
  413.            If arrayList Is Nothing Then
  414.                arrayList = New ArrayList(1)
  415.                If value IsNot Nothing Then
  416.                    arrayList.Add(value)
  417.                End If
  418.  
  419.                MyBase.BaseAdd(name, arrayList)
  420.            ElseIf value IsNot Nothing Then
  421.                arrayList.Add(value)
  422.            End If
  423.        End Sub
  424.  
  425.        ''' ----------------------------------------------------------------------------------------------------
  426.        ''' <summary>
  427.        ''' Gets the values associated with the specified key from this <see cref="NameObjectCollection"/>
  428.        ''' combined into one comma-separated list.
  429.        ''' </summary>
  430.        ''' ----------------------------------------------------------------------------------------------------
  431.        ''' <param name="name">
  432.        ''' The <see cref="String"/> key of the entry that contains the values to get. The key can
  433.        ''' be null.
  434.        ''' </param>
  435.        ''' ----------------------------------------------------------------------------------------------------
  436.        ''' <returns>
  437.        ''' A <see cref="String"/> that contains a comma-separated list of the values associated
  438.        ''' with the specified key from this <see cref="NameObjectCollection"/>,
  439.        ''' if found; otherwise, null.
  440.        ''' </returns>
  441.        ''' ----------------------------------------------------------------------------------------------------
  442.        Public Overridable Function [Get](name As String) As Object
  443.            Dim list As ArrayList = DirectCast(MyBase.BaseGet(name), ArrayList)
  444.            Return NameObjectCollection.GetAsOneObject(list)
  445.        End Function
  446.  
  447.        ''' ----------------------------------------------------------------------------------------------------
  448.        ''' <summary>
  449.        ''' Gets the values associated with the specified key from this <see cref="NameObjectCollection"/>.
  450.        ''' </summary>
  451.        ''' ----------------------------------------------------------------------------------------------------
  452.        ''' <param name="name">
  453.        ''' The <see cref="String"/> key of the entry that contains the values to get. The key can
  454.        ''' be null.
  455.        ''' </param>
  456.        ''' ----------------------------------------------------------------------------------------------------
  457.        ''' <returns>
  458.        ''' A <see cref="Object"/> array that contains the values associated with the specified
  459.        ''' key from this <see cref="NameObjectCollection"/>, if found; otherwise,
  460.        ''' null.
  461.        ''' </returns>
  462.        ''' ----------------------------------------------------------------------------------------------------
  463.        Public Overridable Function GetValues(name As String) As Object()
  464.            Dim list As ArrayList = DirectCast(MyBase.BaseGet(name), ArrayList)
  465.            Return NameObjectCollection.GetAsObjectArray(list)
  466.        End Function
  467.  
  468.        ''' ----------------------------------------------------------------------------------------------------
  469.        ''' <summary>
  470.        ''' Sets the value of an entry in this <see cref="NameObjectCollection"/>.
  471.        ''' </summary>
  472.        ''' ----------------------------------------------------------------------------------------------------
  473.        ''' <param name="name">
  474.        ''' The <see cref="String"/> key of the entry to add the new value to. The key can be null.
  475.        ''' </param>
  476.        '''
  477.        ''' <param name="value">
  478.        ''' The <see cref="Object"/> that represents the new value to add to the specified entry.
  479.        ''' The value can be null.
  480.        ''' </param>
  481.        ''' ----------------------------------------------------------------------------------------------------
  482.        Public Overridable Sub [Set](name As String, value As Object)
  483.            If MyBase.IsReadOnly Then
  484.                Throw New NotSupportedException("CollectionReadOnly")
  485.            End If
  486.  
  487.            Me.InvalidateCachedArrays()
  488.            Dim arrayList As New ArrayList(1) From {value}
  489.            MyBase.BaseSet(name, arrayList)
  490.        End Sub
  491.  
  492.        ''' ----------------------------------------------------------------------------------------------------
  493.        ''' <summary>
  494.        ''' Removes the entries with the specified key from this <see cref="NameObjectCollection"/>
  495.        ''' instance.
  496.        ''' </summary>
  497.        ''' ----------------------------------------------------------------------------------------------------
  498.        ''' <param name="name">
  499.        ''' The <see cref="String"/> key of the entry to remove. The key can be null.
  500.        ''' </param>
  501.        ''' ----------------------------------------------------------------------------------------------------
  502.        Public Overridable Sub Remove(name As String)
  503.            Me.InvalidateCachedArrays()
  504.            MyBase.BaseRemove(name)
  505.        End Sub
  506.  
  507.        ''' ----------------------------------------------------------------------------------------------------
  508.        ''' <summary>
  509.        ''' Gets the values at the specified index of this <see cref="NameObjectCollection"/>
  510.        ''' combined into one comma-separated list.
  511.        ''' </summary>
  512.        ''' ----------------------------------------------------------------------------------------------------
  513.        ''' <param name="index">
  514.        ''' The zero-based index of the entry that contains the values to get from the collection.
  515.        ''' </param>
  516.        ''' ----------------------------------------------------------------------------------------------------
  517.        ''' <returns>
  518.        ''' A <see cref="String"/> that contains a comma-separated list of the values at the specified
  519.        ''' index of this <see cref="NameObjectCollection"/>, if found; otherwise,
  520.        ''' null.
  521.        ''' </returns>
  522.        ''' ----------------------------------------------------------------------------------------------------
  523.        Public Overridable Function [Get](index As Integer) As Object
  524.            Dim list As ArrayList = DirectCast(MyBase.BaseGet(index), ArrayList)
  525.            Return NameObjectCollection.GetAsOneObject(list)
  526.        End Function
  527.  
  528.        ''' ----------------------------------------------------------------------------------------------------
  529.        ''' <summary>
  530.        ''' Gets the values at the specified index of this <see cref="NameObjectCollection"/>.
  531.        ''' </summary>
  532.        ''' ----------------------------------------------------------------------------------------------------
  533.        ''' <param name="index">
  534.        ''' The zero-based index of the entry that contains the values to get from the collection.
  535.        ''' </param>
  536.        ''' ----------------------------------------------------------------------------------------------------
  537.        ''' <returns>
  538.        ''' A <see cref="String"/> array that contains the values at the specified index of the
  539.        ''' <see cref="NameObjectCollection"/>, if found; otherwise, null.
  540.        ''' </returns>
  541.        ''' ----------------------------------------------------------------------------------------------------
  542.        Public Overridable Function GetValues(index As Integer) As Object()
  543.            Dim list As ArrayList = DirectCast(MyBase.BaseGet(index), ArrayList)
  544.            Return NameObjectCollection.GetAsObjectArray(list)
  545.        End Function
  546.  
  547.        ''' ----------------------------------------------------------------------------------------------------
  548.        ''' <summary>
  549.        ''' Gets the key at the specified index of this <see cref="NameObjectCollection"/>.
  550.        ''' </summary>
  551.        ''' ----------------------------------------------------------------------------------------------------
  552.        ''' <param name="index">
  553.        ''' The zero-based index of the key to get from the collection.
  554.        ''' </param>
  555.        ''' ----------------------------------------------------------------------------------------------------
  556.        ''' <returns>
  557.        ''' A <see cref="String"/> that contains the key at the specified index of this <see cref="NameObjectCollection"/>,
  558.        ''' if found; otherwise, null.
  559.        ''' </returns>
  560.        ''' ----------------------------------------------------------------------------------------------------
  561.        Public Overridable Function GetKey(index As Integer) As String
  562.            Return MyBase.BaseGetKey(index)
  563.        End Function
  564.  
  565. #End Region
  566.  
  567. #Region " Private Methods "
  568.  
  569.        ''' ----------------------------------------------------------------------------------------------------
  570.        ''' <summary>
  571.        ''' Resets the cached arrays of the collection to null.
  572.        ''' </summary>
  573.        ''' ----------------------------------------------------------------------------------------------------
  574.        Protected Sub InvalidateCachedArrays()
  575.            Me._all = Nothing
  576.            Me._allKeys = Nothing
  577.        End Sub
  578.  
  579.        ''' ----------------------------------------------------------------------------------------------------
  580.        ''' <summary>
  581.        ''' Gets a value indicating whether the <see cref="NameObjectCollection"/> has keys that are not null.
  582.        ''' </summary>
  583.        ''' ----------------------------------------------------------------------------------------------------
  584.        ''' <returns>
  585.        '''  <c>true</c> if the <see cref="NameObjectCollection"/> has keys that are not null; otherwise, <c>false</c>.
  586.        ''' </returns>
  587.        ''' ----------------------------------------------------------------------------------------------------
  588.        Friend Overridable Function InternalHasKeys() As Boolean
  589.            Return MyBase.BaseHasKeys()
  590.        End Function
  591.  
  592.        ''' ----------------------------------------------------------------------------------------------------
  593.        ''' <summary>
  594.        ''' Converts an <see cref="ArrayList"/> to a single object.
  595.        ''' </summary>
  596.        ''' ----------------------------------------------------------------------------------------------------
  597.        ''' <param name="list">
  598.        ''' The <see cref="ArrayList"/> to convert.
  599.        ''' </param>
  600.        ''' ----------------------------------------------------------------------------------------------------
  601.        ''' <returns>
  602.        ''' The converted object. If the <see cref="ArrayList"/> contains a single item, that item is returned.
  603.        ''' If the <see cref="ArrayList"/> contains multiple items,
  604.        ''' a <see cref="Collection"/> object is created with the items and returned.
  605.        ''' If the <see cref="ArrayList"/> is empty or null, null is returned.
  606.        ''' </returns>
  607.        ''' ----------------------------------------------------------------------------------------------------
  608.        Private Shared Function GetAsOneObject(list As ArrayList) As Object
  609.            Dim num As Integer = If(list?.Count, 0)
  610.            If num = 1 Then
  611.                Return list(0)
  612.            End If
  613.  
  614.            If num > 1 Then
  615.                Dim collection As New Collection From {list(0)}
  616.                For i As Integer = 1 To num - 1
  617.                    collection.Add(list(i))
  618.                Next i
  619.                Return collection
  620.            End If
  621.  
  622.            Return Nothing
  623.        End Function
  624.  
  625.        ''' ----------------------------------------------------------------------------------------------------
  626.        ''' <summary>
  627.        ''' Converts an <see cref="ArrayList"/> to an array of objects.
  628.        ''' </summary>
  629.        ''' ----------------------------------------------------------------------------------------------------
  630.        ''' <param name="list">
  631.        ''' The <see cref="ArrayList"/> to convert.
  632.        ''' </param>
  633.        ''' ----------------------------------------------------------------------------------------------------
  634.        ''' <returns>
  635.        ''' An array of objects containing the items from the <see cref="ArrayList"/>.
  636.        ''' If the <see cref="ArrayList"/> is empty or null, null is returned.
  637.        ''' </returns>
  638.        ''' ----------------------------------------------------------------------------------------------------
  639.        Private Shared Function GetAsObjectArray(list As ArrayList) As Object()
  640.            Dim num As Integer = If(list?.Count, 0)
  641.            If num = 0 Then
  642.                Return Nothing
  643.            End If
  644.  
  645.            Dim array(num - 1) As Object
  646.            list.CopyTo(0, array, 0, num)
  647.            Return array
  648.        End Function
  649.  
  650. #End Region
  651.  
  652.    End Class
  653.  
  654. End Namespace
  655.  
  656.  
7  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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.  
8  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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.  
9  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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.  
10  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) 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.  
Páginas: [1] 2 3 4 5 6 7 8 9 10 11 12 13 14
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines