Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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.

Total page views :  7026
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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/).


Login to add your contents and source code to 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.