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

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


+  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 2 Visitantes están viendo este tema.
Páginas: 1 ... 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 490,584 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.822



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #590 en: 26 Abril 2024, 18:38 pm »

Comparto una forma que he ideado para automatizar la traducción, al idioma actual de la aplicación, los valores booleanos en un propertygrid (por ejemplo), mediante el uso clases de atributos.







El modo de empleo es muy sencillo:

Código
  1. public class TestClass
  2.  
  3. <LocalizableBoolean>
  4. <TypeConverter(GetType(LocalizableBooleanConverter))>
  5. Public Property FeatureEnabled As Boolean = True
  6.  
  7. end class

Código
  1. Me.PropertyGrid1.SelectedObject = new TestClass()

También se puede utilizar de esta forma alternativa para una representación arbitraria en los idiomas que se especifiquen mediante un string separado por comas (en este ejemplo, el español y el francés):

Código
  1. <LocalizableBoolean("es, fr", "ssssí!!, Oui!", "nope!, Non!")>
  2. <TypeConverter(GetType(LocalizableBooleanConverter))>
  3. Public Property FeatureEnabled As Boolean = True





El código:

LocalizedBoolean.vb
Código
  1. ''' <summary>
  2. ''' Represents localized strings for <see langword="True"/> and <see langword="False"/> <see cref="Boolean"/> values.
  3. ''' </summary>
  4. <DebuggerStepThrough>
  5. Public NotInheritable Class LocalizedBoolean
  6.  
  7.    ''' <summary>
  8.    ''' The <see cref="CultureInfo"/> that represents the region for
  9.    ''' the localized strings in <see cref="LocalizedBoolean.True"/>
  10.    ''' and <see cref="LocalizedBoolean.False"/> properties.
  11.    ''' </summary>
  12.    Public ReadOnly Property Culture As CultureInfo
  13.  
  14.    ''' <summary>
  15.    ''' The localized string representation for <see langword="True"/> <see cref="Boolean"/> value.
  16.    ''' </summary>
  17.    Public ReadOnly Property [True] As String
  18.  
  19.    ''' <summary>
  20.    ''' The localized string representation for <see langword="False"/> <see cref="Boolean"/> value.
  21.    ''' </summary>
  22.    Public ReadOnly Property [False] As String
  23.  
  24.    ''' <summary>
  25.    ''' Initializes a new instance of the <see cref="LocalizedBoolean"/> class.
  26.    ''' </summary>
  27.    '''
  28.    ''' <param name="culture">
  29.    ''' The <see cref="CultureInfo"/> that represents the region for the localized strings.
  30.    ''' </param>
  31.    '''
  32.    ''' <param name="trueString">
  33.    ''' The localized string representation for <see langword="True"/> <see cref="Boolean"/> value.
  34.    ''' </param>
  35.    '''
  36.    ''' <param name="falseString">
  37.    ''' The localized string representation for <see langword="False"/> <see cref="Boolean"/> value.
  38.    ''' </param>
  39.    Public Sub New(culture As CultureInfo, trueString As String, falseString As String)
  40.        If culture Is Nothing Then
  41.            Throw New ArgumentNullException(paramName:=NameOf(culture))
  42.        End If
  43.        If String.IsNullOrWhiteSpace(trueString) Then
  44.            Throw New ArgumentNullException(paramName:=NameOf(trueString))
  45.        End If
  46.        If String.IsNullOrWhiteSpace(falseString) Then
  47.            Throw New ArgumentNullException(paramName:=NameOf(falseString))
  48.        End If
  49.  
  50.        Me.Culture = culture
  51.        Me.True = trueString
  52.        Me.False = falseString
  53.    End Sub
  54.  
  55.    ''' <summary>
  56.    ''' Prevents a default instance of the <see cref="LocalizedBoolean"/> class from being created.
  57.    ''' </summary>
  58.    Private Sub New()
  59.    End Sub
  60.  
  61. End Class

LocalizableBooleanAttribute.vb
Código:
''' <summary>
''' Specifies that a <see cref="Boolean"/> property can display localized string representations
''' for <see langword="True"/> and <see langword="False"/> values.
''' </summary>
<AttributeUsage(AttributeTargets.Property, AllowMultiple:=False, Inherited:=True)>
<DebuggerStepThrough>
Public NotInheritable Class LocalizableBooleanAttribute : Inherits Attribute

    ''' <summary>
    ''' Gets the localized boolean representations.
    ''' <para></para>
    ''' The dictionary Key is the ISO 639-1 two-letter code for the language.
    ''' </summary>
    Public ReadOnly Property Localizations As Dictionary(Of String, LocalizedBoolean)

    ''' <summary>
    ''' Initializes a new instance of the <see cref="LocalizedBoolean"/> class.
    ''' </summary>
    Public Sub New()
        Me.Localizations = New Dictionary(Of String, LocalizedBoolean)(StringComparison.OrdinalIgnoreCase) From {
            {"af", New LocalizedBoolean(CultureInfo.GetCultureInfo("af"), "Ja", "Nee")}, ' Afrikaans
            {"am", New LocalizedBoolean(CultureInfo.GetCultureInfo("am"), "እወዳለሁ", "አይደለሁ")}, ' Amharic
            {"ar", New LocalizedBoolean(CultureInfo.GetCultureInfo("ar"), "نعم", "لا")}, ' Arabic
            {"az", New LocalizedBoolean(CultureInfo.GetCultureInfo("az"), "Bəli", "Xeyr")}, ' Azerbaijani
            {"be", New LocalizedBoolean(CultureInfo.GetCultureInfo("be"), "Так", "Не")}, ' Belarusian
            {"bg", New LocalizedBoolean(CultureInfo.GetCultureInfo("bg"), "Да", "Не")}, ' Bulgarian
            {"bn", New LocalizedBoolean(CultureInfo.GetCultureInfo("bn"), "হ্যাঁ", "না")}, ' Bengali
            {"ca", New LocalizedBoolean(CultureInfo.GetCultureInfo("ca"), "Sí", "No")}, ' Catalan
            {"cs", New LocalizedBoolean(CultureInfo.GetCultureInfo("cs"), "Ano", "Ne")}, ' Czech
            {"cy", New LocalizedBoolean(CultureInfo.GetCultureInfo("cy"), "Ie", "Na")}, ' Welsh
            {"da", New LocalizedBoolean(CultureInfo.GetCultureInfo("da"), "Ja", "Nej")}, ' Danish
            {"de", New LocalizedBoolean(CultureInfo.GetCultureInfo("de"), "Ja", "Nein")}, ' German
            {"el", New LocalizedBoolean(CultureInfo.GetCultureInfo("el"), "Ναι", "Όχι")}, ' Greek
            {"en", New LocalizedBoolean(CultureInfo.GetCultureInfo("en"), "Yes", "No")}, ' English
            {"es", New LocalizedBoolean(CultureInfo.GetCultureInfo("es"), "Sí", "No")}, ' Spanish
            {"et", New LocalizedBoolean(CultureInfo.GetCultureInfo("et"), "Jah", "Ei")}, ' Estonian
            {"eu", New LocalizedBoolean(CultureInfo.GetCultureInfo("eu"), "Bai", "Ez")}, ' Basque
            {"fa", New LocalizedBoolean(CultureInfo.GetCultureInfo("fa"), "بله", "خیر")}, ' Persian
            {"fi", New LocalizedBoolean(CultureInfo.GetCultureInfo("fi"), "Kyllä", "Ei")}, ' Finnish
            {"fr", New LocalizedBoolean(CultureInfo.GetCultureInfo("fr"), "Oui", "Non")}, ' French
            {"ga", New LocalizedBoolean(CultureInfo.GetCultureInfo("ga"), "Tá", "Níl")}, ' Irish
            {"gd", New LocalizedBoolean(CultureInfo.GetCultureInfo("gd"), "Tha", "Chan eil")}, ' Scottish Gaelic
            {"gl", New LocalizedBoolean(CultureInfo.GetCultureInfo("gl"), "Si", "Non")}, ' Galician
            {"gu", New LocalizedBoolean(CultureInfo.GetCultureInfo("gu"), "હા", "ના")}, ' Gujarati
            {"hi", New LocalizedBoolean(CultureInfo.GetCultureInfo("hi"), "हाँ", "नहीं")}, ' Hindi
            {"hr", New LocalizedBoolean(CultureInfo.GetCultureInfo("hr"), "Da", "Ne")}, ' Croatian
            {"ht", New LocalizedBoolean(CultureInfo.GetCultureInfo("ht"), "Wi", "Pa")}, ' Haitian Creole
            {"hu", New LocalizedBoolean(CultureInfo.GetCultureInfo("hu"), "Igen", "Nem")}, ' Hungarian
            {"id", New LocalizedBoolean(CultureInfo.GetCultureInfo("id"), "Ya", "Tidak")}, ' Indonesian
            {"ig", New LocalizedBoolean(CultureInfo.GetCultureInfo("ig"), "Ee", "Mba")}, ' Igbo
            {"is", New LocalizedBoolean(CultureInfo.GetCultureInfo("is"), "Já", "Nei")}, ' Icelandic
            {"it", New LocalizedBoolean(CultureInfo.GetCultureInfo("it"), "Sì", "No")}, ' Italian
            {"ja", New LocalizedBoolean(CultureInfo.GetCultureInfo("ja"), "はい", "いいえ")}, ' Japanese
            {"jv", New LocalizedBoolean(CultureInfo.GetCultureInfo("jv"), "Iya", "Ora")}, ' Javanese
            {"kk", New LocalizedBoolean(CultureInfo.GetCultureInfo("kk"), "Иә", "Жоқ")}, ' Kazakh
            {"km", New LocalizedBoolean(CultureInfo.GetCultureInfo("km"), "បាទ/ចាស", "ទេ")}, ' Khmer
            {"kn", New LocalizedBoolean(CultureInfo.GetCultureInfo("kn"), "ಹೌದು", "ಇಲ್ಲ")}, ' Kannada
            {"ko", New LocalizedBoolean(CultureInfo.GetCultureInfo("ko"), "예", "아니오")}, ' Korean
            {"ku", New LocalizedBoolean(CultureInfo.GetCultureInfo("ku"), "Belê", "Na")}, ' Kurdish (Kurmanji)
            {"ky", New LocalizedBoolean(CultureInfo.GetCultureInfo("ky"), "Ооба", "Жок")}, ' Kyrgyz
            {"la", New LocalizedBoolean(CultureInfo.GetCultureInfo("la"), "Ita", "Non")}, ' Latin
            {"lg", New LocalizedBoolean(CultureInfo.GetCultureInfo("lg"), "Yee", "Nedda")}, ' Luganda
            {"lt", New LocalizedBoolean(CultureInfo.GetCultureInfo("lt"), "Taip", "Ne")}, ' Lithuanian
            {"lv", New LocalizedBoolean(CultureInfo.GetCultureInfo("lv"), "Jā", "Nē")}, ' Latvian
            {"mg", New LocalizedBoolean(CultureInfo.GetCultureInfo("mg"), "Eny", "Tsia")}, ' Malagasy
            {"mi", New LocalizedBoolean(CultureInfo.GetCultureInfo("mi"), "Āe", "Kāo")}, ' Maori
            {"mk", New LocalizedBoolean(CultureInfo.GetCultureInfo("mk"), "Да", "Не")}, ' Macedonian
            {"ml", New LocalizedBoolean(CultureInfo.GetCultureInfo("ml"), "അതെ", "ഇല്ല")}, ' Malayalam
            {"mn", New LocalizedBoolean(CultureInfo.GetCultureInfo("mn"), "Тийм", "Үгүй")}, ' Mongolian
            {"mr", New LocalizedBoolean(CultureInfo.GetCultureInfo("mr"), "होय", "नाही")}, ' Marathi
            {"ms", New LocalizedBoolean(CultureInfo.GetCultureInfo("ms"), "Ya", "Tidak")}, ' Malay
            {"mt", New LocalizedBoolean(CultureInfo.GetCultureInfo("mt"), "Iva", "Le")}, ' Maltese
            {"my", New LocalizedBoolean(CultureInfo.GetCultureInfo("my"), "ဟုတ်ကဲ့", "မဟုတ်ဘူး")}, ' Burmese
            {"ne", New LocalizedBoolean(CultureInfo.GetCultureInfo("ne"), "हो", "होइन")}, ' Nepali
            {"nl", New LocalizedBoolean(CultureInfo.GetCultureInfo("nl"), "Ja", "Nee")}, ' Dutch
            {"no", New LocalizedBoolean(CultureInfo.GetCultureInfo("no"), "Ja", "Nei")}, ' Norwegian
            {"ny", New LocalizedBoolean(CultureInfo.GetCultureInfo("ny"), "Yewo", "Ayawo")}, ' Chichewa
            {"pa", New LocalizedBoolean(CultureInfo.GetCultureInfo("pa"), "ਹਾਂ", "ਨਹੀਂ")}, ' Punjabi
            {"pl", New LocalizedBoolean(CultureInfo.GetCultureInfo("pl"), "Tak", "Nie")}, ' Polish
            {"ps", New LocalizedBoolean(CultureInfo.GetCultureInfo("ps"), "هو", "نه")}, ' Pashto
            {"pt", New LocalizedBoolean(CultureInfo.GetCultureInfo("pt"), "Sim", "Não")}, ' Portuguese
            {"rm", New LocalizedBoolean(CultureInfo.GetCultureInfo("rm"), "Gia", "Betg")}, ' Romansh
            {"ro", New LocalizedBoolean(CultureInfo.GetCultureInfo("ro"), "Da", "Nu")}, ' Romanian
            {"ru", New LocalizedBoolean(CultureInfo.GetCultureInfo("ru"), "Да", "Нет")}, ' Russian
            {"sd", New LocalizedBoolean(CultureInfo.GetCultureInfo("sd"), "هاڻي", "نه")}, ' Sindhi
            {"si", New LocalizedBoolean(CultureInfo.GetCultureInfo("si"), "ඔව්", "නැත")}, ' Sinhala
            {"sk", New LocalizedBoolean(CultureInfo.GetCultureInfo("sk"), "Áno", "Nie")}, ' Slovak
            {"sl", New LocalizedBoolean(CultureInfo.GetCultureInfo("sl"), "Da", "Ne")}, ' Slovenian
            {"sm", New LocalizedBoolean(CultureInfo.GetCultureInfo("sm"), "Ioe", "Leai")}, ' Samoan
            {"sn", New LocalizedBoolean(CultureInfo.GetCultureInfo("sn"), "Yebo", "Cha")}, ' Shona
            {"so", New LocalizedBoolean(CultureInfo.GetCultureInfo("so"), "Haa", "Maya")}, ' Somali
            {"sq", New LocalizedBoolean(CultureInfo.GetCultureInfo("sq"), "Po", "Jo")}, ' Albanian
            {"sr", New LocalizedBoolean(CultureInfo.GetCultureInfo("sr"), "Да", "Не")}, ' Serbian (Cyrillic)
            {"su", New LocalizedBoolean(CultureInfo.GetCultureInfo("su"), "Iya", "Teu")}, ' Sundanese
            {"sv", New LocalizedBoolean(CultureInfo.GetCultureInfo("sv"), "Ja", "Nej")}, ' Swedish
            {"sw", New LocalizedBoolean(CultureInfo.GetCultureInfo("sw"), "Ndiyo", "Hapana")}, ' Swahili
            {"ta", New LocalizedBoolean(CultureInfo.GetCultureInfo("ta"), "ஆம்", "இல்லை")}, ' Tamil
            {"te", New LocalizedBoolean(CultureInfo.GetCultureInfo("te"), "అవును", "కాదు")}, ' Telugu
            {"tg", New LocalizedBoolean(CultureInfo.GetCultureInfo("tg"), "Ҳа", "Не")}, ' Tajik
            {"th", New LocalizedBoolean(CultureInfo.GetCultureInfo("th"), "ใช่", "ไม่")}, ' Thai
            {"ti", New LocalizedBoolean(CultureInfo.GetCultureInfo("ti"), "እወ", "አይወ")}, ' Tigrinya
            {"tk", New LocalizedBoolean(CultureInfo.GetCultureInfo("tk"), "Hawa", "Ýok")}, ' Turkmen
            {"to", New LocalizedBoolean(CultureInfo.GetCultureInfo("to"), "ʻIo", "ʻEa")}, ' Tongan
            {"tr", New LocalizedBoolean(CultureInfo.GetCultureInfo("tr"), "Evet", "Hayır")}, ' Turkish
            {"tt", New LocalizedBoolean(CultureInfo.GetCultureInfo("tt"), "Әйе", "Юк")}, ' Tatar
            {"ug", New LocalizedBoolean(CultureInfo.GetCultureInfo("ug"), "ھەئە", "ياق")}, ' Uighur
            {"uk", New LocalizedBoolean(CultureInfo.GetCultureInfo("uk"), "Так", "Ні")}, ' Ukrainian
            {"ur", New LocalizedBoolean(CultureInfo.GetCultureInfo("ur"), "جی ہاں", "نہیں")}, ' Urdu
            {"uz", New LocalizedBoolean(CultureInfo.GetCultureInfo("uz"), "Ha", "Yo'q")}, ' Uzbek
            {"vi", New LocalizedBoolean(CultureInfo.GetCultureInfo("vi"), "Có", "Không")}, ' Vietnamese
            {"xh", New LocalizedBoolean(CultureInfo.GetCultureInfo("xh"), "Ewe", "Hayi")}, ' Xhosa
            {"yi", New LocalizedBoolean(CultureInfo.GetCultureInfo("yi"), "יאָ", "ניי")}, ' Yiddish
            {"yo", New LocalizedBoolean(CultureInfo.GetCultureInfo("yo"), "Bẹẹni", "Bẹẹkoo")}, ' Yoruba
            {"zh", New LocalizedBoolean(CultureInfo.GetCultureInfo("zh"), "是", "不")}, ' Chinese (Simplified)
            {"zu", New LocalizedBoolean(CultureInfo.GetCultureInfo("zu"), "Yebo", "Cha")} ' Zulu
        }
    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="LocalizedBoolean"/> class.
    ''' </summary>
    '''
    ''' <param name="cultureNames">
    ''' A comma-separated value of the ISO 639-1 two-letter code languages (e.g.: "en,es,fr").
    ''' </param>
    '''
    ''' <param name="trueStrings">
    ''' A comma-separated value of the localized string representation for "True" boolean value (e.g.: "Yes,Sí,Oui").
    ''' </param>
    '''
    ''' <param name="falseStrings">
    ''' A comma-separated value of the localized string representation for "False" boolean value (e.g.: "No,No,Non").
    ''' </param>
    Public Sub New(cultureNames As String, trueStrings As String, falseStrings As String)
        Me.New()

        If String.IsNullOrWhiteSpace(cultureNames) Then
            Throw New ArgumentNullException(paramName:=NameOf(cultureNames))
        End If
        If String.IsNullOrWhiteSpace(trueStrings) Then
            Throw New ArgumentNullException(paramName:=NameOf(trueStrings))
        End If
        If String.IsNullOrWhiteSpace(falseStrings) Then
            Throw New ArgumentNullException(paramName:=NameOf(falseStrings))
        End If

        Dim cultureNamesArray As String() = cultureNames.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
        Dim trueStringsArray As String() = trueStrings.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
        Dim falseStringsArray As String() = falseStrings.Split({","c}, StringSplitOptions.RemoveEmptyEntries)

        If cultureNamesArray.Length <> trueStringsArray.Length OrElse cultureNamesArray.Length <> falseStringsArray.Length Then
            Throw New InvalidOperationException("The comma-separated values must have the same amount of tokens.")
        End If

        For i As Integer = 0 To cultureNamesArray.Length - 1
            Dim cultureName As String = cultureNamesArray(i).Trim()
            Dim trueString As String = trueStringsArray(i).Trim()
            Dim falseString As String = falseStringsArray(i).Trim()

            If cultureName.Length <> 2 Then
                Throw New InvalidOperationException("The culture name must be a ISO 639-1 two-letter code.")
            End If

            Dim localizedBoolean As New LocalizedBoolean(CultureInfo.GetCultureInfo(cultureName), trueString, falseString)
            If Me.Localizations.ContainsKey(cultureName) Then
                Me.Localizations(cultureName) = localizedBoolean
            Else
                Me.Localizations.Add(cultureName, localizedBoolean)
            End If
        Next
    End Sub

End Class

LocalizableBooleanConverter.vb
Código
  1. ''' <summary>
  2. ''' Provides conversion functionality between Boolean values and localized strings representing "True" and "False" boolean values.
  3. ''' </summary>
  4. Public Class LocalizableBooleanConverter : Inherits TypeConverter
  5.  
  6.    ''' <summary>
  7.    ''' The localized string representation for "True" boolean value.
  8.    ''' </summary>
  9.    Private trueString As String = "Yes"
  10.  
  11.    ''' <summary>
  12.    ''' The localized string representation for "False" boolean value.
  13.    ''' </summary>
  14.    Private falseString As String = "No"
  15.  
  16.    ''' <summary>
  17.    ''' Returns whether this converter can convert an object of the given type to the type of this converter,
  18.    ''' using the specified context.
  19.    ''' </summary>
  20.    '''
  21.    ''' <param name="context">
  22.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  23.    ''' </param>
  24.    '''
  25.    ''' <param name="sourceType">
  26.    ''' A <see cref="Type" /> that represents the type you want to convert from.
  27.    ''' </param>
  28.    '''
  29.    ''' <returns>
  30.    ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  31.    ''' </returns>
  32.    Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
  33.  
  34.        Return sourceType = GetType(String) OrElse MyBase.CanConvertFrom(context, sourceType)
  35.  
  36.    End Function
  37.  
  38.    ''' <summary>
  39.    ''' Returns whether this converter can convert the object to the specified type, using the specified context.
  40.    ''' </summary>
  41.    '''
  42.    ''' <param name="context">
  43.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  44.    ''' </param>
  45.    '''
  46.    ''' <param name="destinationType">
  47.    ''' A <see cref="Type"/> that represents the type you want to convert to.
  48.    ''' </param>
  49.    '''
  50.    ''' <returns>
  51.    ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  52.    ''' </returns>
  53.    Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
  54.  
  55.        Return destinationType = GetType(String) OrElse MyBase.CanConvertTo(context, destinationType)
  56.  
  57.    End Function
  58.  
  59.    ''' <summary>
  60.    ''' Converts the given object to the type of this converter, using the specified context and culture information.
  61.    ''' </summary>
  62.    '''
  63.    ''' <param name="context">
  64.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  65.    ''' </param>
  66.    '''
  67.    ''' <param name="culture">
  68.    ''' The <see cref="CultureInfo"/> to use as the current culture.
  69.    ''' </param>
  70.    '''
  71.    ''' <param name="value">
  72.    ''' The <see cref="Object"/> to convert.
  73.    ''' </param>
  74.    '''
  75.    ''' <returns>
  76.    ''' An <see cref="Object"/> that represents the converted value.
  77.    ''' </returns>
  78.    <DebuggerStepperBoundary>
  79.    Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As Globalization.CultureInfo, value As Object) As Object
  80.  
  81.        If TypeOf value Is String Then
  82.            Dim stringValue As String = DirectCast(value, String)
  83.            If String.Equals(stringValue, Me.trueString, StringComparison.OrdinalIgnoreCase) Then
  84.                Return True
  85.            ElseIf String.Equals(stringValue, Me.FalseString, StringComparison.OrdinalIgnoreCase) Then
  86.                Return False
  87.            End If
  88.        End If
  89.  
  90.        Return MyBase.ConvertFrom(context, culture, value)
  91.  
  92.    End Function
  93.  
  94.    ''' <summary>
  95.    ''' Converts the given value object to the specified type, using the specified context and culture information.
  96.    ''' </summary>
  97.    '''
  98.    ''' <param name="context">
  99.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  100.    ''' </param>
  101.    '''
  102.    ''' <param name="culture">
  103.    ''' A <see cref="CultureInfo"/>. If null is passed, the current culture is assumed.
  104.    ''' </param>
  105.    '''
  106.    ''' <param name="value">
  107.    ''' The <see cref="Object"/> to convert.
  108.    ''' </param>
  109.    '''
  110.    ''' <param name="destinationType">
  111.    ''' The <see cref="Type"/> to convert the <paramref name="value"/> parameter to.
  112.    ''' </param>
  113.    '''
  114.    ''' <returns>
  115.    ''' An <see cref="Object"/> that represents the converted value.
  116.    ''' </returns>
  117.    <DebuggerStepperBoundary>
  118.    Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As Globalization.CultureInfo, value As Object, destinationType As Type) As Object
  119.  
  120.        If context IsNot Nothing Then
  121.            Dim attributes As IEnumerable(Of LocalizableBooleanAttribute) =
  122.                context.PropertyDescriptor.Attributes.OfType(Of LocalizableBooleanAttribute)
  123.  
  124.            For Each attr As LocalizableBooleanAttribute In attributes
  125.                Dim uiCulture As CultureInfo = My.Application.UICulture
  126.                Dim localizedBoolean As LocalizedBoolean = Nothing
  127.                If attr.Localizations.ContainsKey(uiCulture.TwoLetterISOLanguageName) Then
  128.                    localizedBoolean = attr.Localizations(uiCulture.TwoLetterISOLanguageName)
  129.                End If
  130.  
  131.                If localizedBoolean IsNot Nothing Then
  132.                    Me.trueString = localizedBoolean.True
  133.                    Me.falseString = localizedBoolean.False
  134.                End If
  135.            Next
  136.        End If
  137.  
  138.        If destinationType = GetType(String) Then
  139.            If TypeOf value Is Boolean Then
  140.                Dim boolValue As Boolean = value
  141.                Return If(boolValue, Me.trueString, Me.falseString)
  142.            End If
  143.        End If
  144.  
  145.        Return MyBase.ConvertTo(context, culture, value, destinationType)
  146.  
  147.    End Function
  148.  
  149.    ''' <summary>
  150.    ''' Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.
  151.    ''' </summary>
  152.    '''
  153.    ''' <param name="context">
  154.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context that can be used to
  155.    ''' extract additional information about the environment from which this converter is invoked.
  156.    ''' <para></para>
  157.    ''' This parameter or properties of this parameter can be null.
  158.    ''' </param>
  159.    '''
  160.    ''' <returns>
  161.    ''' A <see cref="StandardValuesCollection"/> that holds a standard set of valid values,
  162.    ''' or <see langword="null" /> if the data type does not support a standard set of values.
  163.    ''' </returns>
  164.    Public Overrides Function GetStandardValues(context As ITypeDescriptorContext) As StandardValuesCollection
  165.  
  166.        Return New StandardValuesCollection(New Boolean() {True, False})
  167.  
  168.    End Function
  169.  
  170.    ''' <summary>
  171.    ''' Returns whether this object supports a standard set of values that can be picked from a list, using the specified context.
  172.    ''' </summary>
  173.    '''
  174.    ''' <param name="context">
  175.    ''' An <see cref="ITypeDescriptorContext" /> that provides a format context.
  176.    ''' </param>
  177.    '''
  178.    ''' <returns>
  179.    ''' <see langword="True"/> if <see cref="TypeConverter.GetStandardValues"/> should be called to
  180.    ''' find a common set of values the object supports; otherwise, <see langword="False"/>.
  181.    ''' </returns>
  182.    Public Overrides Function GetStandardValuesSupported(context As ITypeDescriptorContext) As Boolean
  183.  
  184.        Return True
  185.  
  186.    End Function
  187.  
  188. End Class

NOTA: El diccionario con los idiomas y sus equivalentes para "Sí" y "No", lo ha generado ChatGPT. Puede haber fallos en las traducciones, o en los códigos ISO 639-1 de dos letras. Además, faltaría añadir muchos más idiomas: https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes


« Última modificación: 26 Abril 2024, 21:30 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.822



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #591 en: 27 Abril 2024, 01:20 am »

Comparto otro type converter, para convertir los nombres de los valores de una Enum, a una representación amistosa para mostrarlos, por ejemplo, en un propertygrid.

Este convertidor está optimizado para nombres de enumeración escritos en upper/lower snake case y upper/lower camel case.

Las palabras se separan con un espacio en blanco convencional, y los guiones bajos se reemplazan por un espacio en blanco unicode.

Ejemplo de uso:

Código
  1. <TypeConverter(GetType(EnumNameFormatterConverter))>
  2. Public Enum TestEnum
  3.    MyUpperCamelCaseName
  4.    myLowerCamelCaseName
  5.    My_Upper_Snake_Case_Name
  6.    my_lower_snake_case_name
  7.  
  8.    MyMixed_value123_WTF456wtf_
  9.  
  10.    ___rare_case_STRANGE_Name___________123_aZ_Az_4_5_6_
  11. End Enum

Código
  1. <DefaultValue(TestEnum.MyUpperCamelCaseName)>
  2. Public Property Test As TestEnum = TestEnum.MyUpperCamelCaseName

Sin formato:


Con formato:




El código:

EnumNameFormatterConverter.vb
Código
  1. Imports System.ComponentModel
  2. Imports System.Globalization
  3. Imports System.Runtime.InteropServices
  4. Imports System.Text
  5.  
  6. ''' <summary>
  7. ''' Provides conversion functionality between the value names of an <see cref="[Enum]"/> to a friendly string representation.
  8. ''' <para></para>
  9. ''' This converter is optimized for enum names written in either upper/lower snake case or upper/lower camel case:
  10. ''' <list type="bullet">
  11. '''     <item><description>Snake case: Each word is separated by underscores (e.g.: "My_Value").</description></item>
  12. '''     <item><description>Camel case: Each word is separated by a capitalized letter (e.g.: "MyValue").</description></item>
  13. ''' </list>
  14. ''' </summary>
  15. Public NotInheritable Class EnumNameFormatterConverter : Inherits EnumConverter
  16.  
  17.    ''' <summary>
  18.    ''' Initializes a new instance of the <see cref="EnumNameFormatterConverter"/> class.
  19.    ''' </summary>
  20.    ''' <param name="type">A <see cref="T:System.Type" /> that represents the type of enumeration to associate with this enumeration converter.</param>
  21.    Public Sub New(type As Type)
  22.        MyBase.New(type)
  23.    End Sub
  24.  
  25.    ''' <summary>
  26.    ''' Returns whether this converter can convert an object of the given type to the type of this converter,
  27.    ''' using the specified context.
  28.    ''' </summary>
  29.    '''
  30.    ''' <param name="context">
  31.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  32.    ''' </param>
  33.    '''
  34.    ''' <param name="sourceType">
  35.    ''' A <see cref="Type" /> that represents the type you want to convert from.
  36.    ''' </param>
  37.    '''
  38.    ''' <returns>
  39.    ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  40.    ''' </returns>
  41.    Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
  42.  
  43.        Return sourceType Is GetType(String) OrElse
  44.               MyBase.CanConvertFrom(context, sourceType)
  45.  
  46.    End Function
  47.  
  48.    ''' <summary>
  49.    ''' Returns whether this converter can convert the object to the specified type, using the specified context.
  50.    ''' </summary>
  51.    '''
  52.    ''' <param name="context">
  53.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  54.    ''' </param>
  55.    '''
  56.    ''' <param name="destinationType">
  57.    ''' A <see cref="Type"/> that represents the type you want to convert to.
  58.    ''' </param>
  59.    '''
  60.    ''' <returns>
  61.    ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  62.    ''' </returns>
  63.    Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
  64.  
  65.        Return destinationType Is GetType(String) OrElse
  66.               MyBase.CanConvertTo(context, destinationType)
  67.  
  68.    End Function
  69.  
  70.    ''' <summary>
  71.    ''' Converts the given object to the type of this converter, using the specified context and culture information.
  72.    ''' </summary>
  73.    '''
  74.    ''' <param name="context">
  75.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  76.    ''' </param>
  77.    '''
  78.    ''' <param name="culture">
  79.    ''' The <see cref="CultureInfo"/> to use as the current culture.
  80.    ''' </param>
  81.    '''
  82.    ''' <param name="value">
  83.    ''' The <see cref="Object"/> to convert.
  84.    ''' </param>
  85.    '''
  86.    ''' <returns>
  87.    ''' An <see cref="Object"/> that represents the converted value.
  88.    ''' </returns>
  89.    <DebuggerStepThrough>
  90.    Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object
  91.  
  92.        If TypeOf value Is String Then
  93.            value = DirectCast(value, String).Replace(" ", "").Replace(Convert.ToChar(&H205F), "_"c)
  94.            Return [Enum].Parse(Me.EnumType, value, ignoreCase:=True)
  95.        End If
  96.  
  97.        Return MyBase.ConvertFrom(context, culture, value)
  98.  
  99.    End Function
  100.  
  101.    ''' <summary>
  102.    ''' Converts the given value object to the specified type, using the specified context and culture information.
  103.    ''' </summary>
  104.    '''
  105.    ''' <param name="context">
  106.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  107.    ''' </param>
  108.    '''
  109.    ''' <param name="culture">
  110.    ''' A <see cref="CultureInfo"/>. If null is passed, the current culture is assumed.
  111.    ''' </param>
  112.    '''
  113.    ''' <param name="value">
  114.    ''' The <see cref="Object"/> to convert.
  115.    ''' </param>
  116.    '''
  117.    ''' <param name="destinationType">
  118.    ''' The <see cref="Type"/> to convert the <paramref name="value"/> parameter to.
  119.    ''' </param>
  120.    '''
  121.    ''' <returns>
  122.    ''' An <see cref="Object"/> that represents the converted value.
  123.    ''' </returns>
  124.    <DebuggerStepThrough>
  125.    Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object
  126.  
  127.        If destinationType = GetType(String) Then
  128.            Dim name As String = [Enum].GetName(value.GetType(), value)
  129.            If Not String.IsNullOrEmpty(name) Then
  130.                Return Me.FormatName(name)
  131.            End If
  132.        End If
  133.  
  134.        Return MyBase.ConvertTo(context, culture, value, destinationType)
  135.  
  136.    End Function
  137.  
  138.    ''' <summary>
  139.    ''' Formats the name of a <see cref="[Enum]"/> value to a friendly name.
  140.    ''' </summary>
  141.    '''
  142.    ''' <param name="name">
  143.    ''' <see cref="[Enum]"/> value name.
  144.    ''' </param>
  145.    '''
  146.    ''' <returns>
  147.    ''' The resulting friendly name.
  148.    ''' </returns>
  149.    <DebuggerStepThrough>
  150.    Private Function FormatName(name As String) As String
  151.        Dim sb As New StringBuilder()
  152.        Dim previousChar As Char
  153.        Dim previousCharIsWhiteSpace As Boolean
  154.        Dim previousCharIsUpperLetter As Boolean
  155.        Dim previousCharIsDigit As Boolean
  156.        Dim lastParsedCharIsUnderscore As Boolean
  157.        Dim firstCapitalizedLetterIsAdded As Boolean
  158.  
  159.        For i As Integer = 0 To name.Length - 1
  160.            Dim c As Char = name(i)
  161.            If i = 0 Then
  162.                If c.Equals("_"c) Then
  163.                    sb.Append(Convert.ToChar(Convert.ToChar(&H205F)))
  164.                    lastParsedCharIsUnderscore = True
  165.                Else
  166.                    sb.Append(Char.ToUpper(c))
  167.                    firstCapitalizedLetterIsAdded = True
  168.                End If
  169.                Continue For
  170.            End If
  171.  
  172.            previousChar = sb.Chars(sb.Length - 1)
  173.            previousCharIsWhiteSpace = previousChar.Equals(" "c) OrElse previousChar.Equals(Convert.ToChar(&H205F))
  174.            previousCharIsUpperLetter = Char.IsUpper(previousChar)
  175.            previousCharIsDigit = Char.IsDigit(previousChar)
  176.  
  177.            If Char.IsLetter(c) Then
  178.                If previousCharIsDigit AndAlso Not previousCharIsWhiteSpace Then
  179.                    sb.Append(" "c)
  180.                End If
  181.  
  182.                If Char.IsUpper(c) Then
  183.                    If previousCharIsUpperLetter Then
  184.                        sb.Append(c)
  185.                    ElseIf Not previousCharIsWhiteSpace Then
  186.                        sb.Append(" "c)
  187.                        sb.Append(c)
  188.                    Else
  189.                        sb.Append(c)
  190.                    End If
  191.                    firstCapitalizedLetterIsAdded = True
  192.  
  193.                Else
  194.                    If Not firstCapitalizedLetterIsAdded Then
  195.                        sb.Append(Char.ToUpper(c))
  196.                        firstCapitalizedLetterIsAdded = True
  197.                    Else
  198.                        sb.Append(c)
  199.                    End If
  200.  
  201.                End If
  202.  
  203.            ElseIf Char.IsDigit(c) Then
  204.                If Not previousCharIsDigit AndAlso Not previousCharIsWhiteSpace Then
  205.                    sb.Append(" "c)
  206.                End If
  207.                sb.Append(c)
  208.  
  209.            ElseIf c.Equals("_"c) Then
  210.                If lastParsedCharIsUnderscore OrElse Not previousCharIsWhiteSpace Then
  211.                    sb.Append(Convert.ToChar(&H205F)) ' Unicode white-space: "&#8195;"
  212.                    lastParsedCharIsUnderscore = True
  213.                End If
  214.  
  215.            Else
  216.                sb.Append(c)
  217.                lastParsedCharIsUnderscore = False
  218.  
  219.            End If
  220.  
  221.        Next i
  222.  
  223.        Return sb.ToString()
  224.    End Function
  225.  
  226. End Class
  227.  


« Última modificación: 27 Abril 2024, 03:05 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.822



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #592 en: 27 Abril 2024, 03:03 am »

Comparto un enfoque y uso alternativo al código que he publicado arriba. Este enfoque nos permite atribuir nombres específicos a una enumeración para mostrarlos en un property grid.

Modo de empleo:

Código
  1. Imports System.Componentmodel
  2.  
  3. <TypeConverter(GetType(EnumDescriptionConverter))>
  4. Public Enum TestEnum
  5.    <Description("My Upper Camel Case Name")> MyUpperCamelCaseName = 1
  6.    <Description("My Lower Camel Case Name")> myLowerCamelCaseName = 2
  7.    <Description("My Upper Snake Case Name")> My_Upper_Snake_Case_Name = 3
  8.    <Description("My lower snake case Name")> my_lower_snake_case_Name = 4
  9.    <Description("My Mixed value 123 QWERTY 456 wtf_")> MyMixed_value123_QWERTY456wtf_ = 5
  10.    <Description("Rare case STRANGE Name 123 aZ Az 456")> ___rare_case_STRANGE_Name___________123_aZ_Az_4_5_6_ = 6
  11. End Enum

Código
  1. <DefaultValue(TestEnum.MyUpperCamelCaseName)>
  2. Public Property Test As TestEnum = TestEnum.MyUpperCamelCaseName

El código:

Código
  1. Imports System.ComponentModel
  2. Imports System.Globalization
  3. Imports System.Reflection
  4.  
  5. Public NotInheritable Class EnumDescriptionConverter : Inherits EnumConverter
  6.  
  7. ''' <summary>
  8. ''' Initializes a new instance of the <see cref="EnumDescriptionConverter"/> class.
  9. ''' </summary>
  10. ''' <param name="type">A <see cref="T:System.Type" /> that represents the type of enumeration to associate with this enumeration converter.</param>
  11. Public Sub New(type As Type)
  12. MyBase.New(type)
  13. End Sub
  14.  
  15. ''' <summary>
  16. ''' Returns whether this converter can convert the object to the specified type, using the specified context.
  17. ''' </summary>
  18. '''
  19. ''' <param name="context">
  20. ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  21. ''' </param>
  22. '''
  23. ''' <param name="destinationType">
  24. ''' A <see cref="Type"/> that represents the type you want to convert to.
  25. ''' </param>
  26. '''
  27. ''' <returns>
  28. ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  29. ''' </returns>
  30. Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
  31.  
  32. Return destinationType Is GetType(String) OrElse
  33.   MyBase.CanConvertTo(context, destinationType)
  34.  
  35. End Function
  36.  
  37. ''' <summary>
  38. ''' Returns whether this converter can convert an object of the given type to the type of this converter,
  39. ''' using the specified context.
  40. ''' </summary>
  41. '''
  42. ''' <param name="context">
  43. ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  44. ''' </param>
  45. '''
  46. ''' <param name="sourceType">
  47. ''' A <see cref="Type" /> that represents the type you want to convert from.
  48. ''' </param>
  49. '''
  50. ''' <returns>
  51. ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  52. ''' </returns>
  53. Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
  54.  
  55. Return sourceType Is GetType(String) OrElse
  56.   MyBase.CanConvertFrom(context, sourceType)
  57.  
  58. End Function
  59.  
  60. ''' <summary>
  61. ''' Converts the given value object to the specified type, using the specified context and culture information.
  62. ''' </summary>
  63. '''
  64. ''' <param name="context">
  65. ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  66. ''' </param>
  67. '''
  68. ''' <param name="culture">
  69. ''' A <see cref="CultureInfo"/>. If null is passed, the current culture is assumed.
  70. ''' </param>
  71. '''
  72. ''' <param name="value">
  73. ''' The <see cref="Object"/> to convert.
  74. ''' </param>
  75. '''
  76. ''' <param name="destinationType">
  77. ''' The <see cref="Type"/> to convert the <paramref name="value"/> parameter to.
  78. ''' </param>
  79. '''
  80. ''' <returns>
  81. ''' An <see cref="Object"/> that represents the converted value.
  82. ''' </returns>
  83. <DebuggerStepThrough>
  84. Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object
  85.  
  86. Dim fi As FieldInfo = Me.EnumType.GetField([Enum].GetName(Me.EnumType, value))
  87. Dim dna As DescriptionAttribute = CType(Attribute.GetCustomAttribute(fi, GetType(DescriptionAttribute)), DescriptionAttribute)
  88. Return If(dna IsNot Nothing, dna.Description, value.ToString())
  89.  
  90. End Function
  91.  
  92. ''' <summary>
  93. ''' Converts the given object to the type of this converter, using the specified context and culture information.
  94. ''' </summary>
  95. '''
  96. ''' <param name="context">
  97. ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  98. ''' </param>
  99. '''
  100. ''' <param name="culture">
  101. ''' The <see cref="CultureInfo"/> to use as the current culture.
  102. ''' </param>
  103. '''
  104. ''' <param name="value">
  105. ''' The <see cref="Object"/> to convert.
  106. ''' </param>
  107. '''
  108. ''' <returns>
  109. ''' An <see cref="Object"/> that represents the converted value.
  110. ''' </returns>
  111. <DebuggerStepThrough>
  112. Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object
  113.  
  114. For Each fi As FieldInfo In Me.EnumType.GetFields()
  115. Dim dna As DescriptionAttribute = CType(Attribute.GetCustomAttribute(fi, GetType(DescriptionAttribute)), DescriptionAttribute)
  116. If (dna IsNot Nothing) AndAlso DirectCast(value, String) = dna.Description Then
  117. Return [Enum].Parse(Me.EnumType, fi.Name, ignoreCase:=False)
  118. End If
  119. Next fi
  120.  
  121. Return [Enum].Parse(Me.EnumType, DirectCast(value, String))
  122.  
  123. End Function
  124.  
  125. End Class
  126.  
« Última modificación: 27 Abril 2024, 03:05 am por Eleкtro » En línea

Páginas: 1 ... 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