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

 

 

SerializationEvents.jpg

 

 

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;

 

namespace CustomSerializationSample

{

    [Serializable]

    public class ShoppingCartItem : ISerializable

    {

        public int productID;

        public decimal price;

        public int quantity;

        [XmlIgnore]

        public decimal total;

 

      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 < 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

    }

}