Solved

How to Serialize / Deserialize a Collection Object

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

820 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