Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Data Programming  »  XML  »  Serialization in .NET
Serialization in .NET
by Mark Butenko | Published  01/07/2004 | XML | Rating:
Mark Butenko

Marc Butenko is a Computer Systems Analyst for the Montana Department of Transportation, and writes applications for various engineering groups using Visual Basic .NET. He has a B.S. in Mechanical Engineering and a M.S. in Computer Science.

Marc's Visual Basic experience covers everything from VB4 (16-bit) to Visual Basic .NET and he enjoys beta testing software for major software companies. He says that it's always nice to find someone else's bugs and let them fix them, and gives him a great opportunity to get experience with a wide variety of software.

You can reach Mark at mbutenko@bresnan.net

 

View all articles by Mark Butenko...
Serialization in .NET

Article source code: dotnet_serialization.zip

Introduction

When developing smaller applications that do not have a database (or other formal storage mechanism) or data that doesn't need to be stored in a database (such as the state of a web application), you often still would like to save the data for later retrieval. There are many ways to do this, but many of them are subject to a lot of extra code (work) and extra time spent debugging. With .NET, there is now an easy way to add this functionality to your code with only a few lines of easily tested code. This easy way is called serialization.

Serialization is the process of storing an object, including all of its public and private fields, to a stream. Deserialization is the opposite – restoring an object's field values from a stream. The stream is generally in the form of a FileStream, but does not have to be. It could be a memory stream or any other object that is of type IO.Stream. The format can be anything from XML to binary to SOAP.

In this article, I will show the storage and retrieval of an object's state using both XML serialization and binary serialization. The others are very similar and simply require the use of a different serialization class.

The Basics

The basics of serialization are simple. You have to enable serialization for the object you want to serialize, create a serialization object to write the file and create a deserialization object to read the file.

This simple example uses two classes to make up the object type that we are going to serialize. Our classes for this example are:

<SERIALIZABLE< font>()> _
Public Class Employee
    Public Name As String
    Public ID As Integer
    <NONSERIALIZED< font>(), Serialization.XmlIgnore()> Public Salary As Single
    Public Position As String
End Class

<SERIALIZABLE< font>()> _
Public Class Employees
    Public Sub New()
    End Sub

    Public Sub New(ByVal NumberOfEmployees As Integer)
        ReDim Workers(NumberOfEmployees - 1)

        For i As Integer = 0 To NumberOfEmployees - 1
            Workers(i= New Employee
        Next
    End Sub

    Public Workers() As Employee
End Class

Note the use of the "Serializable" attribute. This tells the serialization object that these structures are allowed to be serialized. The "Serializable" attribute is not required when using XML serialization, but it is still a good idea to designate it.

We can also prevent a field from being serialized. This is useful when the field value has no specific meaning except in this instance of the application. The designation of a field with the "NonSerialized" (for binary serialization) or "Serialization.XMLIgnore" (for XML serialization) will prevent a field from being serialized. Since we are doing both binary and XML serialization, we have to apply both attributes.

Serializing our Object

To perform the serialization of our object only takes a few lines of code. We first must create a serializing object. In our case, this is an object created from the Serialization.XMLSerializer or BinaryFormatter class. We also create a stream (of type FileStream) in which to store the object. Then we call the Serialize method or our serializing object to do the work, then we close the stream.

The code looks like this:

'XML Serialization
Dim Serializer As New Serialization.XmlSerializer(GetType(Employees))
Dim DataFile As New FileStream("Sample.dat"FileMode.Create_
    FileAccess.WriteFileShare.None)

Serializer.Serialize(DataFileData)
DataFile.Close()
Data = Nothing

'Binary Serialization
Dim Serializer As New BinaryFormatter
Dim DataFile As New FileStream("Sample.bin"FileMode.Create_
    FileAccess.WriteFileShare.None)

Serializer.Serialize(DataFileData)
DataFile.Close()
Data = Nothing

The last line in both cases is merely to empty the instance of our data class to demonstrate that when we deserialize the stream into our object we are actually getting data from the file and not from something remaining in memory.

Notice also the inclusion of the following Imports statements at the top of the form:

Imports System.Xml
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization

Deserializing

To deserialize, the code is almost identical as the serialization code except we call the Deserialize method or the serialization object:

'XML Deserialization
Dim Deserializer As New Serialization.XmlSerializer(GetType(Employees))
Dim DataFile As New FileStream("Sample.dat"FileMode.Open_
    FileAccess.ReadFileShare.None)

Data = CType(Deserializer.Deserialize(DataFile), Employees)
DataFile.Close()

'Binary Deserialization
Dim Deserializer As New BinaryFormatter
Dim DataFile As New FileStream("Sample.bin"FileMode.Open_
    FileAccess.ReadFileShare.None)

Data = CType(Deserializer.Deserialize(DataFile), Employees)
DataFile.Close()

Running The Sample Solution

Now that we have reviewed how it is done, take a look at it in action.

Run the sample code and press the "Show Object Data" button. It will show the current contents of the Employees object that is loaded as part of the Form_Load event.

Now serialize the object using the "Serialize to XML" or "Serialize to Binary" buttons. Press the "Show Object Data" button and it will tell us the object is empty.

If we deserialize the stream, and press the "Show Object Data" button again we can see we have our data back. When running these examples, take note of the salary value. Since we designated this field to not be serialized, it is zero after deserializing.

Also, take a look at the two output files ("Sample.xml" and "Sample.bin"). These files could be used by other applications or reused by our application. The XML file, shown here, could easily be used by other applications or used to create an HTML page by applying an XSL style sheet:

<?xml version="1.0"?>
<EMPLOYEES xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <WORKERS>
    <EMPLOYEE>
      <NAME>Marc Butenko</NAME>
      <ID>1</ID>
      <POSITION>Computer Systems Analyst</POSITION>
    </EMPLOYEE>
    <EMPLOYEE>
      <NAME>Bill Gates</NAME>
      <ID>0</ID>
      <POSITION>CEO</POSITION>
    </EMPLOYEE>
    <EMPLOYEE>
      <NAME>John Doe</NAME>
      <ID>2</ID>
      <POSITION>Janitor</POSITION>
    </EMPLOYEE>
  </WORKERS>
</EMPLOYEES>

Summary

Other uses of the serialization object are also available. If we had chosen to serialize the object to a memory stream, we could then write the data to an encrypted file stream to prevent the data from being viewed by prying eyes.

Now that we have covered the basics of serialization, try experimenting with it using different serialization classes and attributes. I often use it in simple applications to provide a quick and easy data storage solution. Hopefully you have found this educational and enlightening and can make use of the material here in your applications.

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:4.04716981132076 out of 5
 106 people have rated this page
Article Score53382
Related Articles
Sponsored Links