WCF Serialization Part 2c: Hacking the NameValueCollection (unsuccesfully)

Tags: WCF, WinFX

As we mentioned here and here, I've been struggling to get the NameValueCollection object to pass through WCF serialization. Please read the first two posts first for some context.

 

In the previous episodes, we saw that we can't get WCF to serialize the NameValueCollection (NVC, from now on) because it incorrectly marked for its CollectionDataContract serialization, but then choked because it had no Add(object) method.

 

So to take the most direct approach, I subclassed the NameValueCollection and added my own Add(object) implementation to see if this jedi mind trick will let WCF work with the NVC class:

 

public class NVC : NameValueCollection

{

    public void Add(object obj)

    {

    }

}

 

Once I did this, the WCF stopped yelling at me that the contract was invalid, but (naturally) my data would vanish during transfer.

 

So next I tried putting a breakpoint inside my Add() method to see what object is passed to it – I was hoping for something along the lines of a KeyValuePair<K,V> or even a DictionaryEntry, something I can use to manually recreate my NVC.

Turns out there's no such luck – even though the NVC has an internal object called NameObjectEntry that the NVC uses internally for storage, it's not exposed externally. Even the GetEnumerator() method returns an enumerator that only goes over the Keys, not a key/value dictionary.

This means that when recreating my dictionary, the value passed to my Add() method is a single string with the key name only, and the value is lost in translation.

 

No luck there, either.

5 Comments

  • Wink Jr. said

    Thank you for saving me who knows how many hours trying to get KeyValuePair working with this, which you think would be a no-brainer, obvious, and built-in. Cheers!

  • Rob V. said

    This might be fixed in VS 2008 (v9.0) with C# 3.0 and .NET 3.5. I haven't tested the code, but the IDE is not throwing up errors with the following: KeyValuePair nvp = KeyValue; foreach (KeyValuePair nvp in NameValueCollection nvc) { [....] string key = nvp.Key; string value = nvp.Value; }
    Note , NOT . Needs to be the object type, not the inherent type. Anyway, not sure if this will work, but as said, VS 2008 is not complaining w/C# 3.0 and .NET 3.5.

Comments have been disabled for this content.