Sunday, May 16, 2010

BinaryFormatter versus XmlElement

Ran into an issue trying to store a Web Reference tool generated class in ViewState that had an internal XmlElement array.

System.Runtime.Serialization.SerializationException: Type 'System.Xml.XmlElement' in Assembly 'System.Xml, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.

One possible solution would be to create a ISerializationSurrogate that gets added to the BinaryFormatter.SurrogateSelector (example). However, it isn't clear how this would work with ViewState serilization (I.e. where to plug it in?).

Instead I extended the partial class created by the web reference tool so that it implemented ISerializable. Then using the GetObjectData method and a custom deserilization constructor I stored the OuterXml of the XmlElement at a string.