views:

40

answers:

1

I would like to serialize the properties of the HttpBrowserCapibilities object so that it may be returned via a web method call. Currently the object cannot be serialized:

Cannot serialize member System.Web.Configuration.HttpCapabilitiesBase.Capabilities of type System.Collections.IDictionary, because it implements IDictionary. 

...which is understandable. However, I would like to simply copy out the properties and their values to a hierarchy, i.e.

<HttpBrowserCapabilities>
   <IsMobile>true</IsMobile>
</HttpBrowserCapabilities>

I'm starting to think I would need to use reflection to copy this object, but I haven't reached a conclusion. Does anyone have any suggestions to keep this simple?

Thanks, George

+2  A: 

Originally I posted an answer using XmlDocument, but I glossed over some of the web method stuff and didn't realize you were really trying to map a DTO.

Reflection sounds complicated but it really isn't. The following snippet will do what you want:

public static void Populate(object dest, IDictionary dictionary)
{
    Type t = dest.GetType();
    foreach (object key in dictionary)
    {
        PropertyInfo prop = t.GetProperty(key.ToString(),
            BindingFlags.Instance | BindingFlags.Public);
        if ((prop != null) && prop.CanWrite)
        {
            object value = dictionary[key];
            prop.SetValue(dest, value, null);
        }
    }
}

Then invoke this as:

BrowserCapsDto dto = new BrowserCapsDto();
Populate(dto, Capabilities);  // Capabilities is the real BrowserCaps

It's pretty easy because you already have an IDictionary and thus you already know all of the possible names you can map; you don't actually need to use any reflection on the source, just the destination.

Aaronaught