Solved

How to Serialize / Deserialize a Collection Object

Posted on 2011-02-26
3
687 Views
Last Modified: 2012-05-11
Hi,

Before I lose my mind here, what's wrong with this code.  The SaveCollection routine throws an exception saying that the class is not marked as Serializeable.  Nonsense.  The example in the book i got this from, doesn't even mark the class serializeable either.  I thought the whole point of using a Serializer function (bf.Serialize(fs, TheCollection)) was so that the arguments didn't need to be marked serializeable.  Anyhow, I marked that class as Serializable, and it still doesn't not work.

The LoadCollection routine can't be tested until there is a saved object first.

Please help before I resort to the "bottle"...
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary

Public Class Class_TriggerDatabase

    <Serializable()> _
    Public Class Data

        Public Structure TriggerInfo
            Dim UpperTriggerAction As String
            Dim UT3 As String
            Dim UT2 As String
            Dim UT1 As String
            Dim LT1 As String
            Dim LT2 As String
            Dim LT3 As String
        End Structure

        Public Triggers As Collection

        Public Sub New()
            Triggers = New Collection
        End Sub
    End Class

    Const FileName As String = "TriggerData.dat"

    Dim TheCollection As Data

    Dim FullPathFilename As String

    Public Sub New(ByVal PathName As String)
        Try
            FullPathFilename = PathName & "\" & FileName
            LoadCollection()
        Catch ex As Exception
        End Try
    End Sub

    Private Sub LoadCollection()
        Try
            Dim fs As FileStream = New FileStream(FullPathFilename, FileMode.Open)
            Dim bf As New BinaryFormatter()
            TheCollection = CType(bf.Deserialize(fs), Data)
            fs.Close()
        Catch ex As Exception
        End Try
    End Sub

    Public Sub SaveCollection()
        Try
            Dim fs As FileStream = New FileStream(FullPathFilename, FileMode.Create)
            Dim bf As New BinaryFormatter()
            bf.Serialize(fs, TheCollection)
            fs.Close()
        Catch ex As Exception
        End Try
    End Sub

    Public Function RetrieveTriggersForThisReportName(ByVal ReportName As String, ByRef TI As Data.TriggerInfo) As Boolean
        RetrieveTriggersForThisReportName = False
        Try
            If TheCollection.Triggers.Contains(ReportName) = True Then
                TI = DirectCast(TheCollection.Triggers.Item(ReportName), Data.TriggerInfo)
                RetrieveTriggersForThisReportName = True
            End If
        Catch ex As Exception
        End Try
    End Function

    Public Function SaveTriggersForThisReportName(ByVal ReportName As String, ByRef TI As Data.TriggerInfo) As Boolean
        SaveTriggersForThisReportName = False
        Try
            If TheCollection.Triggers.Contains(ReportName) Then
                TheCollection.Triggers.Remove(ReportName)
            End If
            TheCollection.Triggers.Add(TI, ReportName)
            SaveTriggersForThisReportName = True
        Catch ex As Exception
        End Try
    End Function
End Class

Open in new window

0
Comment
3 Comments
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 250 total points
ID: 34988697
Try marking the STRUCTURE INSIDE as Serializable as well:
<Serializable()> _
Public Class Data

    <Serializable()> _
    Public Structure TriggerInfo
        Dim UpperTriggerAction As String
        Dim UT3 As String
        Dim UT2 As String
        Dim UT1 As String
        Dim LT1 As String
        Dim LT2 As String
        Dim LT3 As String
    End Structure

    Public Triggers As Collection

    Public Sub New()
        Triggers = New Collection
    End Sub

End Class

Open in new window

0
 
LVL 12

Assisted Solution

by:omegaomega
omegaomega earned 250 total points
ID: 34988701
Hello, RobertFromSecretWeapons,

Actually, I can't see why you get the "not marked serializable" error either.  Since you are ignoring all errors in that routine you should see none.  

But aside of that, as you say, "the LoadCollection routine can't be tested until there is a saved object". Since LoadCollection fails in the class constructor, TheCollection will never be initialized and so will remain Nothing.  Attempting to serialize Nothing should give you an error, but not the error you mention, so I too am confused.

I would start by handling errors in your class methods instead of ignoring them, and also include some default code to initialize TheCollection when the de-serialization fails in the constructor.  And save a nip off the bottle for me.  ;-)

Cheers,
Randy
0
 

Author Closing Comment

by:RobertFromSecretWeapons
ID: 34992176
Hi Guys,

Well, you're both right.  

Idle_Mind, I've never seen ANY serialization example where a "double" serializeable attribute was needed.  But indeed, your suggestion did make a difference in this case. Stupid really.... Maybe it's because I am only serializing a portion of the class.

OmegaOmega, you are right too.  Before posting this thread, I was single stepping this code and saw the exceptions thrown even though there are print statements in the handlers.  I was actually initializing an empty collection early on, but somehow, that code branch got removed.

Thank-you both.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now