Sunday, April 11, 2010

Custom serialization

If Binary, SOAP or XML default serialization classes don't met yout needs, you can take full control of the serialization process.
For do it, you must implement the ISerializable interface wich have the GetObjectData method.  This method describes the way for serialize your class, and takes a SerializationInfo and a StreamingContext as parameters.  SerializationInfo  requires an object that impements IFormatterConverter interfac.  You also need a special constructor for the deserialization process, with the same parameters as GetObjectData.
You can respond to events for controling serialization and desarialization.  For BinaryFormatter implementations you can put the following attributes in some of your class methods in order to indicate wich event it will respond to: Serializing, Serialized, Deserializing and  Deserialized.  The method must return void and take an StreamingContext parameter.  If you use other type of serialization instead of BinaryFormatter, you must use the IDeserializationCallBack interface, wich have two events for respond to:  OnDeserialization and OnDeserialized.
You also can react on serialization depending on context.  The StreamingObject has two properties that you can use to provide contextual information before passing it to GetObjectData or deserialization constructor methods: Context, an object that you can use to provide any custom information, and State, wich allows you to specify  other data by the following flags:

  • CrossProcess:  The source or destination is a different process on the same machine.
  • CrossMachine:  The source or destination is on a different machine.
  • File:  The source or destination is a file.
  • Persistence:  The source or destionation is a store such as a database.
  • Remoting:  The source or destination is remoting to unknown location.
  • Other:  The source or destionation are unknown.
  • Close:  The same process will handle deserialization.
  • CrossAppDomain:  The source or destination is a different AppDomain
  • All:  The default flag.  Incluedes all the previous.
If none of the .Net framework provided formatters fits your requirements, you can create your own, implementing the IFormatter or IGenericFormatter interfaces.  The FormatterServices class provides static methods(including GetObjectData) to help you with this.

No comments:

Post a Comment

Bookmark and Share