< C# Binary SOAP Program Example | Main | C++ Binary Socket Client-Server Program Example >

 


 

Chapter 4 Part 4:

Serialization

 

 

What do we have in this chapter 4 Part 4?

  1. VB .NET Binary SOAP Program Example

 

 

VB .NET Binary SOAP Program Example

 

Create a new empty VB .NET project.

 

VB .NET Binary SOAP Program Example - creating a new empty project using VS 2008

 

Add a class named MyBasicData.

 

VB .NET Binary SOAP Program Example - adding a new item into existing project

 

VB .NET Binary SOAP Program Example - adding a new class into existing project

 

Add the following codes.

 

' This sample illustrates the different binary and SOAP serialization methods. This

' sample illustrates using the IFormatter interface along with the BinaryFormatter

' and the SoapFormatter classes. Additionally, this sample illustrates simple

' serialization as well as selective and custom serialization. The sample illustrates

' both serialization and deserialization from a file. Note however, a serialized

' file can only be deserialized using the same flags. That is if the custom flag

' "/custom" was specified during serialization, it must also be present when

' deserialized.

'

' Usage:

'      usage: executable_file_name.exe [/file outfile.bin] [/soap | /binary] [/deserialize | /serialize]

'                        [/simple | /selective | /custom]

'      /file    filename        Filename to serialize to or deserialize from [default = binary.bin]

'      /soap                    Serialize data to SOAP format

'      /binary                  Serialize data to binary format [default]

'      /deserialize             Deserialize data from file

'      /serialize               Serialize data to file [default]

'      /simple                  Serialize a simple data structure

'      /selective               Serialize a selective data structure

'      /custom                  Serialize a custom data structure

'

' Sample usage:

'      Basic binary serialization:

'          executable_file_name.exe /binary /serialize /simple /file simple.bin

'      Basic binary deserialization:

'          executable_file_name.exe /binary /deserialize /simple /file simple.bin

'      Custom SOAP serialization:

'          executable_file_name.exe /soap /serialize /selective /file selective.soap

'      Custom SOAP deserialization:

'          executable_file_name.exe /soap /deserialize /selective /file selective.soap

'

Imports System

Imports System.IO

Imports System.Runtime.Serialization

Imports System.Runtime.Serialization.Formatters.Binary

' Imports System.Runtime.Serialization.Formatters.Soap - obsolete before 3.5

Imports System.Net

Imports System.Net.Sockets

 

'This is a simple class to illustrate binary serialization. It contains both

'public and private fields.

<Serializable()> _

Class MyBasicData

    Public IntField1 As Integer

    Public StringField1 As String

    Private IntField2 As Integer

 

    ' Constructor for MyBasicData that initializes member variables.

    Public Sub New()

        IntField1 = 1066

        StringField1 = "Basic Data Info"

        IntField2 = 1492

    End Sub

 

    ' Simple routine to display the values of each member variable.

    Public Sub Print()

        Console.WriteLine("MyBasicData.IntField1    = {0}", IntField1.ToString())

        Console.WriteLine("MyBasicData.StringField1 = {0}", StringField1)

        Console.WriteLine("MyBasicData.IntField2    = {0}", IntField2.ToString())

    End Sub

End Class

 

' This class shows how to set the NonSerialized attribute on a class property

'such that it will not appear in the serialized output.

<Serializable()> _

Class MySelectiveData

 

    Public UserId As Integer

    Public UserName As String

 

    <NonSerialized()> Private Password As String

 

    ' Constructor for MySelectiveData to initialize member variables.

    Public Sub New()

        UserId = 100

        UserName = "Joe User"

        Password = "DefaultPassword"

    End Sub

 

    ' Simple routine to display the contents of the MySelectiveData class

    Public Sub Print()

        Console.WriteLine("MySelectiveData.UserId   = {0}", UserId.ToString())

        Console.WriteLine("MySelectiveData.UserName = {0}", UserName)

        Console.WriteLine("MySelectiveData.Password = {0}", Password)

    End Sub

 

    ' Method for setting the current password.

    Public Sub SetPassword(ByVal newpassword As String)

        Password = newpassword

    End Sub

End Class

 

' This class shows how to customize the binary serialization process by implementing

' the ISerializable interface.

<Serializable()> _

Public Class MyCustomData

    Implements ISerializable

 

    Public IntField1 As Integer

    Public StringField1 As String

    <NonSerialized()> Public LocalAddress As IPAddress

 

    ' Constructor for MyCustomData that initialized the member variables.

    Public Sub New()

        IntField1 = 106

        StringField1 = "ISerializable custom serialization"

        LocalAddress = IPAddress.Parse("1.2.3.4")

    End Sub

 

    ' Simple print routine for displaying the member fields of the MyCustomData class.

    Public Sub Print()

        Console.WriteLine("MyCustomData.IntField1    = {0}", IntField1.ToString())

        Console.WriteLine("MyCustomData.StringField1 = {0}", StringField1)

        Console.WriteLine("MyCustomData.LocalAddress = {0}", LocalAddress.ToString())

    End Sub

 

    ' Method called when the object is serialized. Each member property to be

    ' serialized is assigned as string key name. This will be used in the custom

    ' constructor to retrieve the value for each property when deserialization

    ' takes place

    ' <param name="info">

    ' Contains serialization context information for each property

    ' to be serialized.

    ' </param>

    ' <param name="context">

    ' Describes the source and destination of a given serialized stream

    ' </param>

    Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) Implements ISerializable.GetObjectData

        info.AddValue("IntField1", IntField1)

        info.AddValue("whatever", StringField1)

    End Sub

 

    ' Custom constructor that is called when the object is deserialized such that

    ' it can retrieve the values for properties by using the keys assigned to each.

    ' It can also initialize other properties as desired.

    ' <param name="info"></param>

    ' <param name="context"></param>

    Private Sub New(ByVal info As SerializationInfo, ByVal c As StreamingContext)

        Dim ipHost As IPHostEntry

 

        IntField1 = info.GetInt32("IntField1")

        StringField1 = info.GetString("whatever")

 

        ' Since we don't retrieve the LocalAddress property (and since it wasn't

        ' serialized to begin with, we find the local IP address and initialize

        ' it to that.

        Try

            ipHost = Dns.GetHostEntry("127.0.0.1")

            If (ipHost.AddressList.Length > 0) Then

                LocalAddress = ipHost.AddressList(0)

            Else

                LocalAddress = IPAddress.Loopback

            End If

        Catch err As System.Net.Sockets.SocketException

            LocalAddress = IPAddress.Loopback

        End Try

    End Sub

End Class

 

' Simple enumeration for the different types of serialization supported.

Enum SerializeType

    useBinary = 0

    useSoap = 1

End Enum

 

' Simple enumeration for the operation to perform: de-serialization or serialization.

Enum SerializeOperation

    opRead = 0

    opWrite = 1

End Enum

 

' Simple enumeration for the class type to serialize or deserialize.

Enum SerializeDataType

    typeSimple = 0

    typeSelective = 1

    typeCustom = 2

End Enum

 

' Main class that contains the the Main routine for this sample.

Class BinarySerialization

 

    ' Displays usage information for this sample.

    Shared Sub Usage()

        Console.WriteLine("Usage: executable_file_name.exe [/file outfile.bin] [/soap | /binary] [/deserialize | /serialize]")

        Console.WriteLine("                  [/simple | /selective | /custom]")

        Console.WriteLine("    /file    filename        Filename to serialize to or deserialize from [default = binary.bin]")

        Console.WriteLine("    /soap                    Serialize data to SOAP format")

        Console.WriteLine("    /binary                  Serialize data to binary format [default]")

        Console.WriteLine("    /deserialize             Deserialize data from file")

        Console.WriteLine("    /serialize               Serialize data to file [default]")

        Console.WriteLine("    /simple                  Serialize a simple data structure")

        Console.WriteLine("    /selective               Serialize a selective data structure")

        Console.WriteLine("    /custom                  Serialize a custom data structure")

        Console.WriteLine()

        Console.WriteLine("Sample(Usage)")

        Console.WriteLine("1. Basic binary serialization:")

        Console.WriteLine("     executable_file_name.exe /binary /serialize /simple /file simple.bin")

        Console.WriteLine("2. Basic binary deserialization:")

        Console.WriteLine("     executable_file_name.exe /binary /deserialize /simple /file simple.bin")

        Console.WriteLine("3. Custom SOAP serialization:")

        Console.WriteLine("     executable_file_name.exe /soap /serialize /selective /file selective.soap")

        Console.WriteLine("4. Custom SOAP deserialization:")

        Console.WriteLine("     executable_file_name.exe /soap /deserialize /selective /file selective.soap")

    End Sub

 

    ' Main function which parses the command line, creates the data to

    ' serialize, creates the file stream, and either serializes or

    ' deserializes the data. If deserialization is chosen, the member

    ' fields of the deserialized class are printed to the console.

    Shared Sub Main()

        Dim fileStream As Stream

        Dim myFormatter As IFormatter

        Dim fileName As String = "binary.bin"

        Dim serializationType As SerializeType = SerializeType.useBinary

        Dim serializeOp As SerializeOperation = SerializeOperation.opWrite

        Dim dataType As SerializeDataType = SerializeDataType.typeSimple

 

        ' Parse the command line

        Dim args As String() = Environment.GetCommandLineArgs()

        Dim i As Integer

 

        For i = 1 To args.Length - 1

            If args(i) = "/file" Then

                Try

                    i = i + 1

                    fileName = args(i)

                Catch err As System.IndexOutOfRangeException

                    Console.WriteLine("Please specify output filename!\n")

                    Usage()

                End Try

            ElseIf args(i) = "/binary" Then

                serializationType = SerializeType.useBinary

            ElseIf args(i) = "/soap" Then

                serializationType = SerializeType.useSoap

            ElseIf args(i) = "/deserialize" Then

                serializeOp = SerializeOperation.opRead

            ElseIf args(i) = "/serialize" Then

                serializeOp = SerializeOperation.opWrite

            ElseIf args(i) = "/simple" Then

                dataType = SerializeDataType.typeSimple

            ElseIf args(i) = "/selective" Then

                dataType = SerializeDataType.typeSelective

            ElseIf args(i) = "/custom" Then

                dataType = SerializeDataType.typeCustom

            Else

                Usage()

                Exit Sub

            End If

        Next

 

        ' Create the appropriate file stream - to write to or read from.

        If serializeOp = SerializeOperation.opWrite Then

            fileStream = New FileStream( _

                        fileName, _

                        FileMode.Create, _

                        FileAccess.Write, _

                        FileShare.None _

                        )

        Else

            fileStream = New FileStream( _

                        fileName, _

                        FileMode.Open, _

                        FileAccess.Read, _

                        FileShare.None _

                        )

        End If

 

        ' Create the formatter - binary or SOAP.

        If ((serializationType = SerializeType.useBinary) Or (serializationType = SerializeType.useSoap)) Then

            myFormatter = New BinaryFormatter()

        End If

 

        ' Perform the selected operation: read or write

        If serializeOp = SerializeOperation.opWrite Then

 

            ' Create an instance of the selected class and serialized it to the file stream

            If dataType = SerializeDataType.typeSimple Then

                Dim basicData As MyBasicData

 

                basicData = New MyBasicData()

 

                ' Set field to something other than the constructor default value

                basicData.IntField1 = 999

 

                Console.WriteLine("Simple data being serialized:")

                basicData.Print()

 

                ' Serialize the data to the stream

                Try

                    myFormatter = New BinaryFormatter()

                    myFormatter.Serialize(fileStream, basicData)

                Catch err As System.Runtime.Serialization.SerializationException

                    Console.WriteLine("Simple serialization failed: " + err.Message)

                End Try

 

            ElseIf dataType = SerializeDataType.typeSelective Then

                Dim selectiveData As MySelectiveData

 

                selectiveData = New MySelectiveData()

 

                ' Set field to something other than the constructor default value

                selectiveData.SetPassword("abcd1234")

 

                Console.WriteLine("Selective data being serialized:")

                selectiveData.Print()

 

                ' Serialize the date to the stream

                Try

                    myFormatter = New BinaryFormatter()

                    myFormatter.Serialize(fileStream, selectiveData)

                Catch err As System.Runtime.Serialization.SerializationException

                    Console.WriteLine("Selective serialization failed: " + err.Message)

                End Try

 

            Else 'SerializeDataType.typeCustom

                Dim customData As MyCustomData

 

                customData = New MyCustomData()

 

                ' Set field to something other than the constructor default value

                customData.IntField1 = 888

 

                Console.WriteLine("Custom data being serialized:")

                customData.Print()

 

                Try

                    myFormatter = New BinaryFormatter()

                    myFormatter.Serialize(fileStream, customData)

                Catch err As System.Runtime.Serialization.SerializationException

                    Console.WriteLine("Custom serialization failed: " + err.Message)

                End Try

            End If 'SerializeDataType

        Else 'SerializeOperation.opRead

 

            ' Deserialize the selected class from the file stream

            If dataType = SerializeDataType.typeSimple Then

                Dim basicData As MyBasicData

 

                Try

                    myFormatter = New BinaryFormatter()

                    basicData = myFormatter.Deserialize(fileStream)

                    basicData.Print()

                Catch err As System.Runtime.Serialization.SerializationException

                    Console.WriteLine("Deserialization failed: " + err.Message)

                End Try

 

            ElseIf dataType = SerializeDataType.typeSelective Then

                Dim selectiveData As MySelectiveData

 

                Try

                    myFormatter = New BinaryFormatter()

                    selectiveData = myFormatter.Deserialize(fileStream)

                    selectiveData.Print()

                Catch err As System.Runtime.Serialization.SerializationException

                    Console.WriteLine("Deserialization failed: " + err.Message)

                End Try

 

            Else 'SerializeDataType.typeCustom

                Dim customData As MyCustomData

 

                Try

                    myFormatter = New BinaryFormatter()

                    customData = myFormatter.Deserialize(fileStream)

                    customData.Print()

                Catch err As System.Runtime.Serialization.SerializationException

                    Console.WriteLine("Deserialization failed: " + err.Message)

                End Try

            End If 'SerializeDataType

        End If 'SerializeOperation

        fileStream.Close()

    End Sub

End Class

 

Next, change the Application type: to Console Application and Startup object: to Sub Main.

 

VB .NET Binary SOAP Program Example - invoking the project's property page  

 

VB .NET Binary SOAP Program Example - changing the application type from DLL to EXE and setting the startup to Main() subroutine

 

Build and run the program. The following are sample outputs when run at the command prompt.

 

VB .NET Binary SOAP Program Example - a sample output without any arguments

 

VB .NET Binary SOAP Program Example - sample outputs with different arguments

 

Note: Beginning with the .NET Framework version 3.5, the SoapFormatter class is obsolete. Use the BinaryFormatter instead.

 

 

 


 

< C# Binary SOAP Program Example | Main | C++ Binary Socket Client-Server Program Example >