Posts filed under ‘Serialization’

Custom Serialization (Part -3)

.Net has provided a way to serialize object as you wish, you can have all control when serializing and deserializing any object. You even decided format of storing serialized object. All custom serialization can be done by implementing ISerializable interface and applying Serializable attribute to class.

[Serializable]

class ShoppingCartItem : ISerializable

{

public Int32 productId;

public decimal price;

public Int32 quantity;

[NonSerialized]

public decimal total;

// Constructor used to initialized member of my ShoppingCartItem object.

public ShoppingCartItem(int _productID, decimal _price, int _quantity)

{

productId = _productID;

price = _price;

quantity = _quantity;

total = price * quantity;

}

// Constructor will be called on deserialization

protected ShoppingCartItem(SerializationInfo info,

StreamingContext context)

{

productId = info.GetInt32(“Product ID”);

price = info.GetDecimal(“Price”);

quantity = info.GetInt32(“Quantity”);

total = price * quantity;

}

// The following method is called during serialization

[SecurityPermissionAttribute(SecurityAction.Demand,

SerializationFormatter=true)]

public virtual void GetObjectData(SerializationInfo info,

StreamingContext context)

{

info.AddValue(“Product ID”, productId);

info.AddValue(“Price”, price);

info.AddValue(“Quantity”, quantity);

}

}

Above class shows how to implement custom serialization, we have implemented a constructor, that is called on deserialization. That will assign value to our object member.

We have also added a method, GetObjectData which is used to store value at the time of Serialization.

If we notice on constructor and methods, it uses SerializationInfo object that is used to convert value to different datatype combatable to our member’s type.

BinaryFormatter provides a way to handle serialized and deserialized events. There are four types of events

Serializing: This event is raised just before serialization takes place. Apply the

OnSerializing attribute to the method that should run in response to this event.

Serialized: This event is raised just after serialization takes place. Apply the OnSerialized attribute to the method that should run in response to this event.

Deserializing: This event is raised just before deserialization takes place. Apply the OnDeserializing attribute to the method that should run in response to this event.

Deserialized: This event is raised just after deserialization takes place and after IDeserializationCallback.OnDeserialization has been called. Apply the OnDeserialized attribute to the method that should run in response to this event.

Respond to one of the above events methods should follow below criteria

àStreamingContext object passed to method as parameter

àReturn Void

àAppropriate attribute should be specified on the method.

[OnSerializing]

void CalculateTotal(StreamingContext sc)

{

total = price * quantity;

}

[OnDeserialized]

void CheckTotal(StreamingContext sc)

{

if (total == 0) { CalculateTotal(sc); }

}

We can add above methods to our class to handle serialized events.

With the help of StrreamingContext, application can decide how to serialize or deserailzed object, we get idea of platform, weather object is serialized with same process or else, from where object is coming, object location etc.

To create custom formatter we should implement IFormatter interface, both of the BinaryFormatter and SoapFormatter have implementation of IFormatter. IFormatter provides many method to implement serialization and deserialization as per own custom way.

May 5, 2010 at 4:19 am Leave a comment

XML Serialization (Part -2)

In previous post we studied how to perform serialization with binary and soap serialization. In this post we will take a look on XML Serialization.

XML (Extensible Markup Language) is used to represent various data like picture, music, or any other simple type. XML represents data in such a way that, we can access our required information easily. XML data can also be edited easily compared to binary data. One more advantage is that XML data can be transferred in network and application that is not written in .net can also interpret them. Most of the languages has library to interpret XML document.

For XML serialization System.Xml.Serialization needs to include in our solution. Namespace provides classes that support to serialize and deserialized object with XML format.

To serialize primitive data type, its very similar to binary serialization, we use XMLSerializer instance for XML serialization, and use of Serialization and deserialization methods.

But when serialization of custom type class there are some rules and that must be met, otherwise we don’t get expected result.

àClass must be public

àClass must have a constructor with no argument

Both of the above condition should be met when serialization of a class object. Apart from it, class serialization would contain only public fields, no private fields will be shown in XML, you don’t require adding Serialize attribute to class, and it will take default value for it.

There are so many attributes to control serialized output; we customize output as per our requirement.

[XmlRoot ("MyCartItem")]

public class CartItem

{

[XmlAttribute] public Int32 productId;

public decimal price;

public Int32 quantity;

[XmlIgnore] public decimal total;

public ShoppingCartItem()

{

}

}

In above class we have used XMLRoot attribute which will be the root element in XML serialization. XMLAttribute says that ,field should be attribute in XML representation else by default each field is represented as an element. XMLIgnore is similar to NoSerialize in binary serialization; it will not serialize particular field.

Serialized output of above class would be like this..

<?xml version=”1.0″ ?>

<CartItem productId=”5″>

<price>10.25</price>

<quantity>2</quantity>

</CartItem>

Please note down here, I have assigned this value to my class object, it can be anything as per your initialization. I have not written code to serialized and deserialized with XML as its same as binary but instead of BinaryFormatter we need to use XMLSerializer class.

May 4, 2010 at 4:31 am Leave a comment

Serialization with .net (Part -1)

Serialization is the process to stream an object, after that store it to file, or transfer in network. Now a days there are so many requirements that we need to store object in file or we want to pass our object to some application running on remote location, even some time requirement exists to consume object in another application which is written in languages other than supported by .net framework.

Microsoft .net provided a very nice way to serialize object with just a few lines. For serialization you need to add System.Runtime.Searlization in your project.

Microsoft .net provides many types of serialization process like Binary, Soap, XML or custom serialization. Each type of serialization stands at their own place depends on requirement we can use any of the supported serialization.

We can serialize any of the data of .net primitive type or our class created by user.

Let’s check how it can be done.

Whenever you are clear that my serialization will be occurred between applications written in .net, you can use binary serialization. Binary serialization is very efficient and takes less space compared to other serialization method.

I have scenarios to store my string data to file.

àCreate an instance of stream class, where you will store your string data.

FileStream fs = new FileStream(“Serialized.Data”, FileMode.Create);

àI have string variable

string myData = “Hi! This is my string data”;

àI want to use Binary serialization, so I need to add System.Runtime.Serialization.Formatters.Binary and create an instance of it.

BinaryFormatter bf = new BinaryFormatter();

àCall Serialize method of BinaryFormatter object.

bf.Serialize(fs,myData);

Now if you open this “Serialized.Data” file you can able to see myData variable’s content in it, there might be some other binary data will be also added ,which is useful when we deserialized object.

At the time of deserialization create instance of BinarayFormmter and call deserialized method.

àdeserialization can be done by..

myData = (String) bf.Deserialize(fs);

Above example shows when we use primitive data type, what about class. We can do same thing with it, but we need to take care of something when creating class.

To serialize class object add [Serializable]  attribute to class. So when ever we do serialize of that class all public and private members will be serialized. Some time we have calculation field in our class and so its not required to serialized it.

At that time we can add [NonSerialized] attribute to calculated field of class.

But when we deserialize object we don’t have calculated field value so at that we require it, we can do that calculation when object is deserialized.

Inherits class with IDeserializationCallback and implement OnDeserialization method, this method will be called exactly when our class is deserialzed, we need to call it explicitly.

Some time we face, version problem, say for example we have stored object earlier in file, and later on we added some new fields to our class so it will not find those newly added field when we deserialize object.

In that situation we can use [OptionalField] attribute to our new fields or members added to class once object is serialized. At the time of deserialize we can assign some default value to this newly added field at IDeserializationCallback’s OnDeserialization method.

Same thing can be done with SoapFormatter class instead of BinaryFormatter but it takes more space. When we want to pass object across network and firewall, SoapFormatter is better to use.

May 3, 2010 at 4:16 am Leave a comment


Archives

Categories

 

May 2012
M T W T F S S
« Feb    
 123456
78910111213
14151617181920
21222324252627
28293031  

Blog Stats

  • 1,999

Follow

Get every new post delivered to your Inbox.