Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

<< < (115/119) > >>

Elektro Enjuto:
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
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 08-July-2023
' ***********************************************************************
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.Collections.Specialized
Imports System.Runtime.Serialization
 
#End Region
 
Namespace DevCase.Runtime.Collections
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Similarly to a <see cref="NameValueCollection"/>, this class represents a
   ''' collection of associated <see cref="String"/> keys and <see cref="Object"/> values
   ''' that can be accessed either with the name or with the index.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <Serializable>
   Public Class NameObjectCollection : Inherits NameObjectCollectionBase
 
#Region " Private MethFieldsods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Cached array of values in this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private _all() As Object
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Cached array of keys in this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private _allKeys() As String
 
#End Region
 
#Region " Properties "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the entry with the specified key in this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="name">
       ''' The <see cref="String"/> key of the entry to locate. The key can be null.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="Object"/> that contains the comma-separated list of values associated with
       ''' the specified key, if found; otherwise, null.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Default Public Property Item(name As String) As Object
           Get
               Return Me.[Get](name)
           End Get
           Set(value As Object)
               Me.[Set](name, value)
           End Set
       End Property
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the entry at the specified index of this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="index">
       ''' The zero-based index of the entry to locate in the collection.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="Object"/> that contains the comma-separated list of values at the specified
       ''' index of the collection.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Default Public ReadOnly Property Item(index As Integer) As Object
           Get
               Return Me.[Get](index)
           End Get
       End Property
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets all the keys in this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="String"/> array that contains all the keys of this <see cref="NameObjectCollection"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable ReadOnly Property AllKeys() As String()
           Get
               If Me._allKeys Is Nothing Then
                   Me._allKeys = Me.BaseGetAllKeys()
               End If
 
               Return Me._allKeys
           End Get
       End Property
 
#End Region
 
#Region " Constructors "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
       ''' class that is empty, has the default initial capacity and uses the default case-insensitive
       ''' hash code provider and the default case-insensitive comparer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub New()
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
       ''' class that is empty, has the specified initial capacity and uses the specified
       ''' hash code provider and the specified comparer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="hashProvider">
       ''' The <see cref="System.Collections.IHashCodeProvider"/> that will supply the hash codes for
       ''' all keys in this <see cref="NameObjectCollection"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="comparer">
       ''' The <see cref="System.Collections.IComparer"/> to use to determine whether two keys are equal.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <Obsolete("Please use NameObjectCollection(IEqualityComparer) instead.")>
       Public Sub New(hashProvider As IHashCodeProvider, comparer As IComparer)
           MyBase.New(hashProvider, comparer)
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
       ''' class that is empty, has the specified initial capacity and uses the default
       ''' case-insensitive hash code provider and the default case-insensitive comparer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="capacity">
       ''' The initial number of entries that this <see cref="NameObjectCollection"/>
       ''' can contain.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub New(capacity As Integer)
           MyBase.New(capacity)
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
       ''' class that is empty, has the default initial capacity, and uses the specified
       ''' <see cref="System.Collections.IEqualityComparer"/> object.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="equalityComparer">
       ''' The <see cref="System.Collections.IEqualityComparer"/> object to use to determine whether two
       ''' keys are equal and to generate hash codes for the keys in the collection.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub New(equalityComparer As IEqualityComparer)
           MyBase.New(equalityComparer)
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
       ''' class that is empty, has the specified initial capacity, and uses the specified
       ''' <see cref="System.Collections.IEqualityComparer"/> object.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="capacity">
       ''' The initial number of entries that this <see cref="NameObjectCollection"/>
       ''' object can contain.
       ''' </param>
       '''
       ''' <param name="equalityComparer">
       ''' The <see cref="System.Collections.IEqualityComparer"/> object to use to determine whether two
       ''' keys are equal and to generate hash codes for the keys in the collection.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub New(capacity As Integer, equalityComparer As IEqualityComparer)
           MyBase.New(capacity, equalityComparer)
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Copies the entries from the specified <see cref="NameObjectCollection"/>
       ''' to a new <see cref="NameObjectCollection"/> with the specified
       ''' initial capacity or the same initial capacity as the number of entries copied,
       ''' whichever is greater, and using the default case-insensitive hash code provider
       ''' and the default case-insensitive comparer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="capacity">
       ''' The initial number of entries that this <see cref="NameObjectCollection"/>
       ''' can contain.
       ''' </param>
       '''
       ''' <param name="col">
       ''' this <see cref="NameObjectCollection"/> to copy to the new <see cref="NameObjectCollection"/>
       ''' instance.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub New(capacity As Integer, col As NameObjectCollection)
           MyBase.New(capacity)
           If col Is Nothing Then
               Throw New ArgumentNullException(NameOf(col))
           End If
 
           Me.Add(col)
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
       ''' class that is empty, has the specified initial capacity and uses the specified
       ''' hash code provider and the specified comparer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="capacity">
       ''' The initial number of entries that this <see cref="NameObjectCollection"/>
       ''' can contain.
       ''' </param>
       '''
       ''' <param name="hashProvider">
       ''' The <see cref="System.Collections.IHashCodeProvider"/> that will supply the hash codes for
       ''' all keys in this <see cref="NameObjectCollection"/>.
       ''' </param>
       '''
       ''' <param name="comparer">
       ''' The <see cref="System.Collections.IComparer"/> to use to determine whether two keys are equal.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <Obsolete("Please use NameObjectCollection(Int32, IEqualityComparer) instead.")>
       Public Sub New(capacity As Integer, hashProvider As IHashCodeProvider, comparer As IComparer)
           MyBase.New(capacity, hashProvider, comparer)
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="NameObjectCollection"/>
       ''' class that is serializable and uses the specified <see cref="System.Runtime.Serialization.SerializationInfo"/>
       ''' and <see cref="System.Runtime.Serialization.StreamingContext"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="info">
       ''' A <see cref="System.Runtime.Serialization.SerializationInfo"/> object that contains the information
       ''' required to serialize the new <see cref="NameObjectCollection"/>
       ''' instance.
       ''' </param>
       '''
       ''' <param name="context">
       ''' A <see cref="System.Runtime.Serialization.StreamingContext"/> object that contains the source
       ''' and destination of the serialized stream associated with the new <see cref="NameObjectCollection"/>
       ''' instance.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Protected Sub New(info As SerializationInfo, context As StreamingContext)
           MyBase.New(info, context)
       End Sub
 
#End Region
 
#Region " Public Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Copies the entries in the specified <see cref="NameObjectCollection"/>
       ''' to the current <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="c">
       ''' this <see cref="NameObjectCollection"/> to copy to the current
       ''' <see cref="NameObjectCollection"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub Add(c As NameObjectCollection)
           If c Is Nothing Then
               Throw New ArgumentNullException(NameOf(c))
           End If
 
           Me.InvalidateCachedArrays()
           Dim count As Integer = c.Count
           For i As Integer = 0 To count - 1
               Dim key As String = c.GetKey(i)
               Dim values() As Object = c.GetValues(i)
               If values IsNot Nothing Then
                   For j As Integer = 0 To values.Length - 1
                       Me.Add(key, values(j))
                   Next j
               Else
                   Me.Add(key, Nothing)
               End If
           Next i
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Invalidates the cached arrays and removes all entries from this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Sub Clear()
           If MyBase.IsReadOnly Then
               Throw New NotSupportedException("CollectionReadOnly")
           End If
 
           Me.InvalidateCachedArrays()
           MyBase.BaseClear()
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Copies the entire <see cref="NameObjectCollection"/> to a compatible
       ''' one-dimensional <see cref="System.Array"/>, starting at the specified index of the target array.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="dest">
       ''' The one-dimensional <see cref="System.Array"/> that is the destination of the elements copied
       ''' from <see cref="NameObjectCollection"/>. The <see cref="System.Array"/> must
       ''' have zero-based indexing.
       ''' </param>
       '''
       ''' <param name="index">
       ''' The zero-based index in dest at which copying begins.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub CopyTo(dest As System.Array, index As Integer)
           If dest Is Nothing Then
               Throw New ArgumentNullException(NameOf(dest))
           End If
 
           If dest.Rank <> 1 Then
               Throw New ArgumentException("Arg_MultiRank")
           End If
 
           If index < 0 Then
               Throw New ArgumentOutOfRangeException(NameOf(index), "IndexOutOfRange")
           End If
 
           Dim count As Integer = Me.Count
           If dest.Length - index < count Then
               Throw New ArgumentException("Arg_InsufficientSpace")
           End If
 
           If Me._all Is Nothing Then
               Dim array(count - 1) As Object
               For i As Integer = 0 To count - 1
                   array(i) = Me.[Get](i)
                   dest.SetValue(array(i), i + index)
               Next i
 
               Me._all = array
           Else
               For j As Integer = 0 To count - 1
                   dest.SetValue(_all(j), j + index)
               Next j
           End If
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets a value indicating whether this <see cref="NameObjectCollection"/>
       ''' contains keys that are not null.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' true if this <see cref="NameObjectCollection"/> contains keys
       ''' that are not null; otherwise, false.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Function HasKeys() As Boolean
           Return Me.InternalHasKeys()
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Adds an entry with the specified name and value to this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="name">
       ''' The <see cref="String"/> key of the entry to add. The key can be null.
       ''' </param>
       '''
       ''' <param name="value">
       ''' The <see cref="String"/> value of the entry to add. The value can be null.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Sub Add(name As String, value As Object)
           If MyBase.IsReadOnly Then
               Throw New NotSupportedException("CollectionReadOnly")
           End If
 
           Me.InvalidateCachedArrays()
           Dim arrayList As ArrayList = DirectCast(MyBase.BaseGet(name), ArrayList)
           If arrayList Is Nothing Then
               arrayList = New ArrayList(1)
               If value IsNot Nothing Then
                   arrayList.Add(value)
               End If
 
               MyBase.BaseAdd(name, arrayList)
           ElseIf value IsNot Nothing Then
               arrayList.Add(value)
           End If
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the values associated with the specified key from this <see cref="NameObjectCollection"/>
       ''' combined into one comma-separated list.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="name">
       ''' The <see cref="String"/> key of the entry that contains the values to get. The key can
       ''' be null.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="String"/> that contains a comma-separated list of the values associated
       ''' with the specified key from this <see cref="NameObjectCollection"/>,
       ''' if found; otherwise, null.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Function [Get](name As String) As Object
           Dim list As ArrayList = DirectCast(MyBase.BaseGet(name), ArrayList)
           Return NameObjectCollection.GetAsOneObject(list)
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the values associated with the specified key from this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="name">
       ''' The <see cref="String"/> key of the entry that contains the values to get. The key can
       ''' be null.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="Object"/> array that contains the values associated with the specified
       ''' key from this <see cref="NameObjectCollection"/>, if found; otherwise,
       ''' null.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Function GetValues(name As String) As Object()
           Dim list As ArrayList = DirectCast(MyBase.BaseGet(name), ArrayList)
           Return NameObjectCollection.GetAsObjectArray(list)
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Sets the value of an entry in this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="name">
       ''' The <see cref="String"/> key of the entry to add the new value to. The key can be null.
       ''' </param>
       '''
       ''' <param name="value">
       ''' The <see cref="Object"/> that represents the new value to add to the specified entry.
       ''' The value can be null.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Sub [Set](name As String, value As Object)
           If MyBase.IsReadOnly Then
               Throw New NotSupportedException("CollectionReadOnly")
           End If
 
           Me.InvalidateCachedArrays()
           Dim arrayList As New ArrayList(1) From {value}
           MyBase.BaseSet(name, arrayList)
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Removes the entries with the specified key from this <see cref="NameObjectCollection"/>
       ''' instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="name">
       ''' The <see cref="String"/> key of the entry to remove. The key can be null.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Sub Remove(name As String)
           Me.InvalidateCachedArrays()
           MyBase.BaseRemove(name)
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the values at the specified index of this <see cref="NameObjectCollection"/>
       ''' combined into one comma-separated list.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="index">
       ''' The zero-based index of the entry that contains the values to get from the collection.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="String"/> that contains a comma-separated list of the values at the specified
       ''' index of this <see cref="NameObjectCollection"/>, if found; otherwise,
       ''' null.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Function [Get](index As Integer) As Object
           Dim list As ArrayList = DirectCast(MyBase.BaseGet(index), ArrayList)
           Return NameObjectCollection.GetAsOneObject(list)
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the values at the specified index of this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="index">
       ''' The zero-based index of the entry that contains the values to get from the collection.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="String"/> array that contains the values at the specified index of the
       ''' <see cref="NameObjectCollection"/>, if found; otherwise, null.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Function GetValues(index As Integer) As Object()
           Dim list As ArrayList = DirectCast(MyBase.BaseGet(index), ArrayList)
           Return NameObjectCollection.GetAsObjectArray(list)
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the key at the specified index of this <see cref="NameObjectCollection"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="index">
       ''' The zero-based index of the key to get from the collection.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' A <see cref="String"/> that contains the key at the specified index of this <see cref="NameObjectCollection"/>,
       ''' if found; otherwise, null.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Function GetKey(index As Integer) As String
           Return MyBase.BaseGetKey(index)
       End Function
 
#End Region
 
#Region " Private Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Resets the cached arrays of the collection to null.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Protected Sub InvalidateCachedArrays()
           Me._all = Nothing
           Me._allKeys = Nothing
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets a value indicating whether the <see cref="NameObjectCollection"/> has keys that are not null.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       '''  <c>true</c> if the <see cref="NameObjectCollection"/> has keys that are not null; otherwise, <c>false</c>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Friend Overridable Function InternalHasKeys() As Boolean
           Return MyBase.BaseHasKeys()
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Converts an <see cref="ArrayList"/> to a single object.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="list">
       ''' The <see cref="ArrayList"/> to convert.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The converted object. If the <see cref="ArrayList"/> contains a single item, that item is returned.
       ''' If the <see cref="ArrayList"/> contains multiple items,
       ''' a <see cref="Collection"/> object is created with the items and returned.
       ''' If the <see cref="ArrayList"/> is empty or null, null is returned.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Private Shared Function GetAsOneObject(list As ArrayList) As Object
           Dim num As Integer = If(list?.Count, 0)
           If num = 1 Then
               Return list(0)
           End If
 
           If num > 1 Then
               Dim collection As New Collection From {list(0)}
               For i As Integer = 1 To num - 1
                   collection.Add(list(i))
               Next i
               Return collection
           End If
 
           Return Nothing
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Converts an <see cref="ArrayList"/> to an array of objects.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="list">
       ''' The <see cref="ArrayList"/> to convert.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' An array of objects containing the items from the <see cref="ArrayList"/>.
       ''' If the <see cref="ArrayList"/> is empty or null, null is returned.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Private Shared Function GetAsObjectArray(list As ArrayList) As Object()
           Dim num As Integer = If(list?.Count, 0)
           If num = 0 Then
               Return Nothing
           End If
 
           Dim array(num - 1) As Object
           list.CopyTo(0, array, 0, num)
           Return array
       End Function
 
#End Region
 
   End Class
 
End Namespace
 
 

Elektro Enjuto:
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
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 08-June-2023
' ***********************************************************************
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " imports "
 
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Collections.Specialized
Imports System.ComponentModel
Imports System.Linq
 
#End Region
 
Namespace DevCase.Runtime.Collections
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Represents a sortable, dynamic data collection that provides notifications when items get added,
   ''' removed, or when the whole list is refreshed.
   ''' <para></para>
   ''' The items in the collection are automatically sorted by the selector method specified in
   ''' <see cref="SortableObservableCollection(Of T).SortingSelector"/> property.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code language="VB">
   ''' Dim collection As New SortableObservableCollection(Of KeyValuePair(Of Integer, String)) With {
   '''     .SortingSelector = Function(pair As KeyValuePair(Of Integer, String)) pair.Key,
   '''     .IsDescending = True
   ''' }
   '''
   ''' collection.Add(New KeyValuePair(Of Integer, String)(7, "abc"))
   ''' collection.Add(New KeyValuePair(Of Integer, String)(3, "xey"))
   ''' collection.Add(New KeyValuePair(Of Integer, String)(6, "ftu"))
   '''
   ''' For Each pair As KeyValuePair(Of Integer, String) In collection
   '''     Console.WriteLine(pair)
   ''' Next pair
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <typeparam name="T">
   ''' </typeparam>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <seealso cref="ObservableCollection(Of T)"/>
   ''' ----------------------------------------------------------------------------------------------------
   Public Class SortableObservableCollection(Of T) : Inherits ObservableCollection(Of T)
 
#Region " Private Fields "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The selector method to sort the items in the collection.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private _sortingSelector As Func(Of T, Object)
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' A value that determine whether the sorting method is ascending or descending.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private _isDescending As Boolean
 
#End Region
 
#Region " Properties "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the selector method to sort the items in the collection.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Property SortingSelector() As Func(Of T, Object)
           Get
               Return Me._sortingSelector
           End Get
           Set(value As Func(Of T, Object))
               If Me._sortingSelector = value Then
                   Return
               End If
 
               Me._sortingSelector = value
               Me.OnPropertyChanged(New PropertyChangedEventArgs(NameOf(SortingSelector)))
               Me.OnPropertyChanged(New PropertyChangedEventArgs("Items[]"))
               Me.OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))
           End Set
       End Property
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets a value indicating whether the sorting method is ascending or descending.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overridable Property IsDescending() As Boolean
           Get
               Return Me._isDescending
           End Get
           Set(value As Boolean)
               If Me._isDescending = value Then
                   Return
               End If
 
               Me._isDescending = value
               Me.OnPropertyChanged(New PropertyChangedEventArgs(NameOf(SortableObservableCollection(Of T).IsDescending)))
               Me.OnPropertyChanged(New PropertyChangedEventArgs("Items[]"))
               Me.OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))
           End Set
       End Property
 
#End Region
 
#Region " Event Raisers "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Raises the <see cref="SortableObservableCollection(Of T).CollectionChanged" /> event
       ''' with the provided arguments.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="e">
       ''' The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Protected Overrides Sub OnCollectionChanged(ByVal e As NotifyCollectionChangedEventArgs)
           MyBase.OnCollectionChanged(e)
           If (Me.SortingSelector Is Nothing) OrElse
               (e.Action = NotifyCollectionChangedAction.Remove) OrElse
               (e.Action = NotifyCollectionChangedAction.Reset) Then
               Return
           End If
 
           Dim query As IEnumerable(Of (Item As T, index As Integer)) = Me.Select(Function(item, index) (item, index))
           query = If(Me.IsDescending, query.OrderByDescending(Function(tuple) Me.SortingSelector()(tuple.Item)), query.OrderBy(Function(tuple) Me.SortingSelector()(tuple.Item)))
           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)
           Using enumerator As IEnumerator(Of (OldIndex As Integer, NewIndex As Integer)) = map.GetEnumerator()
               If enumerator.MoveNext() Then
                   Me.Move(enumerator.Current.OldIndex, enumerator.Current.NewIndex)
               End If
           End Using
       End Sub
 
#End Region
 
   End Class
 
End Namespace
 

Elektro Enjuto:
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
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 13-July-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
' String.Truncate(Integer, Opt: String) As String
' String.TruncateMiddle(Integer, Opt: String) As String
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.ComponentModel
Imports System.Runtime.CompilerServices
 
#End Region
 
#Region " String Extensions "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Extensions.StringExtensions
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Contains custom extension methods to use with a <see cref="String"/> type.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <HideModuleName>
   Public Module StringExtensions
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Truncates the source string to a specified length
       ''' and replaces the truncated part with an ellipsis.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim text As String = "123456789"
       ''' Dim truncated As String = Truncate(text, 5)
       ''' Console.WriteLine(truncated)
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="text">
       ''' The string that will be truncated.
       ''' </param>
       '''
       ''' <param name="maxLength">
       ''' The maximum length of characters to maintain before truncation occurs.
       ''' </param>
       '''
       ''' <param name="elipsis">
       ''' Optional. The ellipsis string to use as the replacement.
       ''' <para></para>
       ''' Default value is: "…" (U+2026)
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The truncated string with the ellipsis in the end.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Function Truncate(text As String, maxLength As Integer, Optional elipsis As String = "…") As String
           If maxLength < 1 Then
               Throw New ArgumentException("Value can't be less than 1.", paramName:=NameOf(maxLength))
           End If
 
           If String.IsNullOrEmpty(text) Then
               Throw New ArgumentNullException(paramName:=NameOf(text))
           End If
 
#If NETCOREAPP Then
           Return If(text.Length <= maxLength, text, String.Concat(text.AsSpan(0, maxLength), elipsis))
#Else
           Return If(text.Length <= maxLength, text, text.Substring(0, maxLength) & elipsis)
#End If
 
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Truncates the source string to a specified length by stripping out the center
       ''' and replacing it with an ellipsis, so that the beginning and end of the string are retained.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim text As String = "123456789"
       ''' Dim truncated As String = TruncateMiddle(text, 6)
       ''' Console.WriteLine(truncated)
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="text">
       ''' The string that will be truncated.
       ''' </param>
       '''
       ''' <param name="maxLength">
       ''' The maximum length of characters to maintain before truncation occurs.
       ''' </param>
       '''
       ''' <param name="elipsis">
       ''' Optional. The ellipsis string to use as the replacement.
       ''' <para></para>
       ''' Default value is: "…" (U+2026)
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The truncated string with the ellipsis in the middle.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Function TruncateMiddle(text As String, maxLength As Integer, Optional elipsis As String = "…") As String
           If maxLength < 1 Then
               Throw New ArgumentException("Value can't be less than 1.", paramName:=NameOf(maxLength))
           End If
 
           If String.IsNullOrEmpty(text) Then
               Throw New ArgumentNullException(paramName:=NameOf(text))
           End If
 
           Dim charsInEachHalf As Integer = maxLength \ 2
           Dim right As String = text.Substring(text.Length - charsInEachHalf, charsInEachHalf)
           Dim left As String = text.Substring(0, maxLength - right.Length)
 
           Return $"{left}{elipsis}{right}"
       End Function
 
   End Module
 
End Namespace
 
#End Region

Elektro Enjuto:
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
Dim obj As Color = Color.LightGoldenrodYellow
obj.Speak("Microsoft Zira Desktop", rate:=-2, volume:=100)

Código
Dim obj As String = "Hola Mundo!"
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
Dim array As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Dim humanReadable As String = String.Join(" ", array)
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
Public Class MyType
 
   Public Property Property1 As String
   Public Property Property2 As String
 
   Public Overrides Function ToString() As String
       Return $"{Me.Property1}, {Me.Property2}"
   End Function
 
End Class
 

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


Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 09-July-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
' Object.Speak(Opt: String, Opt: Integer, Opt: Integer)
' Object.Speak(Opt: InstalledVoice, Opt: Integer, Opt: Integer)
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.ComponentModel
Imports System.Globalization
Imports System.Runtime.CompilerServices
Imports System.Speech.Synthesis
 
#End Region
 
#Region " Object Extensions "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Extensions.ObjectExtensions
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Contains custom extension methods to use with the <see cref="Object"/> type.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <ImmutableObject(True)>
   <HideModuleName>
   Public Module ObjectExtensions
 
#Region " Public Extension Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Speaks the string representation of the source object by using the
       ''' operating system integrated text-to-speech synthesizer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim c As Color = Color.LightGoldenrodYellow
       ''' c.Speak(name:="Microsoft Zira Desktop", rate:=1, volume:=100)
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="obj">
       ''' The object to be spoken.
       ''' </param>
       '''
       ''' <param name="voiceName">
       ''' Optional. Selects the voice to use, such as "Microsoft Zira Desktop" or "Microsoft Helena Desktop".
       ''' <para></para>
       ''' Note: If this value is null, the default voice is the one for the current culture
       ''' specified in the <see cref="CultureInfo.CurrentCulture"/> property.
       ''' </param>
       '''
       ''' <param name="rate">
       ''' Optional. Sets the speaking rate of the selected voice.
       ''' <para></para>
       ''' Allowed values are in the range of -10 (slowest) to +10 (fastest).
       ''' <para></para>
       ''' Default value: 0 (normal rate).
       ''' </param>
       '''
       ''' <param name="volume">
       ''' Optional. Sets the output volume of the synthesizer.
       ''' <para></para>
       ''' Allowed values are in the range of 0 (minimum) to 100 (maximum).
       ''' <para></para>
       ''' Default value: 100 (maximum volume)
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub Speak(obj As Object, Optional voiceName As String = "",
                                       Optional rate As Integer = 0,
                                       Optional volume As Integer = 100)
 
           Using synth As New SpeechSynthesizer()
               If Not String.IsNullOrEmpty(voiceName) Then
                   synth.SelectVoice(voiceName)
               Else
                   Dim voice As InstalledVoice = synth.GetInstalledVoices(CultureInfo.CurrentCulture).FirstOrDefault()
                   If voice IsNot Nothing Then
                       synth.SelectVoice(voice.VoiceInfo.Name)
                   End If
               End If
 
               synth.Rate = rate
               synth.Volume = volume
               synth.Speak(obj.ToString())
           End Using
 
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Speaks the string representation of the source object by using the
       ''' operating system integrated text-to-speech synthesizer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim c As Color = Color.LightGoldenrodYellow
       ''' Dim voice As InstalledVoice = New SpeechSynthesizer().GetInstalledVoices(CultureInfo.CurrentCulture).FirstOrDefault()
       ''' c.Speak(voice:=voice, rate:=1, volume:=100)
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="obj">
       ''' The object to be spoken.
       ''' </param>
       '''
       ''' <param name="voice">
       ''' Optional. Selects the voice to use, such as "Microsoft Zira Desktop" or "Microsoft Helena Desktop".
       ''' <para></para>
       ''' Note: If this value is null, the default voice is the one for the current culture
       ''' specified in the <see cref="CultureInfo.CurrentCulture"/> property.
       ''' </param>
       '''
       ''' <param name="rate">
       ''' Optional. Sets the speaking rate of the selected voice.
       ''' <para></para>
       ''' Allowed values are in the range of -10 (slowest) to +10 (fastest).
       ''' <para></para>
       ''' Default value: 0 (normal rate).
       ''' </param>
       '''
       ''' <param name="volume">
       ''' Optional. Sets the output volume of the synthesizer.
       ''' <para></para>
       ''' Allowed values are in the range of 0 (minimum) to 100 (maximum).
       ''' <para></para>
       ''' Default value: 100 (maximum volume)
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub Speak(obj As Object, Optional voice As InstalledVoice = Nothing,
                                       Optional rate As Integer = 0,
                                       Optional volume As Integer = 100)
 
           If voice Is Nothing Then
               Throw New ArgumentNullException(paramName:=NameOf(voice))
           End If
 
           Speak(obj, voice.VoiceInfo.Name, rate, volume)
 
       End Sub
 
#End Region
 
   End Module
 
End Namespace
 
#End Region
 


De paso les dejo este método

Eleкtro:
Cifrar código fuente de Visual Basic Script (VBS):

 - https://foro.elhacker.net/programacion_visual_basic/cogravemo_puedo_cifrar_archivos_vbs-t409714.0.html;msg2277482#msg2277482

Navegación

[0] Índice de Mensajes

[#] Página Siguiente

[*] Página Anterior