Solved

How to Serialize / Deserialize a Collection Object

Posted on 2011-02-26
3
690 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

867 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

12 Experts available now in Live!

Get 1:1 Help Now