omar / ByteSize

ByteSize is a utility class that makes byte size representation in code easier by removing ambiguity of the value being represented. ByteSize is to bytes what System.TimeSpan is to time.
MIT License
558 stars 50 forks source link

ByteSizeTypeConverter issue #74

Open jvmlet opened 1 year ago

jvmlet commented 1 year ago

We are using ConfigurationBinder to populate the value from the configuration section, but looks like the converter is not picked up (probably because it's defined as internal) :

image

Next call converter.CanConvertFrom(typeof(string)) returns false and the converter is not invoked.

Snippet from ConfigurationBinder :

 TypeConverter converter = TypeDescriptor.GetConverter(type);
     if (converter.CanConvertFrom(typeof(string))) {
 ...
       }

Please make the ByteSizeTypeConverter as public .

Building with sdk 7.0, targeting 6.0

loudenvier commented 11 months ago

I was not even aware that there was already a type converter in ByteSize. I'm getting command line arguments with a command line parsing library which needs type converters to work and I just created my own as bellow:

public class ByteSizeTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) =>
        sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);

    public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) =>
        value is string s ? ByteSize.Parse(s) : base.ConvertFrom(context, culture, value);

    public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) =>
        value is ByteSize ? value.ToString() : base.ConvertTo(context, culture, value, destinationType);
}

Then all I needed to do was to "add" it to the "mix":

// Need to add our ByteSize TypeConverter
TypeDescriptor.AddAttributes(typeof(ByteSize), new TypeConverterAttribute(typeof(ByteSizeTypeConverter)));

You only need to call it once, probably at your app's startup code.

jvmlet commented 11 months ago

Yes, we did the same, copy-pasted the internal converter code to our code base and hooked it with AddAttribute. Works, but smells.....