Custom Serialization Formatting

This objective covers the use of the BinaryFormatter and SoapFormatter classes. I frankly don’t understand why they should be separated from the rest, with a title of custom serialization, but I guess we should just learn it.

These classes lives in the System.Runtime.Serialization.Formatters namespace. Even better, BinaryFormatter lives in the Binary namespace, and SoapFormatter in the Soap namespace. You will need to set a reference on the System.Runtime.Serialization.Formatters.Soap namespace in order to use the SoapFormatter class. BinaryFormatter is included by default.

BinaryFormatter serializes or deserializes yoir objects into a binary object graph. It will need two things to do so: a stream (not necessary a file stream) and an object, marked as Serializable. By default, all public fields and properties are serialized (and private fields with public properties). You can override this setting by mark your fields with the NonSerializable or OptionalField attribute. The latter is useful when dealing with version-compatible serialization.

A basic example:

public class MyLittleClass
  int x;
  String y;
BinaryFormatter bf = new BinaryFormatter();
MyLittleClass myClass = new MyLittleClass();
myClass.x = 32;
myClass.y = “Hello World!”;
bf.Serialize(File.Create(@”C:mypathbin.dat”, myClass);

And now to deserilaize:

MyLittleClass myC = (MyLittleClass)Bf.Deserialize(File.Open(@”C:mypathbin.dat”, FileMode.Open));
//myC.x will be 32, y will be String.Empty

It’s that easy! Note that when an exception occurs during serialization or deserialization, a SerializationException will be thrown. No extra features in it, just the simple Exception.

There’s a method called UnSafeDeserialization. Use it only when you are in full trust security context, otherwise use Deserialization.

Deserialization is dangerous in some cases, due to the so-called deserialization attacks. To evade these attacks, use the FilterLevel property with the Low member of the TypeFilterLevel enumeration.

I bet you could guess the difference between BinaryFormatter and SoapFormatter. Yes, the latter uses the SOAP format, which is cool when dealing with remote procedure calls, and provides vast compatibility between systems, languages, etc.

Because of the nature of SOAP, SoapFormatter don’t provide unsafe deserialization methods. Otherwise the use and feel is same as the BinaryFormatter’s.

Further Readings

BinaryFormatter Class
SoapFormatter Class

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s