Serialization in Silverlight
Share
Note: This post is, essentially, a re-tread on the serialization solution explored by Rockford Lhotka during a prototype of CSLA.
That last little while I’ve been working on a persistence solution for Silverlight that requires both serialization and compression to have any value. These two concepts are, unfortunately, fairly difficult to implement in Silverlight due to the fact that they no longer exist. Serialization is slowed by the following limitations:
1. There are no Serialization attributes. This means no concept of a formatter that we could use to blast objects into binary, or XML, like we enjoy in .NET today.
2. Reflection is limited to the calling class, and only the calling class. This means every single class needs to reflect on its own properties, class inheritance no longer matters. While this isn’t the end of the world, it’s a lot of extra code you won’t enjoy writing. It will feel a little like you’re giving up OO.
3. Every instance you want to serialize has to implement your interface. This means no .NET value types, or reference types. You want a DateTime? Create your own and make it serializable. It will feel a little like you’re giving up the .NET Framework.
Most of the time you will likely resort to heavy lifting with strings you pull from isolated storage, or proxy classes generated from a WCF Service Reference, and call it quits with serialization. But sometimes, as is the case with custom types, you’ll need the ability to perform serialization similar to a BinaryFormatter.
Rockford Lhotka prototyped a solution for this earlier, and I’ve reorganized it slightly to give a broader view of how it could work for you. Indeed, without rolling your own string-based field management layer, this might be the simplest.
As mentioned above, the process is to create your own Serializable attributes, implement a custom formatter with its own SerializationInfo (in Rockford’s it is based on LINQ to XML and an XmlWriter), and then create "ISerializable" classes for everything you want to pass around on the client. Here is an example with a serializable base class and a serializable DateTime concrete class:
Figure 1 – Here is a diagram showing the class hierarchy:
SerializableDateTime overrides two virtual methods, GetValue and
SetValue, to provide reflection over its own fields.
Figure 2 – A custom XML formatter and SerializationInfo class provide
the ability to serialize in and out of streams.
Download: VS2008
Socialized