A Quick review of Serialization and DeSeralization events

A Quick review of Serialization and DeSeralization events

.Net provides the facility to intercept Serialization / DeSeralization by providing following events.

Serialization:
OnSerializing
OnSerialized
DeSeralization
OnDesrializing
IDeserialazationCallback

Courtesy: MCTS 70-536 Self Paced Training Kit by Microsoft

Following is the program with implementation of [OnDesrialized] event which checks if the total of the item(s) of a certain category is less than 20, it applies appropriate discount.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Xml.Serialization;</code>

<code>namespace CustomSerializationSample
{
[Serializable]
public class ShoppingCartItem : ISerializable
{
public int productID;
public decimal price;
public int quantity;
[XmlIgnore]
public decimal total;</code>

<code>public ShoppingCartItem(int _productID, decimal _price, int _quantity)
{
productID = _productID;
price = _price;
quantity = _quantity;
total = price * quantity;
}
public ShoppingCartItem()
{
}
[OnDeserialized]
void CalculateTotal(StreamingContext sc)
{
decimal discount;
if (total &lt; 20)
{
discount = (total / 100) * 12;
total = total - discount;
}
}
public override string ToString()
{
return "ProductID: " + this.productID + " : Price " + this.price.ToString() +
", Quantity: " + quantity + ", Disc: " + total;
}

#region ISerializable Members

public ShoppingCartItem(SerializationInfo info,
StreamingContext context)
{

productID = info.GetInt32("Product ID");
price = info.GetInt32("Price");
quantity = info.GetInt32("Quantity");
total = price * quantity;
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{

info.AddValue("Product ID", productID);
info.AddValue("Price", price);
info.AddValue("Quantity", quantity);
}
#endregion
}
}
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s