• No results found

Reflection and Serialization 170 

In document CSharp Handout v1.0 (Page 170-175)

Learning Objectives

After completing this session, you will able to: ‰ Describe overview of Serialization ‰ Identify the types of Serialization

Overview

Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent storage location. This storage location can be a physical file, database or ASP.NET Cache. Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines. This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily. Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client. The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another.

What is Serialization and De-serialization?

Serialization is the process of saving the state of an object in a persistent storage media by converting the object to a linear stream of bytes. The object can be persisted to a file, a database or even in the memory. The reverse process of serialization is known as de-serialization and enables us to re-construct the object from the previously serialized instance of the same in the persistent or non-persistent storage media.

Serialization in .NET is provided by the System.Runtime.Serialization namespace. This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream. In order to

implement serialization in .NET, you basically require a stream and a formatter. While the stream acts as a container for the serialized objects, the formatter is used to serialize these objects onto the stream.

The basic advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object if required at a later point of time by de-serializing the object. Remoting and Web Services depend heavily on Serialization and De-serialization.

Types of Serialization

Serialization can be of the following types: ‰ Binary Serialization

‰ SOAP Serialization ‰ XML Serialization ‰ Custom Serialization

Binary Serialization: Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically. The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media.

public void BinarySerialize(string filename, Employee emp) {

FileStream fileStreamObject; try

{

fileStreamObject = new FileStream(filename, FileMode.Create); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(fileStreamObject, emp); } finally { fileStreamObject.Close(); } }

Advantages and Disadvantages of Binary Serialization:

The following are the major advantages of using Binary Serialization:

‰ The object can be de-serialized from the same data you serialized it to. ‰ Enhanced performance as it is faster and even more powerful

‰ Provides support for complex objects, read only properties and even circular references.

The following is the drawback of using Binary Serialization ‰ Not easily portable to another platform.

Soap Serialization: The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures. In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application. The basic advantage of SOAP serialization is portability. The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message. public void SOAPSerialize(string filename,Employee employeeObject) {

FileStream fileStreamObject = new FileStream(filename, FileMode.Create);

SoapFormatter soapFormatter = new SoapFormatter();

soapFormatter.Serialize(fileStreamObject, employeeObject); fileStreamObject.Close();

}

XML Serialization: "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be

processed by any application, as needed, regardless of platform." Implementing XML Serialization in .Net is quite simple. The basic class that we need to use is the XmlSerializer for both

serialization and de-serialization. The Web Services use the SOAP protocol for communication and the return types and the parameters are all serialized using the XmlSerializer class. XML Serialization is however, much slower compared to Binary serialization.

public void XMLSerialize(Employee emp, String filename) {

XmlSerializer serializer = null; FileStream stream = null;

try {

serializer = new XmlSerializer(typeof(Employee)); stream = new FileStream(filename,

FileMode.Create, FileAccess.Write); serializer.Serialize(stream, emp); }

{

if (stream != null) stream.Close(); }

}

The advantages of XML Serialization are as follows: ‰ XML based

‰ Support for cross platforms ‰ Easily readable and editable

Custom Serialization: In some cases, the default serialization techniques provided by .NET may not be sufficient in real life. This is when we require implementing custom serialization. It is possible to implement custom serialization in .NET by implementing the ISerializable interface. This interface allows an object to take control of its own serialization and de-serialization process. It gives us a great deal of flexibility in the way we can save and restore objects.

public class Employee: ISerializable {

private int empCode; private string empName;

protected Employee(SerializationInfo serializationInfo, StreamingContext streamingContext) { this.empCode = serializationInfo.GetInt32("empCode"); this.empName = serializationInfo.GetString("empName"); } public void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { serializationInfo.AddValue("empCode", this.empCode); serializationInfo.AddValue("empName", this.empName); } }

Working with formatters:

A formatter is used to determine the serialization format for objects. In other words, it is used to control the serialization of an object to and from a stream. They are the objects that are used to encode and serialize data into an appropriate format before they are transmitted over the network. They expose an interface called the IFormatter interface. IFormatter's significant methods are Serialize and De-serialize which perform the actual serialization and de-serialization.There are two formatter classes provided within .NET, the BinaryFormatter and the SoapFormatter. Both these classes extend the IFormatter interface.

The Binary Formatter: The Binary formatter provides support for serialization using binary encoding. The BinaryFormater class is responsible for binary serialization and is used commonly in .NET's Remoting technology. This class is not appropriate when the data is supposed to be transmitted through a firewall.

The SOAP Formatter: The SOAP formatter provides formatting that can be used to serialize objects using the SOAP protocol. It is used to create a Soap envelop and it uses an object graph to generate the result. It is responsible for serializing objects into SOAP messages or parsing the SOAP messages and extracting these serialized objects from the SOAP messages. SOAP formatters in .NET are widely used by the Web Services.

Advantages and disadvantages of serialization The following are the basic advantages of serialization:

‰ Facilitate the transportation of an object through a network ‰ Create a clone of an object

The primary disadvantages of serialization are:

‰ Resource overhead (both the CPU and the IO devices)

‰ Latency issues that are involved for transmitting the data over the network ‰ Serialization is quite slow.

‰ XML serialization is insecure, consumes a lot of space on the disk and it works on public members and public classes and not on the private or internal classes.

Summary

‰ .NET provides built-in object serialization services. ‰ Serialization will moves from field-level to object-level.

‰ You can generalize serialization to allow XML, SOAP, Binary formats and other future formats.

‰ Various types of Serialization are Binary Serialization, SOAP Serialization, XML Serialization, and Custom Serialization.

Test Your Understanding 1. What is Serialization? 2. What is Deserialization?

3. What are the Types of serialization? 4. What is a Binary Serialization?

5. What are the advantages and disadvantages of using Binary Serialization? 6. What is Soap Serialization?

7. What is XML Serialization? 8. What is Custom Serialization? 9. What is Binary Formatter? 10. What is Soap Formatter?

In document CSharp Handout v1.0 (Page 170-175)