Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse appsetting value from string to array of strings

In app.config I have custom section with custom element.

<BOBConfigurationGroup>
    <BOBConfigurationSection>
        <emails test="[email protected], [email protected]"></emails>
    </BOBConfigurationSection>
</BOBConfigurationGroup>

For emails element I have custom type :

public class EmailAddressConfigurationElement : ConfigurationElement, IEmailConfigurationElement
{
    [ConfigurationProperty("test")]
    public string[] Test
    {
        get { return base["test"].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); }
        set { base["test"] = value.JoinStrings(); }
    }
}

But when I run my webApp, I get error :

The value of the property 'test' cannot be parsed. The error is: Unable to find a converter that supports conversion to/from string for the property 'test' of type 'String[]'.

Is there any solution to split string in getter?

I can get string value and then split it "manually" when I need array, but in some cases I can forget about it, so better to receive array from start.


JoinStrings - is my custom extension method

 public static string JoinStrings(this IEnumerable<string> strings, string separator = ", ")
 {
     return string.Join(separator, strings.Where(s => !string.IsNullOrEmpty(s)));
 }
like image 344
demo Avatar asked Sep 01 '17 11:09

demo


1 Answers

You can add a TypeConverter to convert between string and string[]:

[TypeConverter(typeof(StringArrayConverter))]
[ConfigurationProperty("test")]
public string[] Test
{
    get { return (string[])base["test"]; }
    set { base["test"] = value; }
}


public class StringArrayConverter: TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string[]);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        return ((string)value).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(string);
    }
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        return value.JoinStrings();
    }
}
like image 121
Ofir Winegarten Avatar answered Oct 14 '22 09:10

Ofir Winegarten