Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Visual Basic Language » Serialization in VB and .net

Serialization in VB and .net

Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format.

Page Views : 15512
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Serialization
     
XML Serialization

Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format, in order to be stored for some later use. In other words, the object is "dehydrated" and put away until we need to use it again.

Some good uses for serialization/deserialization include:

  1. Storing user preferences in an object.
  2. Maintaining security information across pages and applications.
  3. Modification of XML documents without using the DOM.
  4. Passing an object from on application to another.
  5. Passing an object from one domain to another.
  6. Passing an object through a firewall as an XML string.

XML Serialization: It is limited that it can serialize only public members.
Required Namespace :

Imports System.Xml

Imports System.Xml.Serialization

Create XSD file from Class

Object instance into XML file
 
Create one web project and add Person.vb class file.

Imports System

Imports System.Xml

Imports System.Xml.Serialization

 

Namespace XMLSerialization

    ''' <summary>

    ''' Summary description for Person.

    ''' </summary>

    <XmlRoot("Class_Person")> _

    Public Class Person

        Private m_sName As String

        Private m_iAge As Integer

        Public Sub New()

        End Sub

        <XmlElement("Property_Name")> _

        Public Property Name() As String

            Get

                Return m_sName

            End Get

            Set(ByVal value As String)

                m_sName = value

            End Set

        End Property

        <XmlElement("Property_Age")> _

        Public Property Age() As Integer

            Get

                Return m_iAge

            End Get

            Set(ByVal value As Integer)

                m_iAge = value

            End Set

        End Property

        Public Function Hello() As String

            Return "Hi! My name is " + Name + " and I am " + Age.ToString() + " years old"

        End Function

        Public Function GoodBye() As String

            Return "So long"

        End Function

    End Class

End Namespace

[XMLRoot()] and [XMLElement()] these are the .net attributes and tell the serializer where the various members of this object will appear in the XML document and what they will be named. Without these, serialization cannot take place.

Dim objXmlSer As New XmlSerializer(GetType(Person))

Dim objLucky As New Person()

Dim objStrWrt As StreamWriter

objLucky.Name = "Myname"

objLucky.Age = 30

 

Response.Write(objLucky.Hello())

Response.Write(objLucky.GoodBye())

objStrWrt = New StreamWriter(Server.MapPath("abc.xml"))

objXmlSer.Serialize(objStrWrt, objLucky)

objStrWrt.Close()

First of al, we declare and instantiate an XMLSerializer object. The typeof() function describes what type of object it's going to be serializing. Then we assign Name and Age properties of the Person object. Then we used to see the output of that object by calling Hello() and GoodBye() functions. Then we initiates a StreamWriter object and that it will be writing to a file call abc.xml. We then call the Serialize() method of the XMLSerializer object and send it our person object to be serialized as well as the StreamWriter object so it will write the resulting XML to the file specified. Then we close the StreamWriter.
 
The Abc.Xml file is look like.

<Xml version="1.0" encoding="utf-8" ?>

<c- <Class_Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <Property_Name>TestProperty1 </Property_Name>

  <Property_Age>30</Property_Age>

  </Class_Person>

Create class object from XML file

XML file into Object instance.

Now, make some changes in your abc.xml file.

<xml version="1.0" encoding="utf-8" ?>

<Class_Person xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance">

 <Property_Name>TestProperty2</Property_Name>

  <Property_Age>32</Property_Age>

  </Class_Person>

First create instance of Person class. Next, we create an instance of StreamReader object and feed it the stored XML file. Then we instantiate the Person object by calling the deserialize() method of the XMLSerializer object. This method use the StreamReader object to read the content of the XML file. You have to explicitly casting the type to Person type.

Dim objDesPerson As New Person()

Dim objStrRdr As StreamReader

objStrRdr = New StreamReader(Server.MapPath("abc.xml"))

Dim objXmlSer As New XmlSerializer(GetType(Person))

objDesPerson = DirectCast(objXmlSer.Deserialize(objStrRdr), Person)

Response.Write(objDesPerson.Name)

Response.Write(objDesPerson.Age.ToString())

objStrRdr.Close()

Binary Serialization

Public Class Article

    Public sTitle As String

    Public sAuthor As String

    Public sText As String

End Class

Not much to this class, just a few string variables. Lets suppose that we need to write an instance of this call tout to disk. To do this, we can use binary serialization. This will create a binary file that can be read back in as an instance of Article. To do this, we will need to implement 2 methods GetObjectData and Overloaded Constructor.
 
It will requires following namespace:

Imports System.Runtime.Serialization

Imports System.Runtime.Serialization.Formatters.Binary

First we will make the class with serializable attribute and implements the ISerializable interface.
 
[Serializable()]

Public Class Articles

    Implements ISerializable

End Class

We have to implements GetObjectData method of ISerializable interface.

Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)

    info.AddValue("Title", sTitle)

    info.AddValue("Author", sAuthor)

    info.AddValue("Text", sText)

End Sub

This method will allow you to serialize the objects to disk. We could add any code in here that we wanted to customize the way the data is serialized.

Now we need a method to retrieve the data from a serialized object then we will use a overloaded constructor for this.

Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)

    sTitle = Convert.ToString(info.GetValue("Title", GetType(String)))

    sAuthor = Convert.ToString(info.GetValue("Author", GetType(String)))

    sText = Convert.ToString(info.GetValue("Text", GetType(String)))

End Sub

The empty constructor is added here so that you can create a new Article object without deserialized one.
 
Now we have a class that can be serialized and deserialized. For serializing this class we have to create methods like
 
Serializing the object

Public Sub serialize(ByVal fileName As String)

    Dim s As New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)

    Dim B As New BinaryFormatter()

    B.Serialize(s, Me)

    s.Close()

End Sub

Here first we create an instance of FileStream class which, will create file and open it in read and write mode. Next we create an instance of BinaryForamtter class. This class have Seralize method which take parameters FileStream and Instance which you want to serialize.
 
DeSerializing the object

Public Function deSerialize(ByVal fileName As String) As Articles

    Dim Fs As New FileStream(fileName, FileMode.Open, FileAccess.Read)

    Dim F As New BinaryFormatter()

    Dim s1 As Articles = DirectCast(F.Deserialize(Fs), Articles)

    Fs.Close()

    Return s1

End Function

Here again create an instance of BinaryFormatter. The method Deserialize() will take parameter of FileStream object which point to the binary file which you want to deserialize. You have to do explicit casting of Article type during Deserializing.
 
Create One Project For Serializing
 
Create one Articles.vb class file

Imports System

Imports System.IO

Imports System.Runtime.Serialization

Imports System.Runtime.Serialization.Formatters.Binary

Namespace BinarySerialization

    <Serializable()> _

    Public Class Articles

        Implements ISerializable

        Public sTitle As String

        Public sAuthor As String

        Public sText As String

 

        Public Sub New()

        End Sub

        Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)

            sTitle = Convert.ToString(info.GetValue("Title", GetType(String)))

            sAuthor = Convert.ToString(info.GetValue("Author", GetType(String)))

            sText = Convert.ToString(info.GetValue("Text", GetType(String)))

        End Sub

        Public Sub serialize(ByVal fileName As String)

            Dim s As FileStream

            s = New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)

            Dim B As New BinaryFormatter()

            B.Serialize(s, Me)

            s.Close()

        End Sub

        Public Function deSerialize(ByVal fileName As String) As Articles

            Dim Fs As New FileStream(fileName, FileMode.Open, FileAccess.Read)

            Dim F As New BinaryFormatter()

            Dim s1 As Articles = DirectCast(F.Deserialize(Fs), Articles)

            Fs.Close()

            Return s1

        End Function

#Region "ISerializable Members"

 

        Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)

            info.AddValue("Title", sTitle)

            info.AddValue("Author", sAuthor)

            info.AddValue("Text", sText)

        End Sub

#End Region

    End Class

End Namespace

Create one webForm1.aspx page for testing the binary serialization.

'Binary Serialization of the object

Dim c1 As New Articles()

c1.sTitle = "My Title"

c1.sAuthor = "Author Name"

c1.sText = "This is my Text"

c1.serialize("C:\123.txt")

 

'deserialization of the object

Dim c2 As Articles = c1.deSerialize("C:\123.txt")

Response.Write(c2.sTitle)

Response.Write(c2.sAuthor)

Response.Write(c2.sText)

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# Corner (http://www.c-sharpcorner.com/).

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Nimesh Patel
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
A question by Rodrigo On June 17, 2009

¿And how about the Nothing (Null) elements cast to Integer values when deserialize a xml?

Example

if the element is defined as Integer or double, an exception is thrown

<ages>
  <age>10</age>
  <age>3</age>
  <age/>
  <age/>
</ages>


Any work about this?

Thanks in advantage.

 

Reply | Email | Modify 
Not getting correct output when using serialize() to write to a text file by Ahmad On May 25, 2010
Hi,

I am using serialize () to write to a text file. I am passing serializable class object & an input file stream as parameters but when i open the text file i get a junky display containing some portion of input correct . Please have look at the output below.
********************************************
    ÿÿÿÿ          CSerialFiling, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null   SerialFiling.CRecord   maccount
mfirstname    mlastname        

************************************

any suggestions how to correct this issue?

Thanks.

Reply | Email | Modify 
Re: Not getting correct output when using serialize() to write to a text file by John On June 24, 2010
That's how it's supposed to look. The deserialize function is what is able to read that garbled mess. But that is what serializing it does, converts it to binary or xml data.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.