I am going advanced this time with Serialization.But the tutorial is made very very simple so that anyone who has brains can follow them do download the attached document and read through when you get free time also if free read the tutorial and share your comments , Thanks .
Greetz to Davide , James.H , Jaan and all members.
title..PNG 4.05K
2456 downloads
Picture1..png 10.07K
2459 downloads [FONT="]What exactly is Serialization?[/FONT][FONT="]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.[/FONT]
Picture2..png 14.6K
2492 downloads[FONT="]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[/FONT][FONT="].[/FONT]
Picture3..png 13.82K
2469 downloads [FONT="]Use of Serialization:[/FONT][FONT="]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[/FONT]
Picture4..png 24.75K
2486 downloads [FONT="]How to Make an Object Serializable?[/FONT] [FONT="]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.[/FONT]
[FONT="]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.[/FONT]
[FONT="]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.[/FONT]
[FONT="]If a serialized class contains references to objects of other classes that are marked SerializableAttribute, those objects will also be serialized.[/FONT]
Picture5..png 17.31K
2491 downloads [FONT="]Binary and Xml Serialization[/FONT][FONT="]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[/FONT][FONT="].[/FONT]
Picture6..png 13.73K
2493 downloads [FONT="]Binary Serialization[/FONT] [FONT="]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.[/FONT]
Picture7..png 18.89K
2499 downloads [FONT="]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.[/FONT][FONT="]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[/FONT]
Picture8..png 8.72K
2473 downloads [FONT="]SOAP Serialization[/FONT][FONT="]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.[/FONT]
[FONT=Garfield]Binary Serialization: Visual C# 2.0 / 3.0[/FONT]
[FONT="]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.[/FONT]
[FONT="]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:[/FONT]
pic16..png 1.67K
2448 downloads[FONT="]1.[/FONT][FONT="] 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.[/FONT] [FONT="]So what are we waiting for let us start our program right away,[/FONT][FONT="]
[/FONT]
Picture14..png 3.25K
2462 downloads[FONT="]Programming and Explanation[/FONT][FONT=Garfield]Step1:[/FONT]
[FONT="]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.[/FONT]
[FONT="]Go to [/FONT][FONT="]File / New / Project [CTRL + SHFT + N][/FONT]
pic9..PNG 18.96K
2460 downloads[FONT="]This brings up the[/FONT][FONT="] new project Dialog Box shown below[/FONT]
pic10..PNG 83.62K
2474 downloads[FONT="]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.[/FONT]
[FONT=Garfield]Step 2:[/FONT]
[FONT="]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 [/FONT][FONT="]new project dialog box [/FONT][FONT="]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.[/FONT]
[FONT="]Info:[/FONT]
[FONT="]Name : Project Name[/FONT]
[FONT="]Solution Name : Name of the Solution the Project is in.[/FONT]
[FONT="]Now hit the Ok button indicated by ‘ 3’[/FONT]
pic11..PNG 33.75K
2467 downloads[FONT=Garfield]Step 3:[/FONT]
[FONT="] 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,[/FONT]
pic12..PNG 19.12K
2497 downloads[FONT=Garfield]UI Design:[/FONT]
[FONT="]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.[/FONT]
[FONT="]‘ 1 ’ is a group box control , ‘ 2 ‘ is also a group box, ‘ 3 ‘ is buttons[/FONT][FONT="] for which we will be coding[/FONT]
pic13..PNG 14.09K
2468 downloads
pic15..png 3.44K
2437 downloads[FONT="] Coding Our Program and User Interface[/FONT] [FONT="]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 , [/FONT]
[FONT="]Text: Serializer / Deserializer[/FONT]
[FONT="]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.[/FONT]
pic17..PNG 80.44K
2492 downloads[FONT="]Set the text of the form to Serializer / Deserializer.[/FONT]
pic18..PNG 5.39K
2440 downloads[FONT="]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[/FONT]
pic19..PNG 8.2K
2433 downloads[FONT="]The user interface we end up making in the following steps[/FONT]
Picture20..png 7.84K
2448 downloads[FONT="]First drag and drop a group box from the Toolbox onto the form in the [Design] view. Group box looks like below[/FONT][FONT="]
[/FONT]
Picture21..png 737bytes
2449 downloads[FONT="]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,[/FONT]
[FONT="]Group Box1:[/FONT]
[FONT="]Text : Serializer[/FONT]
[FONT="]TextBox1:[/FONT]
[FONT="]Name : stxtfirstname [ s represents textbox from Serializer group box ][/FONT]
[FONT="]Text : First Name[/FONT]
[FONT="]TextBox2:[/FONT]
[FONT="]Name:stxtlastname[/FONT]
[FONT="]Text :Last Name[/FONT]
[FONT="]TextBox3:[/FONT]
[FONT="]Name:sdesignation[/FONT]
[FONT="]Text : Designation[/FONT]
[FONT="]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. [/FONT]
[FONT="]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[/FONT]
[FONT="]Group Box2:[/FONT]
[FONT="]Text : Deserializer[/FONT]
[FONT="]TextBox4:[/FONT]
[FONT="]Name : dtxtfirstname [ d represents textbox from Deserializer group box ][/FONT]
[FONT="]Text : First Name[/FONT]
[FONT="]TextBox5:[/FONT]
[FONT="]Name:dtxtlastname[/FONT]
[FONT="]Text :Last Name[/FONT]
[FONT="]TextBox6:[/FONT]
[FONT="]Name:ddesignation[/FONT]
[FONT="]Text : Designation[/FONT]
[FONT="]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[/FONT]
[FONT="]Button1:[/FONT]
[FONT="]Name : btnSerialize[/FONT]
[FONT="]Text : Serialize[/FONT]
[FONT="]Button2:[/FONT]
[FONT="]Name : btnDeserialize[/FONT]
[FONT="]Text : Deserialize[/FONT]
[FONT="]Yes finally we are good to go to the Coding.[/FONT]
pic22..png 3.3K
26 downloads[FONT="]Source Code[/FONT][FONT="]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.[/FONT]
[FONT="]Scroll all the way up to the Using statements and add these Statements.[/FONT]
pic24..png 36.59K
2446 downloads[FONT="]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[/FONT]
[FONT="]Namespaces of Importance:[/FONT]
[FONT="]System.Runtime.Serialization.Formatters.Binary[/FONT]
[FONT="]System.IO[/FONT]
[FONT="]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 [/FONT][FONT="]System.IO [/FONT][FONT="]this namespace provides the [/FONT][FONT="]File Stream[/FONT][FONT="] class to convert a file into stream.[/FONT]
[FONT=Garfield]Step 1:[/FONT]
[FONT="]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 ][/FONT]
[FONT="]Look below to see what is done,[/FONT]
pic23..PNG 17.14K
2445 downloads[FONT="]Now that we have created some properties, let’s create[/FONT][FONT="] 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.[/FONT]
pic25..PNG 16.11K
2484 downloads[FONT="]Whole Source Code:[/FONT]
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);
}
}
[FONT="]No need to worry I will explain you the whole code in step by step process. So shall we start?[/FONT][FONT=Garfield]Step2:[/FONT]
[FONT="]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[/FONT]
private void btnSerialize_Click(object sender, EventArgs e)[FONT="]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 [/FONT][FONT="]may fail if it can’t create a file[/FONT][FONT="] also [/FONT][FONT="]can’t find the file to read from. [/FONT][FONT="]That is the reason we use the below statement[/FONT]
[COLOR=blue][FONT="]try[/FONT][/COLOR]
[FONT="] {
[/FONT][FONT="][/FONT]
[FONT="]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?[/FONT]
[COLOR=blue][FONT="]catch[/FONT][/COLOR][FONT="] ([COLOR=#2b91af]Exception[/COLOR] ex)[/FONT]
[FONT="] {[/FONT]
[FONT="] [COLOR=#2b91af]MessageBox[/COLOR].Show([COLOR=#a31515]"Something went wrong check the message below\n"[/COLOR] + ex.Message, [COLOR=#a31515]"Error"[/COLOR], [COLOR=#2b91af]MessageBoxButtons[/COLOR].OK, [COLOR=#2b91af]MessageBoxIcon[/COLOR].Error);[/FONT]
[FONT="] }
[/FONT][FONT="][/FONT]
[FONT="]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.[/FONT]
[FONT="][Also a Video Tutorial on the same will be made so that this document is easy to follow][/FONT]
[FONT="] FileStream fStream = null;[/FONT]
[FONT="]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 [/FONT][FONT="]does not instantiate the File Stream class.[/FONT]
[FONT="] [COLOR=#2b91af]Employee[/COLOR] emp1 = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]Employee[/COLOR]();[/FONT] [FONT="] emp1.firstName = [COLOR=blue]this[/COLOR].stxtfirstName.Text;[/FONT] [FONT="] emp1.lastName = [COLOR=blue]this[/COLOR].stxtlastName.Text;[/FONT] [FONT="] emp1.designation = [COLOR=blue]this[/COLOR].stxtDesignation.Text;[/FONT][FONT="]For Object Serialization we need, Object thus we create an Instance of our Employee class [Object]. Let’s call the Object as [/FONT][FONT="]‘emp1[/FONT][FONT="] ‘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 [/FONT][FONT="]to reference variables, classes, etc[/FONT][FONT="] declared in that form you need to specify with [/FONT][FONT="]THIS keyword[/FONT][FONT="]][/FONT]
[COLOR=#2b91af][FONT="]BinaryFormatter[/FONT][/COLOR][FONT="] bFormatter = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]BinaryFormatter[/COLOR]();[/FONT]
[FONT="] [COLOR=blue]try[/COLOR][/FONT]
[FONT="] {[/FONT]
[FONT="] fStream = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]FileStream[/COLOR]([COLOR=#a31515]"CodeCall.txt"[/COLOR], [COLOR=#2b91af]FileMode[/COLOR].Create);[/FONT]
[FONT="]I am really happy that you made it this far, the first line declares an [/FONT][FONT="]Object called bFormatter[/FONT][FONT="] of the [/FONT][FONT="]Binary Formatter class[/FONT][FONT="]. The [/FONT][FONT="]binary formatter class provides the methods[/FONT][FONT="] 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 [/FONT][FONT="]have initialized the File Stream[/FONT][FONT="] by telling it that [/FONT][FONT="]Create a Filename called CodeCall.txt in the directory where executable resides[/FONT][FONT="], [now this is the reason we had to include it [/FONT][FONT="]inside a try block[/FONT][FONT="], as file creation may cause errors if you are [/FONT][FONT="]not an Administrator[/FONT][FONT="]].[/FONT][FONT="]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 [/FONT][FONT="]pass the emp1 object as a parameter[/FONT][FONT="] for the [/FONT][FONT="]serialize method of the Binary Formatter class[/FONT][FONT="] along with the [/FONT][FONT="]file path into which the serialized data will be dumped[/FONT][FONT="]. Then we greet the user that the [/FONT][FONT="]process was successful and clear the textbox and other fields[/FONT][FONT="] of the group box1.[/FONT][FONT="]Finally we close the file handle opened by the file stream.[/FONT]
[FONT="]bFormatter.Serialize(fStream, emp1);[/FONT]
[FONT="] [COLOR=#2b91af]MessageBox[/COLOR].Show([COLOR=#a31515]"Succesfully Serialized"[/COLOR], [COLOR=#a31515]"Done :)"[/COLOR], [COLOR=#2b91af]MessageBoxButtons[/COLOR].OK, [COLOR=#2b91af]MessageBoxIcon[/COLOR].Information);[/FONT]
[FONT="] [COLOR=blue]this[/COLOR].stxtDesignation.Text = [COLOR=#a31515]""[/COLOR];[/FONT]
[FONT="] [COLOR=blue]this[/COLOR].stxtfirstName.Text = [COLOR=#a31515]""[/COLOR];[/FONT]
[FONT="] [COLOR=blue]this[/COLOR].stxtlastName.Text = [COLOR=#a31515]""[/COLOR];[/FONT]
[FONT="] [COLOR=blue]this[/COLOR].stxtfirstName.Focus();[/FONT]
[FONT="] }[/FONT]
[FONT="] [COLOR=blue]finally[/COLOR][/FONT]
[FONT="] {[/FONT]
[FONT="] fStream.Close();[/FONT]
[FONT="] }[/FONT]
[FONT="]Whole Source Code for Deserialization:[/FONT]
[COLOR=blue][FONT="]private[/FONT][/COLOR][FONT="] [COLOR=blue]void[/COLOR] btnDeserialize_Click([COLOR=blue]object[/COLOR] sender, [COLOR=#2b91af]EventArgs[/COLOR] e)[/FONT]
[FONT="] {[/FONT]
[FONT="] [COLOR=#2b91af]FileStream[/COLOR] fStream = [COLOR=blue]null[/COLOR];[/FONT]
[FONT="] [COLOR=#2b91af]Employee[/COLOR] emp1 = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]Employee[/COLOR]();[/FONT]
[FONT="] [COLOR=blue]try[/COLOR][/FONT]
[FONT="] {[/FONT]
[FONT="] fStream = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]FileStream[/COLOR]([COLOR=#a31515]"CodeCall.txt"[/COLOR], [COLOR=#2b91af]FileMode[/COLOR].Open);[/FONT]
[FONT="] [COLOR=#2b91af]BinaryFormatter[/COLOR] bFotmatter = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]BinaryFormatter[/COLOR]();[/FONT]
[FONT="] [COLOR=blue]try[/COLOR][/FONT]
[FONT="] {[/FONT]
[FONT="] emp1 = ([COLOR=#2b91af]Employee[/COLOR])bFotmatter.Deserialize(fStream);[/FONT]
[FONT="] [COLOR=blue]this[/COLOR].dtxtfirstName.Text = emp1.firstName;[/FONT]
[FONT="] [COLOR=blue]this[/COLOR].dtxtlastName.Text = emp1.lastName;[/FONT]
[FONT="] [COLOR=blue]this[/COLOR].dtxtDesignation.Text = emp1.designation;[/FONT]
[FONT="] }[/FONT]
[FONT="] [COLOR=blue]finally[/COLOR][/FONT]
[FONT="] {[/FONT]
[FONT="] fStream.Close();[/FONT]
[FONT="] }[/FONT]
[FONT="] }[/FONT]
[FONT="] [COLOR=blue]catch[/COLOR] ([COLOR=#2b91af]Exception[/COLOR] ex)[/FONT]
[FONT="] {[/FONT]
[FONT="] [COLOR=#2b91af]MessageBox[/COLOR].Show([COLOR=#a31515]"An error occured Please check the message below\n"[/COLOR] + ex.Message, [COLOR=#a31515]"Error"[/COLOR], [COLOR=#2b91af]MessageBoxButtons[/COLOR].OK, [COLOR=#2b91af]MessageBoxIcon[/COLOR].Error);[/FONT]
[FONT="] }[/FONT]
[FONT="] }[/FONT]
[FONT="] }[/FONT]
[FONT="]I am pretty much sure you would understand what the hell is happening there, it is the deserialization code written under the [/FONT][FONT="]‘btnDeserializer ‘. [/FONT][FONT="]Certain changes I need to explain here are below[/FONT][FONT="] fStream = [COLOR=blue]new[/COLOR] [COLOR=#2b91af]FileStream[/COLOR]([COLOR=#a31515]"CodeCall.txt"[/COLOR], [COLOR=#2b91af]FileMode[/COLOR].Open);[/FONT][FONT="]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 [/FONT][FONT="]FileMode.Open[/FONT]
[FONT="]Since the file contains the Object ‘ [/FONT][FONT="]emp 1’[/FONT][FONT="] 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.[/FONT]
[FONT="] emp1 = ([COLOR=#2b91af]Employee[/COLOR])bFotmatter.Deserialize(fStream);[/FONT][FONT="]Finally we replace the Values into the TextBox.[/FONT]
[FONT="] [COLOR=blue]this[/COLOR].dtxtfirstName.Text = emp1.firstName;[/FONT] [FONT="] [COLOR=blue]this[/COLOR].dtxtlastName.Text = emp1.lastName;[/FONT] [FONT="] [COLOR=blue]this[/COLOR].dtxtDesignation.Text = emp1.designation;[/FONT][FONT="]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.[/FONT]
gokuJames for Forum CodeCall
Also available here :
http://docs.google.c...rialization.pdf
and Here
http://www.scribd.co...q1773ygedw4z436
or you can download from attachment
Attached Files
Edited by gokuajmes, 27 March 2010 - 02:27 AM.


Sign In
Create Account



Back to top









