Handling Exceptions in Properties for Bidirectional Data Coming from a Web Service

I need to consume data from a web service. I am getting XML data and use that to create objects through property setters.

In one specific case, an object attribute (called "is_active" and indicates whether it is active or inactive in the application) is sometimes represented

<field type="BooleanField" name="is_active">1</field>

      

and in other cases -

<field type="BooleanField" name="is_active">True</field>

      

The client code requires me to represent this using integers 1 and 0. The returned string "True" or "False" results in a System.FormatException error, as expected.

What is the most graceful way to handle this situation?

Thanks.

+1


a source to share


1 answer


What do you use to process your data? Since this is obviously custom serialization, it seems like you should be able to customize the "BooleanField" handling to handle both ...

IMO, however, you are not using the xml the way it is intended ... it would be easier to specify this as elements / attributes like like XmlSerializer

(really, why not just use it XmlSerializer

?):

<isActive>true</isActive>

      

or

<foo ... isActive="true" ... />

      



Note that the xml standard for true / false is lowercase ...


Additionally; if you are using TypeConverter

- you can just change the converter:

using System;
using System.Collections.Generic;
using System.ComponentModel;
public class Program
{
    static void Main()
    {
        TypeDescriptor.AddAttributes(typeof(bool),
            new TypeConverterAttribute(typeof(MyBooleanConverter)));

        TypeConverter conv = TypeDescriptor.GetConverter(typeof(bool));
        Console.WriteLine((bool)conv.ConvertFrom("True"));
        Console.WriteLine((bool)conv.ConvertFrom("true"));
        Console.WriteLine((bool)conv.ConvertFrom("False"));
        Console.WriteLine((bool)conv.ConvertFrom("false"));
        Console.WriteLine((bool)conv.ConvertFrom("0"));
        Console.WriteLine((bool)conv.ConvertFrom("1"));
    }
}

class MyBooleanConverter : BooleanConverter
{
    static readonly Dictionary<string, bool> map
        = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase)
        { { "true", true }, { "false", false },
          { "1", true }, { "0", false } };

    public override object ConvertFrom(ITypeDescriptorContext context,
        System.Globalization.CultureInfo culture, object value)
    {
        string s = value as string;
        bool result;
        if (!string.IsNullOrEmpty(s) && map.TryGetValue(s, out result))
        {
            return result;
        }
        return base.ConvertFrom(context, culture, value);
    }
}

      

+1


a source







All Articles