Showing posts with label Attribute. Show all posts
Showing posts with label Attribute. Show all posts

Tuesday, May 10, 2011

Injecting XML Serialization for formatting decimal properties

When serializing objects that contain properties with type of decimal, the .NET XmlSerializer writes them to the resulting XML file exactly as they are specified in your program code. That means that if you assign a value of 5 then you will get the following XML from the serializer:

<Price>5</Price>

If you instead assign 5.00 you will receive the following output:

<Price>5.00</Price>

In this behavior the decimal type is different to all other numeric value types (e.g. double). For those of you who are interested at details you may have a look at comnumber.cpp which is the underlying Win32 API file used for formatting numbers. But that’s not the focus of this blog entry. I will just show one possibility to inject some additional behavior in order to format all the decimal properties you want formatted. This solution takes into account that you already have some code and objects you need to serialize and therefore tries to make as little changes to existing code as possible.

You can either tell the serializer to format all decimal properties it finds on an object or you may give it the chance to decide itself which properties to format and which not. The first approach requires no changes within your objects and is a lot easier. But if you want only certain properties to be formatted you must mark these properties accordingly. In order to do this we firstly define a custom attribute like follows:

[AttributeUsage(AttributeTargets.Property)]
public class DecimalFormatterAttribute : Attribute
{
    public DecimalFormatterAttribute(string formatString)
    {
        Format = formatString;
    }

    public string Format { get; private set; }
}

The attribute simply gets a user defined format string that will later be used to format the decimal value of the decorated property. With the AttributeUsage attribute we tell the compiler that our attribute is only valid on properties. With that attribute set up you can no go and decorate all the properties you want to be formatted by the serializer:

[DecimalFormatter("0.00")]
public decimal Price { get; set; }

To write out simple value types the XmlSerializer uses as type of XmlSerializationPrimitiveWriter. It would be the easiest way to extend this writer and use your own class for formatting. But due to its protection level you can’t do this. So the only thing one can do is to set the value of a given decimal property according to the format string specified within our custom property before serializing the object. That means that before we call XmlSerializer.Serialize(…) we need to format our decimal properties. There are a number of ways in which you can achieve this. I will present two of them here. Both solutions don’t require great code changes.

1. Custom serialization class

In a custom class you specify a Serialize and a Deserialize method. Both methods route their calls to an internal field of type XmlSerializer. In the Serialize method additional logic is executed before the call to XmlSerializer.Serialize:

public void Serialize(Stream stream, object o)
{
    var type = o.GetType();
    //get all public properties of o
    var properties = type.GetProperties();
    if (properties.Length > 0)
    {
        foreach (var propertyInfo in properties)
        {
            //apply only to properties of type decimal
            if (propertyInfo.PropertyType.Equals(typeof (decimal)))
            {
                //try to get DecimalFormatterAttribute attribute
                object[] formatterAttribute =
                    propertyInfo.GetCustomAttributes(
                                             typeof (DecimalFormatterAttribute), false);

                if (formatterAttribute.Length == 1)
                {
                    string format =
((DecimalFormatterAttribute)
formatterAttribute[0]).Format;
                    var value = (decimal) propertyInfo.GetValue(o, null);
                    var formattedString = value.ToString(
format, NumberFormatInfo.CurrentInfo); 

                    propertyInfo.SetValue(o,
decimal.Parse(formattedString), null);
                }
            }
        }
    }
    serializer.Serialize(stream, o);
} 

The method uses reflection to get all properties of the given object. If you don’t specify any BindingFlags value in the call to Type.GetProperties then all public properties will be retrieved by default. For each property – if it is of type decimal – we try to get our custom attribute and if we find it we apply it to the ToString method of the property value. Afterwards we set the property value by parsing the generated string. Of course this is kind of a little trick but I think it’s acceptable here. When we are finished formatting all decimal properties we simply need to call the Serialize method of the XmlSerializer.
The disadvantage of this solution is that you need to change all existing calls to XmlSerializer.Serialze you may already have in your application in that way that you must use a different class.

2. Use an extension method for XmlSerializer

If you don’t want a separate class encapsulating an XmlSerializer then you can use an extension method: 

public static class XmlSerializerExtension
{
    public static void SerializeDecimal(
this XmlSerializer serializer, Stream stream, object o)
    {
       …  
    }
} 

The method implementation is the same as above. Unfortunately you cannot name the extension method Serialize because the XmlSerializer class already contains that method. So slightly rename your method and you are able to use it instead of XmlSerializer.Serialize:

var s = new XmlSerializer(typeof (Product));
s.SerializeDecimal(stream, p);
 
Again you need to change at least the method call within your existing code. It’s purely a matter of taste which of the presented methods to choose.

Thursday, November 4, 2010

Binding Enum values to WPF Item Collection Controls

There are several ways to bind an enumeration to an item collection control (like Listbox or Combobox) in WPF. Because we’re using XAML I will show you the declarative way. Let’s assume we have an enumeration that represents different ways of transmission:

public enum Transmission
{       
    None = 0,       
    Phone = 2,
    Mail = 4,
    Letter = 8,
    Chat = 16
}

This enumeration needs to be bound to a combo box in our WPF window. So the easiest way is to use an ObjectDataProvider which returns an array of the enum values. In XAML that would look like the following code snippet:

<ObjectDataProvider
    MethodName="GetValues"
    ObjectType="{x:Type System:Enum}"
    x:Key="TransmissionTypeEnum">
  <ObjectDataProvider.MethodParameters>
    <x:Type TypeName="App:Transmission"></x:Type>
  </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

We define an ObjectDataProvider and tell it to use the GetValues method on the Enum object. Enum provides this static method which takes the type argument that represents the current enum type. So we add a method parameter and give it the type of our transmission enumeration. After defining the provider, you can use it right away as a binding source for an item collection control like so:

<ComboBox ItemsSource="{Binding Source={StaticResource TransmissionTypeEnum}}"

That’s it. Now, the combo box should display the values of the enum.
But what do we do, if we want to display user friendly text instead of the possibly technical enum definitions? Again, there are several ways to achieve this. The only thing you always need is a place to store the description for each enum field. Here we use the DescriptionAttribute class that is defined in the System.ComponentModel namespace. It allows us, to write the description right above each field:

public enum Transmission
{
    [DescriptionAttribute("None")]
    None = 0,

    [DescriptionAttribute("Telephone")]
    Phone = 2,

    [DescriptionAttribute("E-Mail Attachment")]
    Mail = 4,

    [DescriptionAttribute("Letter")]
    Letter = 8,

    [DescriptionAttribute("Chat (Text, Voice or Video)")]
    Chat = 16
}

Now we need a component to read out the descriptions and provide some kind of item source to bind to our combo box. Let’s create a static class that contains a method which gets the enum type and returns a Dictionary with the description for each field in the enumeration:

public static IDictionary<string, object> GetDict(Type enumType)
{
    var typeList = new Dictionary<string, object>();

    //get the description attribute of each enum field
    DescriptionAttribute descriptionAttribute;
    foreach (var value in Enum.GetValues(enumType))
    {
        FieldInfo fieldInfo = enumType.GetField((value.ToString()));
        descriptionAttribute =
(DescriptionAttribute)Attribute.GetCustomAttribute(fieldInfo,
typeof(DescriptionAttribute));
        if (descriptionAttribute != null)
        {
            typeList.Add(descriptionAttribute.Description, value);
        }
    }

    return typeList;
}

This code is really straight forward. It gets the description attribute for each field in the enumeration by using reflection. The description and the enum value itself are added to a dictionary which can be used as binding source for our combo box:

<ObjectDataProvider
    MethodName="GetDict"
    ObjectType="{x:Type App:EnumDescriptionValueDict}"
    x:Key="EnumDescriptionDict">
  <ObjectDataProvider.MethodParameters>
    <x:Type TypeName="App:Transmission"></x:Type>
  </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

<ComboBox
      ItemsSource="{Binding Source={StaticResource EnumDescriptionDict}}"
      DisplayMemberPath="Key"
      SelectedValuePath="Value"/>

Because we are using a dictionary now, we have to tell the combo box the appropriate display and value path. Those are simply the properties of a single KeyValuePair within the dictionary. When you run the code, you will see the descriptions within the combo box, instead of the enumeration values.

Just one last thing for this post I want you to show is the binding of the selected value in the combo box to a view model property. Let’s assume we have a view model with a property of type Transmission. We want this property bound to the currently selected value of the combo box. All we need is a Converter that converts the enum value to string and also converts a string to an enum value. Therefore I’ll name this converter EnumToStringConverter:

[ValueConversion(typeof(Enum), typeof(String))]
public class EnumToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value.ToString();
    }

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? null : Enum.Parse(targetType,
                                         value.ToString(), true);
    }
}

With the value converter defined and the according property on the view model, we can now add the following line to our combo box:

SelectedValue="{Binding Transmission, Converter={StaticResource EnumConverter}, Mode=TwoWay}"

Here you go. With an enum bound to a combo box that shows custom descriptions and promotes its selected value right to the underlying view model. Enjoy it!