Click here to Skip to main content
13,556,972 members
Click here to Skip to main content
Articles » Languages » VB.NET » HowTo » Downloads

Stats

239.9K views
41 bookmarked
Posted 16 Jan 2004
Licenced

Serialize VB.NET objects without the events

, 26 Jan 2004
Serialize VB.NET objects that have event handlers attached to its events.
Module Startup


    Sub Main()

        ' Create the objects - one that raises an event and one that handles the event
        Dim objHandler As New ObjectThatCatchesEvents ' This type is NOT Serializable
        Dim objGoodRaiser As New GoodObjectThatRaisesEvents ' This type is Serializable
        Dim objBadRaiser As New BadObjectThatRaisesEvents ' This type is Serializable
        Dim objStream As System.IO.MemoryStream
        Dim objFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim objCollection As New SerializableCollectionWithEvents

        ' Attach the event handler
        AddHandler objGoodRaiser.NameChanged, AddressOf objHandler.NameChangedHandler
        AddHandler objBadRaiser.NameChanged, AddressOf objHandler.NameChangedHandler
        AddHandler objCollection.ObjectAdded, AddressOf objHandler.ObjectAddedHandler

        ' Add a few items to the collection
        objCollection.Add("Hello")
        objCollection.Add("is there anybody home?")

        ' Serialize the "bad" event raiser
        ' Serialization exception will be raised because
        ' objHandler is not serializable - note
        ' we did not intend to serialize objHandler
        objStream = New System.IO.MemoryStream
        Console.WriteLine("Attempting to serialize normal serializable object with event handlers attached")
        Try
            objFormatter.Serialize(objStream, objBadRaiser)
            Console.WriteLine("Sucessfully serialized Bad Raiser!")
        Catch ex As Exception
            Console.WriteLine("Error While trying to serialize Bad Raiser!: " & ex.Message)
        End Try

        ' Serialize the "good" event raiser
        objStream = New System.IO.MemoryStream
        Console.WriteLine("Attempting to serialize super serializable object with event handlers attached...")
        Try
            objFormatter.Serialize(objStream, objGoodRaiser)
            Console.WriteLine("Sucessfully serialized Good Raiser!")
        Catch ex As Exception
            Console.WriteLine("Error While trying to serialize good Raiser!: " & ex.Message)
        End Try

        ' Try deserializing it
        Console.WriteLine("Attempting to deserialize super serializable object...")
        objStream.Position = 0
        objGoodRaiser = Nothing
        Try
            objGoodRaiser = DirectCast(objFormatter.Deserialize(objStream), GoodObjectThatRaisesEvents)
            Console.WriteLine("Sucessfully deserialized Good Raiser!")
        Catch ex As Exception
            Console.WriteLine("Error While trying to deserialize good Raiser!: " & ex.Message)
        End Try

        ' Try serializing a class that doesn't inherit from SerializableObject, but
        ' still uses it's shared methods
        objStream = New System.IO.MemoryStream
        Console.WriteLine("Attempting to serialize collection...")
        Try
            objFormatter.Serialize(objStream, objCollection)
            Console.WriteLine("Sucessfully serialized collection!")
        Catch ex As Exception
            Console.WriteLine("Error While trying to serialize collection!: " & ex.Message)
        End Try

        ' Try deserializing it
        Console.WriteLine("Attempting to deserialize serializable collection...")
        objStream.Position = 0
        objCollection = Nothing
        Try
            objCollection = DirectCast(objFormatter.Deserialize(objStream), SerializableCollectionWithEvents)
            Console.WriteLine("Sucessfully deserialized collection!")

            Console.WriteLine("Collection contents:")
            ' Print out the contents of the collection
            For Each obj As Object In objCollection
                Console.WriteLine(obj.ToString)
            Next
            Console.WriteLine("End collection contents")
        Catch ex As Exception
            Console.WriteLine("Error While trying to deserialize collection!: " & ex.Message)
        End Try

        ' Wait to exit
        Console.WriteLine("Press enter to exit...")
        Console.ReadLine()

    End Sub

End Module

' Class that is serialized and raises events - this one raises and exception when serialized
<Serializable()> Public Class BadObjectThatRaisesEvents

    ' Event to be handled
    Public Event NameChanged As EventHandler

    ' Single field that is to be serialized
    Private mName As String = "My Name"
    Public Property Name() As String
        Get
            Return mName
        End Get
        Set(ByVal Value As String)
            mName = Value
            RaiseEvent NameChanged(Me, EventArgs.Empty)
        End Set
    End Property

End Class
' Class that is serialized and raises events - this one works
<Serializable()> Public Class GoodObjectThatRaisesEvents
    Inherits SerializableObject

    ' Add the default and de-serialization constructors
    Public Sub New()
        MyBase.New()
    End Sub
    Protected Sub New(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext)
        MyBase.New(info, context)
    End Sub

    ' Event to be handled
    Public Event NameChanged As EventHandler

    ' Single field that is to be serialized
    Private mName As String = "My Name"
    Public Property Name() As String
        Get
            Return mName
        End Get
        Set(ByVal Value As String)
            mName = Value
            RaiseEvent NameChanged(Me, EventArgs.Empty)
        End Set
    End Property

End Class

' Class that is not serialized and handles events
Public Class ObjectThatCatchesEvents


    Public Sub NameChangedHandler(ByVal sender As Object, ByVal e As System.EventArgs)
        Trace.WriteLine("Name Changed")
    End Sub

    Public Sub ObjectAddedHandler(ByVal sender As Object, ByVal e As System.EventArgs)
        Trace.WriteLine("Object Added")
    End Sub


End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Trev Hunter
Web Developer
Canada Canada
Currently a codemonkey that codes. Soon to be a fully-fledged monkey Wink | ;)

You may also be interested in...

Pro
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02-2016 | 2.8.180515.1 | Last Updated 27 Jan 2004
Article Copyright 2004 by Trev Hunter
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid