By GOKUJAMES

What exactly is Serialization?
Serialization is the process of converting an object into a stream of bytes in order to persist 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.

Fig 1.1
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 .

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

How to Make an Object Serializable?

To serialize an object, you need the object to be serialized, a stream to contain the serialized object, and a Formatter. System.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. A Serialization Exception is thrown if you attempt to serialize but the type does not have the SerializableAttribute attribute. If you do not want a field within your class to be Serializable, apply the NonSerializedAttribute attribute. 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

Either binary or XML serialization can be used. In binary serialization, all members, even those that are read-only, are serialized, and performance is enhanced. XML serialization provides more readable code, as well as 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. It is not suitable for passing data through a firewall but provides better performance when storing data.

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 can apply attributes to classes and class members in order to control the way the XmlSerializer serializes or deserializes an instance of the class. For more information, see Controlling XML Serialization Using Attributes and Attributes That Control XML Serialization

SOAP Serialization
XML serialization can also be used to serialize objects into XML streams that conform to the SOAP specification. SOAP is a protocol based on XML, designed specifically to transport procedure calls using XML. As with regular XML serialization, attributes can be used to control the literal-style SOAP messages generated by an XML Web service. For more information, see XML Serialization with XML Web Services and Attributes That Control Encoded SOAP Serialization.

Binary Serialization: Visual C# 2.0 / 3.0

Basically serialization works by breaking down the data to pieces and storing them in the server but Binary Serialization is a type of Object Serialization. Object serialization works by breaking the whole Object into pieces and then storing them. This means that, to use it, you define an object and initialize it. This creates a "state" of the object. When you save the object, it is converted into a stream. To perform binary serialization, there are a few steps you must follow:

1. Above the Class declaration you need to add the [Serializable] Attribute, so that compiler understands that the object of that class is going to be converted to stream and stored. So what are we waiting for let us start our program right away,

1

Programming and Explanation

Step1:
Create a New Visual Studio 2008 / 2005 Windows forms applications, Language is of your choice I will be explaining with both Visual C# also Visual Basic.net. Go to File / New / Project [CTRL + SHFT + N]
1 2 2 3

This brings up the new project Dialog Box shown below

3 1

2 2

At the left what u see is Called the project Type tree. This is where you have to select a Language and the category the application falls into. I will be programming in Visual C# and it will be a Windows Forms Application.

Step 2:
Select Visual C# in the left and then select Windows Forms Application towards the right in the Template box. Do make sure you select .NET Framework towards the top in the new project dialog box below the dialog is you will find a details box; here you will enter the Project Name, Solution Name. I have emphasized enough on difference between project names, solution names. Please do watch my video tutorial on Button control posted in the forums. Info: Name : Project Name Solution Name : Name of the Solution the Project is in. Now hit the Ok button indicated by ‘ 3’

1

2 2 3

Step 3:
If you don’t have the properties window open hit the [ALT + ENTER] combo or the [F4] key else do as instructed below to popup the properties dialog along with the solution explorer,
1

2

UI Design:
Now for my favourite part the user interface design. Final user interface is as shown below. Quite simple isn’t it just contains two group Box and several known controls. ‘ 1 ’ is a group box control , ‘ 2 ‘ is also a group box, ‘ 3 ‘ is buttons for which we will be coding.

1

2

3

2

Coding Our Program and User Interface

Great, I am happy that you came so far. Let us start our design, first create the group box control which is above in the UI. Then we can replicate and just rename the controls so we make the UI as fast as we can. Before that basic aesthetics, rename some properties as shown below .Click the form in your IDE then open the properties box and set the following properties , Text: Serializer / Deserializer If you bump into any problems have a look at the picture below to know how a properties dialog looks like and also setting properties. Resize the form a bit so that we have some room to put those two group box and then also add two big buttons. Just try doing different combinations of properties later so that you have a form the way you like. Example- try making your buttons look like that of Apple’s Website buttons.

1

2

Set the text of the form to Serializer / Deserializer.

1

Firstly we are going to make the group box that is named Serializer .Group box is a container control hence it will be available in the Container Tab of the Visual Studio Toolbox. See below image below to get the idea
1

2

The user interface we end up making in the following steps

First drag and drop a group box from the Toolbox onto the form in the [Design] view. Group box looks like below

From now onwards it’s your duty to drag and drop the controls from toolbox; I am not explaining that bit anymore. Below are the few settings you need to make so that the code works on your application too,

Group Box1: Text : Serializer TextBox1: Name : stxtfirstname [ s represents textbox from Serializer group box ] Text : First Name

TextBox2: Name:stxtlastname Text :Last Name TextBox3: Name:sdesignation Text :Designation I am very much sure Visual Studio 2008 will help you out in aligning the controls inside the group box in a very rich manner. Ok are you done? Great! Now copy the Group Box as a whole and Paste it. Align the group box so that we get the looks of the final UI shown first.Make some changes to the group box that you pasted as below

Group Box2: Text : Deserializer TextBox4: Name : dtxtfirstname [ d represents textbox from Deserializer group box ] Text : First Name

TextBox5: Name:dtxtlastname Text :Last Name TextBox6: Name:ddesignation Text :Designation

Yes One final touch is adding buttons to the Form . Add 2 buttons to the form and Rename them anything you like, also change the text from Button1 to Serialize and Button2 to Deserialize. I will name my button’s as below Button1: Name : btnSerialize Text : Serialize Button2: Name : btnDeserialize Text : Deserialize Yes finally we are good to go to the Coding.

3

Source Code

First any programmer in .NET has to do is find the Namespace that he will be using in his program. For our program we will be using a Few, so double click the form in an empty space else right click and select View Code in the menu. Scroll all the way up to the Using statements and add these Statements.

I want you to take a note that A namespace cannot be added twice, that would result in an error. Visual Studio will let you know that so don’t worry

Namespaces of Importance: System.Runtime.Serialization.Formatters.Binary System.IO Now this is the core namespace that we will be using for Serialization of Object. This namespace contains the necessary classes and methods to serialize the Object. Also to serialize we need a Stream that is the reason we have used the System.IO this namespace provides the File Stream class to convert a file into stream.

Step 1: For Object Serialization our basic need is the Object .So where does the Object come from off course the class. So let’s quickly create a Employee class and create a few property for the class such as employees first name , last name and designation.[ Now you are getting the idea huh :D ] Look below to see what is done,

1

1

2

[Event handlers will be indicated with Orange colour balls]

Now that we have created some properties, let’s create Get and Set assessors for our properties. To serialize a Object, the class that the object derives from has to be Serializable hence we also add a [Serializable] attribute before the class declaration. You might catch my Idea on what I am talking if u see the below Picture.

1

2

3

Whole Source Code:

private void btnSerialize_Click(object sender, EventArgs e) { try { FileStream fStream = null; Employee emp1 = new Employee(); emp1.firstName = this.stxtfirstName.Text; emp1.lastName = this.stxtlastName.Text; emp1.designation = this.stxtDesignation.Text; BinaryFormatter bFormatter = new BinaryFormatter(); try { fStream = new FileStream("CodeCall.txt", FileMode.Create); bFormatter.Serialize(fStream, emp1); MessageBox.Show("Succesfully Serialized", "Done :)", MessageBoxButtons.OK, MessageBoxIcon.Information); this.stxtDesignation.Text = ""; this.stxtfirstName.Text = ""; this.stxtlastName.Text = ""; this.stxtfirstName.Focus(); } finally { fStream.Close(); } } catch (Exception ex) { MessageBox.Show("Something went wrong check the message below\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
No need to worry I will explain you the whole code in step by step process. So shall we start?

Step2:

Double click the ‘btnSerialize ‘will create a event handler for the click event that hand’s over 2 arguments Object that Invoked the event and the Arguments for the event

private void btnSerialize_Click(object sender, EventArgs e)
Basically this is what serialization in my Program is, we will take the input from the user in the Serializer group box. Then write these values to a File, when the user clicks the ‘btnDeserializer ‘we will use the file stream to read the values the user stored in the file and display it in the Deserializer group box. Doesn’t that sound easy? But our application may fail if it can’t create a file also can’t find the file to read from. That is the reason we use the below statement

try {
We tell the C Sharp compiler to try the code that is inside the try block, if any error occurs then execute what is inside the Catch block. Which is shown below?

catch (Exception ex) { MessageBox.Show("Something went wrong check the message below\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
The code above catches an Exception when the file was not able to create or when u don’t have Admin access to create a file. I just catch the exception [error message] ex then display that in a message box so that the user might know what went wrong during the process?. The message box has OK button, and an error icon. [Also a Video Tutorial on the same will be made so that this document is easy to follow]

FileStream fStream = null;
The above code creates a Variable of type ‘File Stream ‘file stream is used to write a File into some directory. Code just declares a variable of that type but does not instantiate the File Stream class.

Employee emp1 = new Employee(); emp1.firstName = this.stxtfirstName.Text; emp1.lastName = this.stxtlastName.Text; emp1.designation = this.stxtDesignation.Text;
For Object Serialization we need, Object thus we create an Instance of our Employee class [Object]. Let’s call the Object as ‘emp1 ‘for the sake of simplicity. User input from the textbox is then assigned to specific / respective properties of the employee object. [When u work with a win form application to reference variables, classes, etc declared in that form you need to specify with THIS keyword]

BinaryFormatter bFormatter = new BinaryFormatter(); try { fStream = new FileStream("CodeCall.txt", FileMode.Create);
I am really happy that you made it this far, the first line declares an Object called bFormatter of the Binary Formatter class. The binary formatter class provides the methods to serialize and Deserialize Objects. Then if you remember we had created an Object of File stream type at the start of the program go up a bit and see the code! This is the code where we have initialized the File Stream by telling it that Create a Filename called CodeCall.txt in the directory where executable resides, [now this is the reason we had to include it inside a try block, as file creation may cause errors if you are not an Administrator].

I want you to Digest the below code as much as possible because this is where all the action takes place. Here is series of steps that takes place, we pass the emp1 object as a parameter for the serialize method of the Binary Formatter class along with the file path into which the serialized data will be dumped. Then we greet the user that the process was successful and clear the textbox and other fields of the group box1.Finally we close the file handle opened by the file stream.

bFormatter.Serialize(fStream, emp1); MessageBox.Show("Succesfully Serialized", "Done :)", MessageBoxButtons.OK, MessageBoxIcon.Information); this.stxtDesignation.Text = ""; this.stxtfirstName.Text = ""; this.stxtlastName.Text = ""; this.stxtfirstName.Focus(); } finally { fStream.Close(); }

Whole Source Code for Deserialization:

private void btnDeserialize_Click(object sender, EventArgs e) { FileStream fStream = null; Employee emp1 = new Employee(); try { fStream = new FileStream("CodeCall.txt", FileMode.Open); BinaryFormatter bFotmatter = new BinaryFormatter(); try { emp1 = (Employee)bFotmatter.Deserialize(fStream); this.dtxtfirstName.Text = emp1.firstName; this.dtxtlastName.Text = emp1.lastName; this.dtxtDesignation.Text = emp1.designation; } finally { fStream.Close(); } } catch (Exception ex) { MessageBox.Show("An error occured Please check the message below\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }

I am pretty much sure you would understand what the hell is happening there, it is the deserialization code written under the ‘btnDeserializer ‘. Certain changes I need to explain here are below

fStream = new FileStream("CodeCall.txt", FileMode.Open);
Because we are deserializing we need the file from which to get the Object from, so we pass the path to the file and filemode.Since we need to read its FileMode.Open

Since the file contains the Object ‘ emp 1’ of the employee class we need to explicitly type cast the output from the file to the Object created before. Note that we call the Deserialize method and then pass the stream as the parameter that contains the file path and file mode.

emp1 = (Employee)bFotmatter.Deserialize(fStream);

Finally we replace the Values into the TextBox.

this.dtxtfirstName.Text = emp1.firstName; this.dtxtlastName.Text = emp1.lastName; this.dtxtDesignation.Text = emp1.designation;

Thanks for Reading this article, I will be making a Video in short time. No need to bother if this does not sink into your Huge Brains.

GokuJames for CodeCall

Sign up to vote on this title
UsefulNot useful