1
Vote

XmlDigester doesn't support nullable types

description

Hi,
 
XmlDigester doesn't seem to support nullable types.
 
For exemple, take the test project. Now, open Order.cs and change the type of the "Total" property in to "decimal?".
Run the project, and you'll see that PropertySetterRule.OnEnd will throw an InvalidCastException.
 
This can be fixed by first checking if the property type is nullable.
If so, check if its value is null. If it is, then don't assign a value to the property, otherwise, convert it into into underlying type.
 
Here is how I fixed PropertySetterRule :
// populate object's property
object top = this.Digester.Peek();
PropertyInfo prop = top.GetType().GetProperty(property, BindingFlags.Public | BindingFlags.Instance);
if(prop != null)
{
Type conversionType = prop.PropertyType;
 
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (body == string.Empty)
  return;
 
System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
 
prop.SetValue(top, Convert.ChangeType(body, conversionType), null);
}
 
The same problem happens in SetPropertiesRule, and here is a fix :
// set property value
if(prop != null)
{
Type conversionType = prop.PropertyType;
 
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value != string.Empty)
{
  System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
  conversionType = nullableConverter.UnderlyingType;
}
}
 
if (value != string.Empty)
prop.SetValue(top, Convert.ChangeType(value, conversionType), null);
}
 
Best Regards,
 
Cédric Richard

comments