But in DataContractSerializer–does not handle object-types well

In using SuspensionManager and the Session State on Windows 8, I tried saving an object into it and the app kept crashing on load.. Just spent four hours chasing my tail…

Finally figured it out. Here it is if anyone else is hitting it.

If you have a class pointing to object and that object is actually a class where the Namespace property on the DataContractAttribute is empty, you are going to fail deserialization.

The solution is simple (usually) – give that class a namespace..

Repro

Given class MyClass:

//[DataContract(Namespace = "http://dotnetfail")]
[DataContract(Namespace = "")]
public class MyData
{
}

The following code will throw on the last line. Notice how serialization works fine as long as you don’t actually point to MyClass from an object type (the first part)

// This will work
DataContractSerializer ser = new DataContractSerializer(typeof(MyData));
MemoryStream stream = new MemoryStream();
ser.WriteObject(stream, new MyData());
stream.Position = 0;
ser.ReadObject(stream);

// This will throw (at the end)
ser = new DataContractSerializer(typeof(Dictionary<string, object>), new Type[] { typeof(MyData) });
stream = new MemoryStream();
var dict = new Dictionary<string, object>();
dict["MyObject"] = new MyData();
ser.WriteObject(stream, dict);
stream.Position = 0;
ser.ReadObject(stream);

The error points to a bogus location in the XML and gives a bogus exception description, sadly (which is why it took me so long to find it).

The following exception is thrown:

Error in line 1 position 202. 'EndElement' 'KeyValueOfstringanyType' from 
namespace 'http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not
expected. Expecting element 'Value'.
 
Hope this saves some time for someone.
Advertisements
This entry was posted in Dev, Windows8 and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s