Serialization
Morten Mertner Senior Consultant, Teknologisk Institut - Architect and Software Developer (C#) - Teacher - Speaker (conferences and gatherings) Certificeringer - MSCD.NET - MCT Open Source - Gentle.NET (object persistence framework / object-relational mapper) - MbUnit (unit test framework)
Agenda Serialization - what is serialization? - implementation Basic Serialization Custom Serialization Versioning
What is Serialization? Serialization - the process of converting an in-memory object graph into a linear sequence of bytes Purposes (what happens to the byte sequence) - send it to another process - send it to the clipboard, to be browsed or used by another application - send it to another machine - send it to a file on disk
Serialization Object Graph What is an object graph? - an object graph is a set of objects with some set of references to each other - the most obvious problem is how to represent the links between the objects in the Serialized stream 3 Dog 4 Cat 7 Cat 1 Mouse 9 Horse 2 Duck
Serialization Implementation CLR - has metadata on each type - property and field definitions - object memory layout - this metadata enables the default serialization mechanisms - shows the power of custom attributes and reflection Formatters decide what the output looks like - XML (default is to include public properties only) - binary (default is to include all members) - custom (you decide)
Serialization Example ArrayList list = new ArrayList(); for( int x=0; x< 10; x++ ) { list.add (x); } Stream s = (new File ("foo.bin")).open(filemode.create); BinaryFormatter bf = new BinaryFormatter(); bf.serialize( s, list ); s.close(); Stream s = (new File ("foo.bin")).open(filemode.open); BinaryFormatter bf = new BinaryFormatter(); ArrayList list = (ArrayList) bf.deserialize( s ); s.close();
Basic Serialization Types must be marked as [Serializable] - base class must also be serializable [Serializable] public class MyClass {} Exclude members from serialization using [NonSerialized] [Serializable] public class MyClass { [NonSerialized] IDbConnection connection; }
Custom Serialization ISerializable Events - IDeserializationCallback - Attributes Custom Formatters
Custom Serialization ISerializable Customize the serialization process - if a class implements ISerializable the default serialization mechanism will not be used ISerializable contains only one method void GetObjectData( SerializationInfo info, StreamingContext context ); // And an implied constructor that may be private private <TypeName>( SerializationInfo info, StreamingContext context );
Custom Serialization Events IDeserializationCallback (.NET 1.1) - provides a means to restore non-serialized members after deserialization is complete - mainly useful with custom formatter - example usage: restore database connection
Custom Serialization Events Applied as method attributes (.NET 2.0) - OnSerializingAttribute - OnSerializedAttribute - OnDeserializingAttribute - OnDeserializedAttribute Event handling method signature void <Method Name>( StreamingContext context ); Prefer serialization attributes over custom serialization
Custom Serialization Custom Formatter IFormatter interface - pluggable mechanism for using a different output format public interface IFormatter: { //Properties SerializationBinder Binder { get; set; } StreamingContext Context { get; set; } ISurrogateSelector SurrogateSelector { get; set; } //Methods object Deserialize(Stream serializationstream); void Serialize(Stream serializationstream, object graph); }
Serialization Versioning In.NET 1.1 - cannot change type definition once serialized - no internal mutability of metadata In.NET 2.0 - binary formatter silently ignores additional members in stream - allows removing of members - formatters can be told to ignore additional members in class - allows adding members - default is intolerant
Serialization Versioning OptionalField attribute - use it to toggle tolerance - can contain version information - reflect it in deserializing event and perform custom steps [AttributeUsage( AttributeTargets.Field, Inherited=false)] public sealed class OptionalFieldAttribute : Attribute { public int VersionAdded { get; set; } }
Serialization Versioning and Web Services Web Services - uses XML / SOAP formatter But... - contract is not allowed to change - contract is usually inflexible (no optional fields) Solution - interface (contract) refactoring
Serialization Final Words Serialization - powerful mechanism for persisting object graphs - easily customizable Generic Serialization - provides type safety - use SerializationUtil from IDesign - downloadable from http://www.idesign.net