Cinchoo – Configuration framework, part 27

Using Converters

Download source files (Require .NET 4.0 / Visual Studio 2010)

Cinchoo configuration framework takes care of converting most of the intrinsic type configuration object members from text value like string to int, string to enum etc. In cases where you have custom type members, you will have to use converters to convert the text value to object. Cinchoo support the following types of converters

  1. System.ComponentModel.TypeConverter – For more information about it, visit ‘How to: Implement a TypeConverter
  2. System.Windows.Data.IValueConverter
  3. Cinchoo.Core.IChoValueConverter – It is similar interface to IValueConverter.

TypeConverters can be specified two ways using ChoTypeConverterAttribute 

  1. At each object member level – Will take priority over second option
  2. At the object type level

Lets go over with sample configuration object defined below

[ChoNameValueConfigurationSection("appSettings")]
public class AppSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("name", DefaultValue = "Raj")]
    public string Name;

    [ChoPropertyInfo("address", DefaultValue = "21, Melbloum Lane, Edison NJ 08837")]
    public string Address;

    [ChoPropertyInfo("Color", DefaultValue = "Yellow")]
    public ConsoleColor Color;

    [ChoPropertyInfo("height", DefaultValue = "5.6")]
    public double Height;

    [ChoPropertyInfo("SSN", DefaultValue = "111-00-3333")]
    [ChoTypeConverter(typeof(SSNConverter))]
    public string SSN;

    [ChoPropertyInfo("Location", DefaultValue = "10, 12")]
    public Point Location;

    [ChoAfterConfigurationObjectLoadedHandler]
    public void AfterConfigurationObjectLoadedHandler(object sender, ChoConfigurationObjectEventArgs e)
    {
        Console.WriteLine(sender.ToString());
    }
}

In here,

  • Color is of ConsoleColor enum type. As I mentioned earlier, it is implicitly taken care by Cinchoo framework to read/store the value as string.
  • SSN is of string type, expects values in specific format (000-00-0000). It is decorated with member level type converter ‘SSNConverter’
  • Location is of Point type. But Point class bounded to PointConverter as below. No need to specify at the member level.

SSNConverter Implementation

public class SSNConverter : TypeConverter
{
    private static readonly Regex _ssnRegex = new Regex(@"^[0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9][0-9][0-9]$|^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$", RegexOptions.Compiled);
    private static readonly Regex _noSSNRegex = new Regex(@"^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$", RegexOptions.Compiled);
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value != null && value is string)
        {
            string ssnValue = value as string;
            if (_ssnRegex.IsMatch(ssnValue))
                return ssnValue;
            else if (_noSSNRegex.IsMatch(ssnValue))
                return "{0}-{1}-{2}".FormatString(ssnValue.Substring(0, 2), ssnValue.Substring(2, 4), ssnValue.Substring(4, 7));
        }
        throw new ArgumentException("Invalid '{0}' SSN value passed.".FormatString(value));
    }
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(string);
    }
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        return (string)value;
    }
}

PointConverter Implementation

[ChoTypeConverter(typeof(Point))]
public class PointConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value is string)
        {
            if (targetType == typeof(Point))
            {
                int x = 0, y = 0;
                string inValue = value as string;
                string[] parts = inValue.SplitNTrim(',');
                if (parts.Length >= 1)
                    x = System.Convert.ToInt32(parts[0]);
                if (parts.Length >= 2)
                    y = System.Convert.ToInt32(parts[1]);
                return new Point(x, y);
            }
        }
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value is Point)
        {
            if (targetType == typeof(string))
            {
                Point inValue = (Point)value;
                return "{0}, {1}".FormatString(inValue.X, inValue.Y);
            }
        }

        return value;
    }
}

You can use any existing TypeConverter / IValueConverter in your application. Try for yourself. Thanks.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s