Page 1 of 1

Serialization in VB.NET Putting a purpose to possibly the most powerful function in .net. Rate Topic: -----

#1 Asscotte  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 35
  • View blog
  • Posts: 610
  • Joined: 08-February 09

Posted 15 March 2010 - 01:37 PM

Serialization is basically turning a; Class, structure or even an object into something else. There are two main ways to do this in VB.NET; XML and Binary. So now you are probably wondering what you can do with such a powerful way to save data easily. Well if you follow this tutorial I will show you.

Okay first you need to create a new Win Forms project, and add a few different data stores, like a; Picture Box, Textbox, and whatever else you want. (You need to be able to load data into each of these.

When you have finished that create a new class called 'MyFileType'. The code I have placed below is a rough guide change it to support whatever data types you have on your form.

<Serializable()>Public Class MyFileType

Public frm_Picture as system.drawing.bitmap = nothing
Public frm_SomeTextbox as string = string.empty
Public frm_SomeWierdBoolean as boolean = new boolean
Public EnumThing as new CountingToInfinity 

Public Enum CountingToInfinity
One = 1
Two = 2
Three = 3
Four = 4
Infinity = 5
End Enum

End Class



The most important part of this code is the '<Serializable()>' tag, without it we could not perform any magic at all. Basically it tells the compiler that this that any data contained in one of these objects can be freely manipulated. If you were going to use this kind of set-up seriously you would use Property's, wouldn't you.

Okay now for the real heart and soul of this code, because some of the best examples of this are on the web already, I will show case them.

XML Serialization:
In this code there are two different ways of doing it, the later is better as you can have fun with various strings rather than writing the whole thing to disk and then picking it up later.

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

Public Class XML_Control

#Region " Write to file "
    ''' <summary>
    ''' Writes XML to file
    ''' </summary>
    ''' <param name="_object"></param>
    ''' <param name="Location"></param>
    ''' <param name="Overwrite"></param>
    ''' <remarks></remarks>
    Public Sub WriteXMLSeri_ToFile(ByVal _object As Object, ByVal Location As String, Optional ByVal Overwrite As Boolean = True)
        If IO.File.Exists(Location) Then
            If Overwrite = True Then
                IO.File.Delete(Location)
            End If
        End If

        'Serialize object to a text file.
        Dim objStreamWriter As New StreamWriter(Location)
        Dim x As New XmlSerializer(_object.GetType)
        x.Serialize(objStreamWriter, Location)
        objStreamWriter.Close()
    End Sub
#End Region

#Region " Read from files "
    ''' <summary>
    ''' Reads XML from a file
    ''' </summary>
    ''' <param name="location"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetXML_File(ByVal location As String) As Object
        'Deserialize text file to a new object.
        Dim objStreamReader As New StreamReader(location)
        Dim p2 As New <YourType>
        Dim x As Xml.Serialization.XmlSerializer
        p2 = x.Deserialize(objStreamReader)
        objStreamReader.Close()
        Return p2
    End Function
#End Region

#Region " Write + Read to XML string"

    ''' <summary>
    ''' Returns the set of included namespaces for the serializer.
    ''' </summary>
    ''' <returns>
    ''' The set of included namespaces for the serializer.
    ''' </returns>
    Public Shared Function GetNamespaces() As XmlSerializerNamespaces
        Dim ns As XmlSerializerNamespaces
        ns = New XmlSerializerNamespaces()
        ns.Add("xs", "http://www.w3.org/2001/XMLSchema")
        ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance")
        Return ns
    End Function


    Public Shared ReadOnly Property TargetNamespace() As String
        Get
            Return "http://www.w3.org/2001/XMLSchema"
        End Get
    End Property



    Public Shared Function ToXml(ByVal Obj As Object, ByVal ObjType As System.Type) As String
        Dim ser As XmlSerializer
        ser = New XmlSerializer(ObjType, TargetNamespace)
        Dim memStream As MemoryStream
        memStream = New MemoryStream()
        Dim xmlWriter As XmlTextWriter
        xmlWriter = New XmlTextWriter(memStream, Encoding.UTF8)
        xmlWriter.Namespaces = True
        ser.Serialize(xmlWriter, Obj, GetNamespaces())
        xmlWriter.Close()
        memStream.Close()
        Dim xml As String
        xml = Encoding.UTF8.GetString(memStream.GetBuffer())
        xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)))
        xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1))
        Return xml
    End Function


    Public Shared Function FromXml(ByVal Xml As String, ByVal ObjType As System.Type) As Object
        Dim ser As XmlSerializer
        ser = New XmlSerializer(ObjType)
        Dim stringReader As StringReader
        stringReader = New StringReader(Xml)
        Dim xmlReader As XmlTextReader
        xmlReader = New XmlTextReader(stringReader)
        Dim obj As Object
        obj = ser.Deserialize(xmlReader)
        xmlReader.Close()
        stringReader.Close()
        Return obj
    End Function
#End Region

End Class




Both methods use .net to do the actual serialization work, and other than that they are pretty similar one method just changes the input and output into a string. I also advise on using XML a large amount of the time as it is a global programming standard rather than using the next method which is just a binary blob. Also some classes and structures have trouble being serialized into binary whereas there are very few problems with XML. (Provided you do it right).

The Binary Method:
This code is by Aeonhack, and can be found here.

    'Author: Aeonhack

    'Notes:
    'Imports System.Runtime.Serialization.Formatters.Binary
    '
    'Toggle just about any object to and from a byte() array using
    'these two simple methods.

    'Sample Usage:

    '<Serializable()> Class Customer
    '    Public First, Last As String, Age As Integer
    '    Sub New(ByVal _first As String, ByVal _last As String, ByVal _age As Integer)
    '        First = _first : Last = _last : Age = _age
    '    End Sub
    'End Class

    'Serialize our object, converting it into a byte array. After this
    'process is complete you may do some of the following things to it:
    'encrypt, compress, and/or write it to the HDD.

    'Dim Data = Serialize(New Customer("John", "Connor", 19))

    'This is not limited to custom classes, you could use it on things
    'such as strings, arrays, controls, forms, or anything
    'that has the <Serializable()> attribute applied to it.

    'If you want to get your object back into it's original state we
    'simply pass the "(Of Type)(Data())" to our Deserialize function.

    'Dim John = Deserialize(Of Customer)(Data)

    Shared Function Serialize(ByVal data As Object) As Byte()
        If TypeOf data Is Byte() Then Return data
        Using M As New IO.MemoryStream : Dim F As New BinaryFormatter : F.Serialize(M, data) : Return M.ToArray() : End Using
    End Function
    Shared Function Deserialize(Of T)(ByVal data As Byte()) As T
        Using M As New IO.MemoryStream(data, False) : Return CType((New BinaryFormatter).Deserialize(M), T) : End Using
    End Function



As I have said the binary method is a tad unreliable, but still a rock hard method and very good if you don't know where your 'file' is going.

Also on another note; these methods of serialization are not limited to the file system, you can use it everywhere, those who have read my P2P tutorial may have realised that I have used it slightly there. Serialization is a huge benefit and saves people from creating file types with split constants, which you see very often. Most of the time it is due to the lack of a suitable file container.

Remember that with large blobs of data this is very memory intensive and requires a separate thread.

If you want more information on XML serialization and other tags you can add to you code to give different XML affects click here.

Enjoy your new found coding skill :) ,

Is This A Good Question/Topic? 4
  • +

Replies To: Serialization in VB.NET

#2 motcom  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 290
  • View blog
  • Posts: 1,371
  • Joined: 16-June 08

Posted 07 June 2010 - 01:46 PM

Nice one Asscote, i never bothered to look at the word "serialization" but your first few sentences made absolute sense...

I had to work with things like this before and never understood what it's all about, it remembers me what we used to do in turbo C++ ages ago..

It was not exactly the same, but similar...

Thanks for that one...
Was This Post Helpful? 0
  • +
  • -

#3 sougias  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 28-October 09

Posted 08 June 2010 - 07:46 AM

If we wont to delete an entry from the xml file how we can do that.?
Was This Post Helpful? 0
  • +
  • -

#4 citricube  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 73
  • Joined: 21-January 08

Posted 03 May 2012 - 11:52 AM

Thank you, this is exactly what I was looking for! :bananaman:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1