Implementation of the event handler attributes

The following code sample shows how to implement event handler attributes by using the ISerializable interface and IDeserializableCallback with CustomFormatter and its methods. The code implements both the ISerializable and the IDeserializableCallback interfaces in a class named Rectangle, which gives the result of the area of a rectangle whose length and width are passed through the constructor of the class.

The class defines five variables, which are initialized through a constructor and five methods with different event handling attributes. There is an optional field among the variables marked by OptionalFieldAttribute. The class also defines the GetObjectData method to initialize the SerializationInfo class before serialization and the OnDeserialization method, which implements the OnDeserialization method of IDeserializableCallback to get the result after deserialization. The Rectangle class also provides two methods, Serialize and Deserialize, which serialize and deserialize the object of the Rectangle class respectively, by using the CustomFormatter class.

The CustomFormatter class implements IFormatter and IFormatterConverter interfaces to create the custom formatter. The CustomFormatter class provides three properties and two methods, Serialize and Deserialize, which implement the serialize and deserialize methods of the IFormatter interface. The length and the width of the rectangle, stored in the SerializationInfo class, are transformed into Bytes by the Convert method that implements the Convert method of the IFormatterConverter interface.

Later in the code, the Main method shows how to create and serialize an object of the Rectangle class into a binary file on the disk by custom formatter and shows how EventHandlerAttributes and OptionalFieldAttribute are used during serialization and deserialization. While doing so, the object is serialized per the implementation provided by the serialize method in the CustomFormatter class. Finally, the code creates a second object of the Rectangle class by deserializing the data in the binary file and displays the newly created object on the console. The data in the binary file is deserialized per the implementation provided for the deserialize method in the CustomFormatter class.

Visual Basic

Imports System Imports System.IO Imports System.Text Imports System.Collections Imports System.Xml.Serialization Imports System.Runtime.Serialization

Class EventHandlerAttributes

Public Shared Sub Main()

Dim ob As New Rectangle

Conso1e.WriteLine(vbLf + '

' Before serialization the object contains: ")


Rectangle.Seri al ize()

Conso1e.WriteLine(vbLf + '

' After serialization the object contains: ")


Rectangle.Deseri a1ize()

Conso1e.WriteLine(vbLf + '

' After deserialization the object contains: ")


Console. ReadLine()

End Sub

End Class

<Seria1izab1e()>C1ass Rectangle Implements ISerializable Implements IDeseri alizationCalIback

Public LengthRect As Double Public WidthRect As Double

Private InfoSerial As SerializationInfo Private ContextStrea As StreamingContext

<NonSeria1ized()>Pub1ic AreaRect As Double

Public Sub New(ByVa1 length As Double, ByVal width As Double) LengthRect = length WidthRect = width End Sub

Public Sub New( _

ByVal info As SerializationInfo, ByVal context As StreamingContext) Me.InfoSerial = info Me.ContextStrea = context End Sub

<NonSerialized()>_ Public Var3 As String Private var4 As String

<OptionalFieldAttribute(VersionAdded :=2)>_ Dim optionalField As String

var2 = "Hello World!"

var3 = "This is a nonserialized value"

var4 = Nothing optionalField = "This is an optional value" End Sub

Public Sub Print()

Console.WriteLine( Console.WriteLine( Console.WriteLine( Console.WriteLine( Console.WriteLine( End Sub

' variable1 =


, var1)

' variable2 =


, var2)

' variable3 =


, var3)

' variable4 =


, var4)

' variable5 =




Friend Sub OnSerializingMethod(ByVal context As StreamingContext)

var2 = "This value went into the data file during serialization." End Sub

Friend Sub OnSerializedMethod(ByVal context As StreamingContext)

var2 = "This value was reset after serialization." End Sub


Friend Sub OnDeserializingMethod(ByVal context As StreamingContext)

var3 = "This value was set during deserialization" End Sub


Friend Sub OnDeserializedMethod(ByVal context As StreamingContext)

var4 = "This value was set after deserialization." End Sub End Class

Public Class CustomFormatter Implements IFormatter Implements IFormatterConverter

Public Property Binder() As System.Runtime.Serialization.SerializationBinder Implements System.Runtime.Seri alization.IFormatter.Binde r Get

Throw New NotSupportedException() End Get

Set(ByVal value As System.Runtime.Serialization.SerializationBinder)

Throw New NotSupportedException() End Set End Property

Public Property Context() As System.Runtime.Serialization.StreamingContext _ Implements System.Runtime.Seri alization.IFormatter.Context Get

Throw New NotSupportedException() End Get

Set(ByVal value As System.Runtime.Serialization.StreamingContext)

Throw New NotSupportedException() End Set End Property

Public Function Deserialize(ByVal serializationStream As System.IO.Stream) _ As Object Implements System.Runtime.Serialization.IFormatter.Deserialize

Dim st As New StreamReader(serializationStream) Dim str As String = st.ReadToEnd Dim s() As String = str.Split(",")

Dim ss As New SerializationInfo(GetType(Rectangle), New CustomFormatter) ss.AddValue("LengthRect", Double.Parse(s(0))) ss.AddValue("WidthRect", Double.Parse(s(1)))

Dim ob As New Rectangle(ss, Nothing)

If TypeOf (ob) Is IDeserializationCallback Then ob.OnDeserialization(ob) End If

Return ob

End Function

Public Sub Serialize(ByVal serializationStream As System.IO.Stream, _ ByVal graph As Object) Implements _ System.Runtime.Serialization.IFormatter.Seri alize

Dim g As Rectangle = CType(graph, Rectangle)

Dim ss As New SerializationInfo(GetType(Rectangle), New CustomFormatter)

If TypeOf (g) Is ISerializable Then g.GetObjectData(ss, Nothing) End If

Dim ba() As Byte = Convert(ss, TypeCode.Byte) serializationStream.Write(ba, 0, ba.Length) End Sub

Public Property SurrogateSelector() As _

System.Runtime.Serialization.ISurrogateSelector Implements _ System.Runtime.Serialization.IFormatter.SurrogateSelector Get

Throw New NotSupportedException() End Get

Set(ByVal value As System.Runtime.Serialization.ISurrogateSelector)

Throw New NotSupportedException() End Set End Property

Public Function Convert(ByVal value As Object, ByVal type As System.Type) _

As Object Implements System.Runtime.Serialization.IFormatterConverter.Convert

Throw New NotSupportedException() End Function

Public Function Convert(ByVal value As Object, ByVal typeCode As _

System.TypeCode) As Object Implements _


Dim ba() As Byte =

Encoding.ASCII.GetBytes(CType(value, _

Serializati onInfo)

.GetDouble("LengthRect") & "," & CType(value, _

Serializati onInfo)

.GetDouble("Wi dthRect"))

Return ba

End Function

Public Function ToBoolean(ByVal value As Object) As Boolean Implements _ System.Runtime.Serialization.IFormatterConverter.ToBoolean

End Function

Public Function ToByte(ByVal value As Object) As Byte Implements _ System.Runtime.Serialization.IFormatterConverter.ToByte

End Function

Public Function ToChar(ByVal value As Object) As Char Implements _ System.Runtime.Serialization.IFormatterConverter.ToChar

End Function

Public Function ToDateTime(ByVal value As Object) As Date Implements _ System.Runtime.Serialization.IFormatterConverter.ToDateTime

End Function

Public Function ToDecimal(ByVal value As Object) As Decimal Implements _ System.Runtime.Serialization.IFormatterConverter.ToDecimal

End Function

Public Function ToDouble(ByVal value As Object) As Double Implements _ System.Runtime.Serialization.IFormatterConverter.ToDouble

End Function

Public Function ToInt16(ByVal value As Object) As Short Implements _ System.Runtime.Serialization.IFormatterConverter.ToInt16

End Function

Public Function ToInt32(ByVal value As Object) As Integer Implements _ System.Runtime.Serialization.IFormatterConverter.ToInt32

End Function

Public Function ToInt64(ByVal value As Object) As Long Implements _ System.Runtime.Serialization.IFormatterConverter.ToInt64

End Function

using System;

using System.IO;

using System.Text;

using System.Xml.Serialization;

using System.Runtime.Seriali zation;

class EventHandlerAttributes {

public static void Main() {

Rectangle ob = new Rectangle();

Console.WriteLine(" Before serialization the object contains: "); ob.Print();


Console.WriteLine(" After serialization the object contains: "); ob.Print();

Rectangle.Deserialize() ;

Console.WriteLine( " After deserialization the object contains: ");


[Serializable()]class Rectangle : ISerializable, IDeserializationCallback {

public Double LengthRect; public Double WidthRect;

private SerializationInfo InfoSerial; private StreamingContext ContextStream;

[NonSerialized()] public Double AreaRect;

public Rectangle(Double length, Double width) {

this.LengthRect = length; this.WidthRect = width;

public Rectangle(Se riali zati onInfo info, StreamingContext context)

this.InfoSerial = info; this.ContextStream = context;

public void OnDeserialization(Object sender) {

this.LengthRect = this.InfoSerial.GetDouble("LengthRect"); this.WidthRect = this.InfoSerial.GetDouble("WidthRect");

AreaRect = LengthRect * WidthRect; }

public override string ToString() {

this.AreaRect = this.LengthRect * this.WidthRect;

return string.Format("Length={0}, Width={1}, Area={2}", LengthRect,

WidthRect, AreaRect); }

public void GetObjectData(System.Runtime.Serialization.SerializationInfo info,

System.Runtime.Serialization.Streami ngContext context) {

info.AddValue("LengthRect", this.LengthRect) ; info.AddValue("WidthRect", this.WidthRect);

public static void Serialize() {

Rectangle c = new Rectangle(10, 20);

Console.WriteLine("Object being serialized: " + c.ToString());

FileStream fs = new FileStream("c:\\DataFile.dat", FileMode.Create);

CustomFormatter formatter = new CustomFormatter();



formatter.Serialize(fs, c);


catch (SerializationException e)


Console.WriteLine("Failed to serialize. Reason:

" + e.Message);





fs.Close() ;



public static void Deserialize() {

Rectangle c = null;

FileStream fs = new FileStream("c:\\DataFile.dat", FileMode.Open);

CustomFormatter formatter = new CustomFormatter(); c = ((Rectangle)(formatter.Deserialize(fs))); Console.WriteLine("Object being serialized: " + c.ToString());

catch (SerializationException e) {

Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw;

finally {

public int Var1; private String var2;

[NonSeria1ized()] public string Var3;

private String var4;

[Optiona1Fie1dAttribute(VersionAdded = 2)] String optionalField;

public Rectang1e() {

Var3 = "This is a nonserialized value";

optionalField = "This is an optional value";

public void Print() {

Conso1e.Writel_ine(" Conso1e.WriteLine(" Conso1e.Write_ine(" Conso1e.WriteLine(" Conso1e.WriteLine("

variablel =

' +


variab1e2 =

' +


variableB =

' +


variab1e4 =

' +


variab1e5 =

' +

optionalField) ;


internal void OnSeria1izingthisthod(StreamingContext context) {

var2 = "This value went into the data file during serialization.";


internal void OnSeria1izedthisthod(StreamingContext context) {

var2 = "This value was reset after serialization.";


internal void OnDeseria1izingthisthod(StreamingContext context) {

Var3 = "This value was set during deserialization";


internal void OnDeseria1izedthisthod(StreamingContext context) {

var4 = "This value was set after deserialization.";

public class CustomFormatter : System.Runtime.Serialization.IFormatter,

IFormatterConverter {

public System.Runtime.Serialization.SerializationBinder Binder {

throw new NotSupportedException();

throw new NotSupportedException();

public object Convert(object value, System.TypeCode typeCode) {

Encoding.ASCII.GetBytes(((Seria1izationInfo)(va1ue)).GetDoub1e("Length Rect") + "," +

((Seria1izationInfo)(va1ue)) .GetDoub1e("WidthRect")) ; return ba;

public object Convert(object value, System.Type typeCode) {

Encoding.ASCII.GetBytes(((Seria1izationInfo)(va1ue)).GetDoub1e("LengthRect") + "," + ((Seria1izationInfo)(va1ue)).GetDoub1e("WidthRect")); return ba;

public bool ToBoo1ean(object value) {

throw new NotSupportedException();

public byte ToByte(object value) {

throw new NotSupportedException();

public char ToChar(object value) {

throw new NotSupportedException();

public System.DateTime ToDateTime(object value) {

throw new NotSupportedException();

public decimal ToDecima1(object value) {

throw new NotSupportedException();

public double ToDoub1e(object value) {

throw new NotSupportedException();

Was this article helpful?

0 0

Post a comment