Namespace: System.Runtime.Serialization
In a very complex object creation scenario we may want to
implement serialization our self. To do custom serialization one must apply the
serialization attributes to the class in the same way and also class must
implement ISerializable interface.
Constructor to be implemented should look like:
Protected
<ClassName>(SerializationInfo si, StreamingContext sc)
{
productid
= info.GetInt32(“Product ID”);
productprice
= info.GetInt32(“Price”);
productQuantity =
info.GetInt32(“Quantity”);
total =
productprice * productQuantity;
}
For Deserialization implement
the method:
[SecurityPermissionAttribute(SecurityAction.Demand,
SerializationFormatter = true)]
public virtual void
GetObjectData(SerializationInfo info, StreamContext context)
{
info.AddValue(“Product
ID”,productid);
info.AddValue(“Price”,productprice);
info.AddValue(“Quantity”,productQuantity);
}
Responding to Serialization Events:
Serializing: Apply [OnSerializing]
Attribute
Serialized: Apply [OnSerialized]
Attribute
Deserializing: Apply [OnDeserialized]
Attribute
Deserialized: Apply [OnDeserializing]
Attribute
NOTE: This method is been called after IDeserializationCallback.OnDeserialization. Don’t use
[OnDeserializing] attribute if Formatter other than BinarFormatter is used, in
this case use OnDeserialization callback method.
Rules for Event handling:
• Method must accept StreamingContext object
• Returns void
• Proper attribute is being applied
How to change serialization based on context:
Specific Context information may be
required to in order to deserialize an object. One can make those decisions
himself in the GetObject method in which StreamingContext is provided. One can
throw exception if the context information is not relevant.
To manipulate the Context information use the State bit and
Set the status as required. These statuses are:
CrossProcessor, CrossMachine, File, Persistance, Remoting, Other, Close, CrossAppDomain, All.
One can use Context property of Formatters to alter context
information before manipulation.
How to Create Custom Formatters:
IFormatter, IGenericFormatter
interface can be implemented. One can take advantage form static methods of FormatterServices class.
Comments