Sunday, August 18, 2019

Serialization (C#)

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

How serialization works

This illustration shows the overall process of serialization:
Serialization graphic
The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version, culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.

Uses for serialization

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. 
Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Making an object serializable

To serialize an object, you need the object to be serialized, a stream to contain the serialized object, and a FormatterSystem.Runtime.Serialization contains the classes necessary for serializing and deserializing objects.
Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. An exception is thrown if you attempt to serialize but the type doesn't have the SerializableAttribute attribute.
If you don't want a field within your class to be serializable, apply the NonSerializedAttributeattribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and the field cannot be meaningfully reconstituted in a different environment, then you may want to make it nonserializable.
If a serialized class contains references to objects of other classes that are marked SerializableAttribute, those objects will also be serialized.

Binary and XML serialization

You can use binary or XML serialization. In binary serialization, all members, even members that are read-only, are serialized, and performance is enhanced. XML serialization provides more readable code, and greater flexibility of object sharing and usage for interoperability purposes.

Binary serialization

Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams.

XML serialization

XML serialization serializes the public fields and properties of an object, or the parameters and return 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 XML. System.Xml.Serialization contains the classes necessary for serializing and deserializing XML.
You apply attributes to classes and class members to control the way the XmlSerializer serializes or deserializes an instance of the class.

Basic and custom serialization

Serialization can be performed in two ways, basic and custom. Basic serialization uses the .NET Framework to automatically serialize the object.

Basic serialization

The only requirement in basic serialization is that the object has the SerializableAttribute attribute applied. The NonSerializedAttribute can be used to keep specific fields from being serialized.
When you use basic serialization, the versioning of objects may create problems. You would use custom serialization when versioning issues are important. Basic serialization is the easiest way to perform serialization, but it does not provide much control over the process.

Custom serialization

In custom serialization, you can specify exactly which objects will be serialized and how it will be done. The class must be marked SerializableAttribute and implement the ISerializable interface.
If you want your object to be deserialized in a custom manner as well, you must use a custom constructor.

Designer serialization

Designer serialization is a special form of serialization that involves the kind of object persistence associated with development tools. 
Designer serialization is the process of converting an object graph into a source file that can later be used to recover the object graph. A source file can contain code, markup, or even SQL table information.

Let's look at an example of how we can achieve this.
In our example, we are going to perform the below high-level steps in the code
  1. Create a class called Tutorial which has 2 properties, namely ID, and Name
  2. We will then create an object from the class and assign a value of "1" to the ID property and a value of ".Net" to the name property.
  3. We will then use serialization to serialize the above object to a file called Example.txt
  4. Finally, we will use deserialization to deserialize the object from the file and display the values in the Console.
Enter the below code in the program.cs file of the console application.
Step 1) The first step is to add the class which will be used for serialization
C# File Operations
Code Explanation:-
  1. The class which needs to be serialized needs to have the [Serializable] attribute. This is a keyword in C#. This keyword is then attached to the Tutorial class. If you don't mention this attribute, you will get an error when you try to serialize the class.
  2. Next is the definition of the class which will be serialized. Here we are defining a class called "Tutorial" and providing 2 properties, one is "ID" and the other is "Name."
Step 2) In this step, first we will create the object of the Tutorial class and serialize it to the file called Example.txt
C# File Operations
Code Explanation:-
  1. First, we create an object of the Tutorial class. We then assign the value of "1" to ID and ".net" to the name property.
  2. We then use the formatter class which is used to serialize or convert the object to a binary format. The data in the file in serialization is done in binary format. Next, we create a file stream object. The file stream object is used to open the file Example.txt for writing purposes. The keywords FileMode.Create and FileMode.Write is used to specifically mention that the file should be opened for writing purposes.
  3. Finally, we use the Serialize method to transfer the binary data to the file. We then close the stream, since the write operation is complete.
Step 3) Finally to ensure that the data is present in the file, we use deserialization to deserialize the object from the file.
C# File Operations
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
  [Serializable]
  class Tutorial
  {
  public int ID;
  public String Name;
   static void Main(string[] args)
   {
    Tutorial obj = new Tutorial();
    obj.ID = 1;
    obj.Name = ".Net";

    IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Create,FileAccess.Write);

    formatter.Serialize(stream, obj);
    stream.Close();

    stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Open,FileAccess.Read);
    Tutorial objnew = (Tutorial)formatter.Deserialize(stream);

    Console.WriteLine(objnew.ID);
    Console.WriteLine(objnew.Name);

    Console.ReadKey();
  }
 }
}
Code Explanation:-
  1. We create the object "stream" to open the file Example.txt in reading only mode.
  2. We then use the formatter class which is used to deserialize the object, which is stored in the Example.txt file. The object returned is set to the object objnew.
  3. Finally, we display the properties of the object "objnew" to the console using the "ID" and "name" properties.
When the above code is set, and the project is run using Visual Studio, you will get the below output.
Output:-
C# File Operations
You can see from the above output that the values from the file were deserialized properly and displayed in the console.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...