Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ByteSizeTypeConverter issue #74

Open
jvmlet opened this issue Oct 11, 2023 · 2 comments
Open

ByteSizeTypeConverter issue #74

jvmlet opened this issue Oct 11, 2023 · 2 comments

Comments

@jvmlet
Copy link

jvmlet commented Oct 11, 2023

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
Copy link

loudenvier commented Nov 1, 2023

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
Copy link
Author

jvmlet commented Nov 1, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants