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

 

 


Tema destacado: Guía rápida para descarga de herramientas gratuitas de seguridad y desinfección


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

Desconectado Desconectado

Mensajes: 121



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


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

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

Desconectado Desconectado

Mensajes: 121



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


En línea

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

Desconectado Desconectado

Mensajes: 121



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

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

Desconectado Desconectado

Mensajes: 121



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

@%$& #$ %&#$, ¡hay que decirlo más!.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #574 en: 27 Febrero 2024, 13:15 pm »

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
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #575 en: 27 Febrero 2024, 13:19 pm »

Convertir un objeto Datatable a una tabla en formato Markdown:

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Converts the elements of a <see cref="DataTable"/> into a Markdown table.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <example> This is a code example that shows how to convert a DataTable object to Markdown table.
  7. ''' <code language="VB.NET">
  8. ''' Dim dt As New DataTable()
  9. ''' dt.Columns.Add("ID", GetType(Integer))
  10. ''' dt.Columns.Add("Name", GetType(String))
  11. ''' dt.Rows.Add(1, "John")
  12. ''' dt.Rows.Add(2, "Doe")
  13. '''
  14. ''' Dim markdownTable As String = EnumerableToMarkdownTable(dt)
  15. ''' Console.WriteLine(markdownTable.ToString())
  16. ''' </code>
  17. ''' </example>
  18. ''' ----------------------------------------------------------------------------------------------------
  19. ''' <param name="table">
  20. ''' The source <see cref="DataTable"/>.
  21. ''' </param>
  22. ''' ----------------------------------------------------------------------------------------------------
  23. ''' <returns>
  24. ''' A string representing the Markdown table.
  25. ''' </returns>
  26. ''' ----------------------------------------------------------------------------------------------------
  27. Public Shared Function DataTableToMarkdownTable(table As DataTable) As String
  28.  
  29.    If table Is Nothing Then
  30.        Throw New ArgumentNullException(paramName:=NameOf(table))
  31.    End If
  32.  
  33.    If table.Rows.Count = 0 Then
  34.        Throw New ArgumentNullException("The source table does not contain any row.", paramName:=NameOf(table))
  35.    End If
  36.  
  37.    Dim columnNames As IEnumerable(Of String) = table.Columns.Cast(Of DataColumn)().Select(Function(column) column.ColumnName)
  38.    Dim maxColumnValues As Integer() = columnNames.Select(Function(name) table.AsEnumerable().Max(Function(row) If(row.IsNull(name), 0, row(name).ToString().Length))).ToArray()
  39.  
  40.    Dim headerLine As String = "| " & String.Join(" | ", columnNames) & " |"
  41.    Dim headerDataDividerLine As String = "| " & String.Join(" | ", maxColumnValues.Select(Function(length) New String("-"c, length))) & " |"
  42.  
  43.    Dim lines As IEnumerable(Of String) = {headerLine, headerDataDividerLine}.Concat(
  44.        table.AsEnumerable().Select(
  45.            Function(row) "| " & String.Join(" | ", columnNames.Select(Function(name, i) If(row.IsNull(name), "".PadRight(maxColumnValues(i)), row(name).ToString().PadRight(maxColumnValues(i))))) & " |"
  46.        )
  47.    )
  48.  
  49.    Return String.Join(Environment.NewLine, lines)
  50.  
  51. End Function



Convertir un objeto IEnumerable a una tabla en formato Markdown:

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Converts the elements of an <see cref="IEnumerable(Of T)"/> into a Markdown table.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <remarks>
  7. ''' Original C# concept: <see href="https://github.com/jpierson/to-markdown-table/blob/develop/src/ToMarkdownTable/LinqMarkdownTableExtensions.cs"/>
  8. ''' </remarks>
  9. ''' ----------------------------------------------------------------------------------------------------
  10. ''' <example> This is a code example that shows how to convert a List(Of String) object to Markdown table.
  11. ''' <code language="VB.NET">
  12. ''' Dim list As New List(Of String)
  13. ''' list.Add("John")
  14. ''' list.Add("Doe")
  15. '''
  16. ''' Dim markdownTable As String = EnumerableToMarkdownTable(list)
  17. ''' Console.WriteLine(markdownTable.ToString())
  18. ''' </code>
  19. ''' </example>
  20. ''' ----------------------------------------------------------------------------------------------------
  21. ''' <example> This is a code example that shows how to convert a List of a custom type to Markdown table.
  22. ''' <code language="VB.NET">
  23. ''' Public Class TestClass
  24. '''     Public Property ID As Integer
  25. '''     Public Property Name As String
  26. '''     Public Property Age As Integer
  27. ''' End Class
  28. '''
  29. ''' Dim list As New List(Of TestClass) From {
  30. '''     New TestClass() With {.ID = 1, .Name = "John", .Age = 30},
  31. '''     New TestClass() With {.ID = 2, .Name = "Doe" , .Age = 40}
  32. ''' }
  33. '''
  34. ''' Dim markdownTable As String = EnumerableToMarkdownTable(list)
  35. ''' Console.WriteLine(markdownTable.ToString())
  36. ''' </code>
  37. ''' </example>
  38. ''' ----------------------------------------------------------------------------------------------------
  39. ''' <typeparam name="T">
  40. ''' The type of elements in the collection.
  41. ''' </typeparam>
  42. '''
  43. ''' <param name="source">
  44. ''' The generic collection to convert into a Markdown table.
  45. ''' </param>
  46. ''' ----------------------------------------------------------------------------------------------------
  47. ''' <returns>
  48. ''' A string representing the Markdown table.
  49. ''' </returns>
  50. ''' ----------------------------------------------------------------------------------------------------
  51. Public Shared Function EnumerableToMarkdownTable(Of T)(source As IEnumerable(Of T)) As String
  52.    If source Is Nothing OrElse Not source.Any() Then
  53.        Throw New ArgumentNullException(paramName:=NameOf(source))
  54.    End If
  55.  
  56.    If GetType(T).IsPrimitive OrElse GetType(T) = GetType(String) Then
  57.        Return $"| Items |{Environment.NewLine}| ----- |{Environment.NewLine}{String.Join(Environment.NewLine, source.Select(Function(s) $"| {s} |"))}"
  58.    End If
  59.  
  60.    Dim properties As PropertyInfo() = GetType(T).GetProperties(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.GetProperty)
  61.    Dim fields As IEnumerable(Of FieldInfo) = GetType(T).GetRuntimeFields().Where(Function(f) f.IsPublic)
  62.  
  63.    Dim gettables As IEnumerable(Of MarkdownColumnData) =
  64.        Enumerable.Union(properties.Select(Function(p As PropertyInfo)
  65.                                               Return New MarkdownColumnData With {
  66.                                                   .Name = p.Name,
  67.                                                   .GetValue = Function(obj) p.GetValue(obj),
  68.                                                   .Type = p.PropertyType
  69.                                               }
  70.                                           End Function),
  71.                         fields.Select(Function(f As FieldInfo)
  72.                                           Return New MarkdownColumnData With {
  73.                                               .Name = f.Name,
  74.                                               .GetValue = Function(obj) f.GetValue(obj),
  75.                                               .Type = f.FieldType
  76.                                           }
  77.                                       End Function))
  78.  
  79.    Dim maxColumnValues As Integer() = source.
  80.            Select(Function(x) gettables.Select(Function(p) If(p.GetValue(x)?.ToString()?.Length, 0))).
  81.            Union({gettables.Select(Function(p) p.Name.Length)}).
  82.            Aggregate(
  83.                Enumerable.Repeat(0, gettables.Count()).AsEnumerable(),
  84.                Function(accumulate, x) accumulate.Zip(x, Function(a, b) System.Math.Max(a, b))).
  85.            ToArray()
  86.  
  87.    Dim columnNames As IEnumerable(Of String) =
  88.        gettables.Select(Function(p) p.Name)
  89.  
  90.    Dim headerLine As String =
  91.        "| " & String.Join(" | ", columnNames.Select(Function(n, i) n.PadRight(maxColumnValues(i)))) & " |"
  92.  
  93.    Dim isNumeric As Func(Of Type, Boolean) =
  94.        Function(type As Type)
  95.            Return type = GetType(Byte) OrElse type = GetType(SByte) OrElse type = GetType(UShort) OrElse type = GetType(UInteger) OrElse type = GetType(ULong) OrElse type = GetType(Short) OrElse type = GetType(Integer) OrElse type = GetType(Long) OrElse type = GetType(Decimal) OrElse type = GetType(Double) OrElse type = GetType(Single)
  96.        End Function
  97.  
  98.    Dim rightAlign As Func(Of Type, String) =
  99.        Function(type As Type)
  100.            Return If(isNumeric(type), ":", " "c)
  101.        End Function
  102.  
  103.    Dim headerDataDividerLine As String =
  104.            "| " &
  105.            String.Join("| ", gettables.Select(Function(g, i) New String("-"c, maxColumnValues(i)) & rightAlign(g.Type))) &
  106.            "|"
  107.  
  108.    Dim lines As IEnumerable(Of String) =
  109.        {
  110.            headerLine,
  111.            headerDataDividerLine
  112.        }.Union(source.
  113.            Select(Function(s)
  114.                       Return "| " & String.Join(" | ", gettables.Select(Function(n, i) If(n.GetValue(s)?.ToString(), "").PadRight(maxColumnValues(i)))) & " |"
  115.                   End Function))
  116.  
  117.    Return lines.Aggregate(Function(p, c) p & Environment.NewLine & c)
  118. End Function
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #576 en: 27 Febrero 2024, 13:38 pm »

Los dos siguientes métodos sirven para truncar nombres de archivos que superen los 255 caracteres (incluyendo la longitud de la extensión del archivo), acortando la longitud cuanto sea necesario para no sobrepasar dicho límite, y añadiendo puntos suspensivos (…) al final del nombre del archivo.

Eso es lo que hace con los nombres de archivo (file name), no con las rutas (file path).

En caso de enviar como parámetro a cualquiera de estos dos métodos una ruta de archivo (file path), aparte de realizar los ajustes mencionados con el nombre del archivo y, en caso de que la ruta exceda el límite máximo permitido de 260 caracteres (definido en MAX_PATH), se añadirá el prefijo "\\?\" a la ruta para garantizar la compatibilidad de uso con sistemas NTFS que tengan habilitado el soporte para rutas de longitud extendida (es decir, mayores de 260 caracteres).

De esta forma, y además de prevenir el uso de nombres de archivo (file names) inválidos / demasiado largos, además se garantiza que la aplicación que utilice estos métodos para la manipulación o creación de archivos sea "LONG PATH AWARE".

Nota: Los métodos han pasado pruebas usando rutas locales (relativas y absolutas). No han sido probados con rutas UNC ni adaptados para ello.

Leer con detenimiento el bloque de documentación XML para más información.

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' If needed, truncates the length of the specified file name or full file path  
  4. ''' to comply with Windows OS maximum file name length of 255 characters
  5. ''' (including the file extension length).
  6. ''' <para></para>
  7. ''' If the file name exceeds this limit, it truncates it and
  8. ''' adds a ellipsis (…) at the end of the file name.
  9. ''' <para></para>
  10. ''' If the path exceeds the MAX_PATH limit (260 characters),
  11. ''' it adds the "\\?\" prefix to support extended-length paths.
  12. ''' <para></para>
  13. ''' See also: <see href="https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation"/>
  14. ''' </summary>
  15. ''' ----------------------------------------------------------------------------------------------------
  16. ''' <remarks>
  17. ''' This method is particularly useful when dealing with file names or file paths that might exceed
  18. ''' the maximum allowed length, preventing potential errors related to file name length limitations
  19. ''' when creating files in the drive.
  20. ''' </remarks>
  21. ''' ----------------------------------------------------------------------------------------------------
  22. ''' <param name="filePath">
  23. ''' The file name or full file path.
  24. ''' </param>
  25. '''
  26. ''' <param name="maxFileNameLength">
  27. ''' Optional. The maximum character length that the file name can have.
  28. ''' Default (and maximum) value is 255.
  29. ''' </param>
  30. ''' ----------------------------------------------------------------------------------------------------
  31. ''' <returns>
  32. ''' The truncated file name or full file path.
  33. ''' </returns>
  34. ''' ----------------------------------------------------------------------------------------------------
  35. <DebuggerStepThrough>
  36. Public Shared Function TruncateLongFilePath(filePath As String, Optional maxFileNameLength As Byte = 255) As String
  37.  
  38.    If String.IsNullOrEmpty(filePath) Then
  39.        Throw New ArgumentNullException(paramName:=NameOf(filePath))
  40.    End If
  41.  
  42.    If filePath.StartsWith("\\?\", StringComparison.Ordinal) Then
  43.        filePath = filePath.Substring(4)
  44.    End If
  45.  
  46.    Dim fileInfo As New FileInfo(If(filePath.Length <= 255, filePath, $"\\?\{filePath}"))
  47.    TruncateLongFilePath(fileInfo, maxFileNameLength)
  48.    Return fileInfo.FullName
  49.  
  50. End Function
  51.  
  52. ''' ----------------------------------------------------------------------------------------------------
  53. ''' <summary>
  54. ''' If needed, truncates the length of the file name in
  55. ''' the source <see cref="FileInfo"/> object to comply with
  56. ''' Windows OS maximum file name length of 255 characters
  57. ''' (including the file extension length).
  58. ''' <para></para>
  59. ''' If the file name exceeds this limit, it truncates it and
  60. ''' adds a ellipsis (…) at the end of the file name.
  61. ''' <para></para>
  62. ''' If the path exceeds the MAX_PATH limit (260 characters),
  63. ''' it adds the "\\?\" prefix to support extended-length paths.
  64. ''' <para></para>
  65. ''' See also: <see href="https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation"/>
  66. ''' </summary>
  67. ''' ----------------------------------------------------------------------------------------------------
  68. ''' <remarks>
  69. ''' This method is particularly useful when dealing with file paths that might exceed
  70. ''' the maximum allowed length, preventing potential errors related to file name length limitations
  71. ''' when creating files in the drive.
  72. ''' </remarks>
  73. ''' ----------------------------------------------------------------------------------------------------
  74. ''' <param name="refFileInfo">
  75. ''' The source <see cref="FileInfo"/> object representing a full file path.
  76. ''' <para></para>
  77. ''' When this method returns, this object contains the file path with the file name truncated.
  78. ''' </param>
  79. '''
  80. ''' <param name="maxFileNameLength">
  81. ''' Optional. The maximum character length that the file name can have.
  82. ''' Default (and maximum) value is 255.
  83. ''' </param>
  84. ''' ----------------------------------------------------------------------------------------------------
  85. <DebuggerStepThrough>
  86. Public Shared Sub TruncateLongFilePath(ByRef refFileInfo As FileInfo, Optional maxFileNameLength As Byte = 255)
  87.  
  88.    If refFileInfo Is Nothing Then
  89.        Throw New ArgumentNullException(paramName:=NameOf(refFileInfo))
  90.    End If
  91.  
  92.    If maxFileNameLength = 0 Then
  93.        Throw New ArgumentException("Value must be greater than zero.", paramName:=NameOf(maxFileNameLength))
  94.    End If
  95.  
  96.    If refFileInfo.Name.Length >= maxFileNameLength Then
  97.        Dim fileExt As String = refFileInfo.Extension
  98.        Dim fileName As String = refFileInfo.Name.Substring(0, maxFileNameLength - 1 - fileExt.Length) & $"…{fileExt}"
  99.  
  100.        Dim directoryName As String = Path.GetDirectoryName(refFileInfo.FullName)
  101.        If directoryName.Equals("\\?", StringComparison.Ordinal) Then
  102.            refFileInfo = New FileInfo($"\\?\{fileName}")
  103.  
  104.        ElseIf directoryName.StartsWith("\\?\", StringComparison.Ordinal) Then
  105.            refFileInfo = New FileInfo(Path.Combine(refFileInfo.DirectoryName, fileName))
  106.  
  107.        Else
  108.            Dim fullpath As String = Path.Combine(refFileInfo.DirectoryName, fileName)
  109.            refFileInfo = If(fullpath.Length >= 260, ' MAX_PATH
  110.                          New FileInfo($"\\?\{fullpath}"),
  111.                          New FileInfo(fullpath))
  112.        End If
  113.    End If
  114.  
  115. End Sub
« Última modificación: 27 Febrero 2024, 15:02 pm por Eleкtro » En línea



Parado_larga_duracion_ESP

Desconectado Desconectado

Mensajes: 49


Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #577 en: 27 Febrero 2024, 14:04 pm »

Dejo un repositorio de utilidades de Excel. Tiene 3 ficheros a día de hoy.

1. Para pasar y leer JSONs
2. Demo de carga de datos por AJAX
3. Utilidades varias, incluida REGEX_MATCH. Va bien para validar formatos en Excel.

https://github.com/allnulled/excel-framework/tree/main
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #578 en: 28 Febrero 2024, 13:07 pm »

La siguiente función, por nombre "GetAssemblyNetTargetType", sirve para determinar si el tipo de un archivo de ensamblado es .NET Framework, .NET Standard o .NET Core.

Modo de empleo:
Código
  1. Dim assembly As Assembly = Assembly.LoadFile("C:\Assembly.dll")
  2. Dim assemblyType As NetTargetType = GetAssemblyNetTargetType(assembly)
  3. Console.WriteLine(assemblyType.ToString())

La función contiene tres validaciones diferentes, separadas por Regiones, aunque por lo general solamente se procesará el bloque de código de la primera validación.

Se ha diseñado así con la intención de funcionar correctamente en diversos escenarios, con errores esperados e inesperados de Reflection, y ya sea teniendo en cuenta si se usa esta función desde una aplicación .NET Framework, o .NET Core.

Código
  1. ''' <summary>
  2. ''' Specifies the type of a .NET assembly.
  3. ''' </summary>
  4. Public Enum NetTargetType
  5.    ''' <summary>
  6.    ''' An assembly that targets .NET Framework.
  7.    ''' </summary>
  8.    NetFramework
  9.  
  10.    ''' <summary>
  11.    ''' An assembly that targets .NET Standard.
  12.    ''' </summary>
  13.    NetStandard
  14.  
  15.    ''' <summary>
  16.    ''' An assembly that targets .NET Core.
  17.    ''' </summary>
  18.    NetCore
  19. End Enum

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Determines whether the specified assembly ia a .NET Framework, .NET Standard or .NET Core assembly.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <returns>
  7. ''' A <see cref="NetTargetType"/> value that indicates the type of assembly.
  8. ''' </returns>
  9. ''' ----------------------------------------------------------------------------------------------------
  10. <DebuggerStepThrough>
  11. Public Shared Function GetAssemblyNetTargetType(assembly As Assembly) As NetTargetType
  12.  
  13. #Region " Primary validation "
  14.    Dim parimaryValidationException As Exception = Nothing
  15.  
  16.    Dim attrib As TargetFrameworkAttribute
  17.    Try
  18.        attrib = assembly.GetCustomAttributes.OfType(Of TargetFrameworkAttribute).SingleOrDefault()
  19.        If attrib?.FrameworkName.StartsWith(".NETFramework", StringComparison.OrdinalIgnoreCase) Then
  20.            Return NetTargetType.NetFramework
  21.  
  22.        ElseIf attrib?.FrameworkName.StartsWith(".NETStandard", StringComparison.OrdinalIgnoreCase) Then
  23.            Return NetTargetType.NetStandard
  24.  
  25.        ElseIf attrib?.FrameworkName.StartsWith(".NETCore", StringComparison.OrdinalIgnoreCase) Then
  26.            Return NetTargetType.NetCore
  27.  
  28.        Else
  29.            Throw New NotImplementedException($"Cannot determine type of {NameOf(TargetFrameworkAttribute)}.")
  30.  
  31.        End If
  32.  
  33.    Catch ex As FileNotFoundException When ex.FileName.StartsWith("System.Runtime", StringComparison.OrdinalIgnoreCase)
  34.        ' This exception will be thrown generally when the current
  35.        ' running application is targetting .NET Framework
  36.        ' and Reflection (via method "GetCustomAttributes")
  37.        ' tries to load "System.Runtime" assembly.
  38.  
  39.        Dim assName As New AssemblyName(ex.FileName)
  40.        If assName.Version.Major >= 4 AndAlso assName.Version.Minor <> 0 Then
  41.            Return NetTargetType.NetCore
  42.        Else
  43.            ' Ignore and continue with the alternative .NET Core validation.
  44.        End If
  45.  
  46.    Catch ex As Exception
  47.        parimaryValidationException = ex
  48.        ' Ignore for now, and continue with the alternative validations.
  49.  
  50.    End Try
  51. #End Region
  52.  
  53. #Region " .NET Standard alternative validation (when Primary validation failed) "
  54.    Dim isNetStandard As Boolean =
  55.        assembly.GetReferencedAssemblies().
  56.                 Any(Function(x) x.Name.Equals("netstandard", StringComparison.OrdinalIgnoreCase))
  57.  
  58.    If isNetStandard Then
  59.        Return NetTargetType.NetStandard
  60.    End If
  61. #End Region
  62.  
  63. #Region " .NET Core alternative validation (when Primary validation failed) "
  64. Dim isNetCore As Boolean =
  65.    assembly.GetReferencedAssemblies().
  66.             Any(Function(x As AssemblyName)
  67.                     Return (x.Name.Equals("System.Runtime", StringComparison.OrdinalIgnoreCase) _
  68.                             AndAlso x.Version.Major >= 4 _
  69.                             AndAlso x.Version.Minor <> 0) _
  70.                             OrElse ({"System.Collections",
  71.                                      "System.ComponentModel.Primitives",
  72.                                      "System.Drawing.Primitives",
  73.                                      "System.Windows.Forms"
  74.                                     }.Contains(x.Name) _
  75.                             AndAlso x.Version.Major > 4)
  76.                 End Function)
  77.  
  78.    If isNetCore Then
  79.        Return NetTargetType.NetCore
  80.    End If
  81. #End Region
  82.  
  83.    If parimaryValidationException IsNot Nothing Then
  84.        Throw parimaryValidationException
  85.    End If
  86.    Throw New Exception("Cannot determine type of assembly.")
  87. End Function
« Última modificación: 28 Febrero 2024, 13:27 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #579 en: 28 Febrero 2024, 17:13 pm »

Dos métodos que manipulan el registro de Windows. El primero sirve para crear una nueva entrada en el menú contextual del explorador de Windows al hacer click derecho sobre un tipo de archivo, lo que por lo general sirve para asociar un programa a un tipo/extensión de archivo y poder cargar el archivo haciendo click en esa entrada del menú contextual.

Y el segundo método sirve para borrar la entrada.

Nota: el primer método sirve para crear entradas individuales, no sirve para crear submenús.

Código
  1. ''' <summary>
  2. ''' Creates a registry key that represents a new entry in the Explorer's context-menu for the specified file type.
  3. ''' </summary>
  4. '''
  5. ''' <param name="fileType">
  6. ''' The file type (typically a file extension) for which to create the entry in the Explorer's context-menu.
  7. ''' </param>
  8. '''
  9. ''' <param name="keyName">
  10. ''' The name of the registry key.
  11. ''' </param>
  12. '''
  13. ''' <param name="text">
  14. ''' The display text for the entry in the Explorer's context-menu.
  15. ''' <para></para>
  16. ''' This value can be null, in which case <paramref name="keyName"/> will be used as text.
  17. ''' </param>
  18. '''
  19. ''' <param name="position">
  20. ''' The position of the entry in the Explorer's context-menu.
  21. ''' <para></para>
  22. ''' Valid values are: "top", "middle" and "bottom".
  23. ''' <para></para>
  24. ''' This value can be null.
  25. ''' </param>
  26. '''
  27. ''' <param name="icon">
  28. ''' The icon to show for the entry in the Explorer's context-menu.
  29. ''' <para></para>
  30. ''' This value can be null.
  31. ''' </param>
  32. '''
  33. ''' <param name="command">
  34. ''' The command to execute when the entry is clicked in the Explorer's context-menu.
  35. ''' </param>
  36. <DebuggerStepThrough>
  37. Public Shared Sub CreateFileTypeRegistryMenuEntry(fileType As String, keyName As String,
  38.                                                  text As String, position As String,
  39.                                                  icon As String, command As String)
  40.  
  41.    If String.IsNullOrWhiteSpace(fileType) Then
  42.        Throw New ArgumentNullException(paramName:=NameOf(fileType))
  43.    End If
  44.  
  45.    If String.IsNullOrWhiteSpace(keyName) Then
  46.        Throw New ArgumentNullException(paramName:=NameOf(keyName))
  47.    End If
  48.  
  49.    If String.IsNullOrWhiteSpace(command) Then
  50.        Throw New ArgumentNullException(paramName:=NameOf(command))
  51.    End If
  52.  
  53.    If String.IsNullOrEmpty(text) Then
  54.        text = keyName
  55.    End If
  56.  
  57.    Using rootKey As RegistryKey = Registry.ClassesRoot,
  58.          subKey As RegistryKey = rootKey.CreateSubKey($"{fileType}\shell\{keyName}", writable:=True),
  59.          subKeyCommand As RegistryKey = subKey.CreateSubKey("command", writable:=True)
  60.  
  61.        subKey.SetValue("", text, RegistryValueKind.String)
  62.        subKey.SetValue("icon", icon, RegistryValueKind.String)
  63.        subKey.SetValue("position", position, RegistryValueKind.String)
  64.  
  65.        subKeyCommand.SetValue("", command, RegistryValueKind.String)
  66.    End Using
  67.  
  68. End Sub

Código
  1. ''' <summary>
  2. ''' Deletes an existing registry key representing an entry in the Explorer's context-menu for the specified file type.
  3. ''' </summary>
  4. '''
  5. ''' <param name="fileType">
  6. ''' The file type associated with the registry entry.
  7. ''' </param>
  8. '''
  9. ''' <param name="keyName">
  10. ''' The name of the registry key to delete.
  11. ''' </param>
  12. '''
  13. ''' <param name="throwOnMissingsubKey">
  14. ''' Optional. If <see langword="True"/>, throws an exception if the registry key is not found.
  15. ''' <para></para>
  16. ''' Default value is <see langword="True"/>.
  17. ''' </param>
  18. <DebuggerStepThrough>
  19. Public Shared Sub DeleteFileTypeRegistryMenuEntry(fileType As String, keyName As String, Optional throwOnMissingsubKey As Boolean = True)
  20.  
  21.    If String.IsNullOrWhiteSpace(fileType) Then
  22.        Throw New ArgumentNullException(paramName:=NameOf(fileType))
  23.    End If
  24.  
  25.    If String.IsNullOrWhiteSpace(keyName) Then
  26.        Throw New ArgumentNullException(paramName:=NameOf(keyName))
  27.    End If
  28.  
  29.    Using rootKey As RegistryKey = Registry.ClassesRoot
  30.        rootKey.DeleteSubKeyTree($"{fileType}\shell\{keyName}", throwOnMissingsubKey)
  31.    End Using
  32.  
  33. End Sub
« Última modificación: 28 Febrero 2024, 17:18 pm por Eleкtro » En línea



Páginas: 1 ... 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 [58] 59 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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