5,545,925 members and growing! (16,574 online)
Email Password   helpLost your password?
Languages » C / C++ Language » General     Intermediate

Serialize custom collections of CollectionBase

By eschneider100

Basic demo on how to serialize and deserialize custom collections
VB, Windows, .NET 1.1, .NETVisual Studio, VS.NET2003, Dev

Posted: 11 Jan 2004
Updated: 15 Jan 2004
Views: 73,096
Bookmarked: 15 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
13 votes for this Article.
Popularity: 2.75 Rating: 2.47 out of 5
6 votes, 46.2%
1
2 votes, 15.4%
2
1 vote, 7.7%
3
1 vote, 7.7%
4
3 votes, 23.1%
5

Introduction

This is a simple demo on how to serialize and deserialize custom collections, while handling derived collection items. This version also demos, serialize, deserialize of unknown derived types of cItem (see Eitem class).

Background

I wanted to be able to serialize using collections rather than arrays, allowing better type checking.

Using the code

This page does not display all the code, but the basic structure. Download the application for a demo on usage of the objects.
'-----------------------------------------

'The abstract item

'

'NOTE: Notice the attributes on the Citem, these are all the 

'derived types we plan to use in the collection

'

Option Explicit On 
Option Strict On

Imports System.Xml.Serialization

'NOTE: If you derrive from this clas, then add a

'XmlInclude attribute for the new class!


< _
XmlInclude(GetType(Yitem)), _
XmlInclude(GetType(XItem)), _
Serializable() _
> _
Public Class Citem
  Private m_Id As Integer
  Private m_Data As String

  Public Property Id() As Integer
     Get
        Return m_Id
     End Get
     Set(ByVal value As Integer)
        m_Id = value
     End Set
  End Property

  Public Property Data() As String
     Get
        Return m_Data
     End Get
     Set(ByVal value As String)
        m_Data = value
     End Set
  End Property

End Class


'-------------------------------------------

'derrived collection item

'This one has an extra property for the demon

'to show differences in XML output

'

Option Explicit On 
Option Strict On

Public Class XItem
    Inherits cItem

    Private m_D As Double

    Public Property D() As Double
        Get
            Return m_D
        End Get
     Set(ByVal value As Double)
        m_D = Value
     End Set
  End Property
End Class


'-----------------------------------------------

'derrived collection item

'

Option Explicit On 
Option Strict On

Public Class Yitem
    Inherits cItem

End Class


'--------------------------------------------

'derrived collection item


'NOTE: XmlInclude attribute is not included on cItem,

'This was done to demo Serialize/Deserialize 

'unknown derrived types of cItem


Option Explicit On 
Option Strict On

Public Class Eitem
  Inherits Citem

  Private m_B As Double

  Public Property B() As Double
     Get
        Return m_B
     End Get
     Set(ByVal value As Double)
        m_B = value
     End Set
  End Property

End Class


'---------------------------------------------------

'The Collection

'

Option Explicit On 
Option Strict On

Imports System.Xml
Imports System.IO

<Serializable()> _
Public Class MyCollection
  Inherits System.Collections.CollectionBase

  Public Overridable Function Add(ByVal value As cItem) As Integer
     MyBase.List.Add(value)
  End Function

  Default Public Overridable Property Item(ByVal index As Integer) As cItem
     Get
        Return DirectCast(MyBase.List.Item(index), cItem)
     End Get
     Set(ByVal value As cItem)
        MyBase.List.Item(index) = value
     End Set
  End Property

  Public Shared Sub SerializeObject(ByVal filename As String, _
   ByVal col As MyCollection, ByVal ExtraTypes() As System.Type)
     Try

        ' Create a new XmlSerializer instance.

        Dim s As New Xml.Serialization.XmlSerializer(_
         GetType(MyCollection), ExtraTypes)

        ' Writing the XML file to disk requires a TextWriter.

        Dim writer As New StreamWriter(filename)

        ' Serialize the object, and close the StreamWriter.

        s.Serialize(writer, col)
        writer.Close()

     Catch x As System.InvalidOperationException
        Throw New Exception("Check class cItem, all derrived "+ _
   "classes must be listed with the [ "+
   "XmlInclude(GetType(derrivedClass)) ] attribute!")
     End Try
  End Sub

  Public Shared Sub SerializeObject(ByVal filename As String, _
    ByVal col As MyCollection)
     Try
        ' Create a new XmlSerializer instance.

        Dim s As New Xml.Serialization.XmlSerializer(GetType(MyCollection))

        ' Writing the XML file to disk requires a TextWriter.

        Dim writer As New StreamWriter(filename)

        ' Serialize the object, and close the StreamWriter.

        s.Serialize(writer, col)
        writer.Close()

     Catch x As System.InvalidOperationException
        Throw New Exception("Check class cItem, all derrived classes "+ _
        "must be listed with the [ XmlInclude"+ _
        "(GetType(derrivedClass)) ] attribute!")
     End Try
  End Sub

  Public Shared Function DeserializeObject(ByVal filename As String, _
     ByVal ExtraTypes() As System.Type) As MyCollection
     Try
        Dim fs As New IO.FileStream(filename, FileMode.Open)
        Dim w As New Xml.Serialization.XmlSerializer( _
   GetType(MyCollection), ExtraTypes)
        Dim g As MyCollection = CType(w.Deserialize(fs), MyCollection)

        fs.Close()

        Return g

     Catch x As Exception
        Throw x
     End Try
  End Function

  Public Shared Function DeserializeObject(ByVal filename As String _
    ) As MyCollection
     Try
        Dim fs As New IO.FileStream(filename, FileMode.Open)
        Dim w As New Xml.Serialization.XmlSerializer(GetType(MyCollection))
        Dim g As MyCollection = CType(w.Deserialize(fs), MyCollection)

        fs.Close()

        Return g

     Catch x As Exception
        Throw x
     End Try
  End Function

End Class

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

About the Author

eschneider100


Software Engineer, Finance market, VB5/6/NET/JAVA/C/C++.
Occupation: Web Developer
Location: United States United States

Other popular C / C++ Language articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralSpecifying derived types at runtimemembersolublefish11:32 31 Dec '04  
GeneralRe: Specifying derived types at runtimemembereschneider10017:52 31 Dec '04  
GeneralSerialization for ViewStatememberdrazz7512:44 22 May '04  
GeneralRe: Serialization for ViewStatemembereschneider10016:18 24 May '04  
GeneralRe: Serialization for ViewStatememberlumonis19:53 9 Dec '05  
QuestionRe: Serialization for Web ServicememberRenz812:52 10 Jan '07  
AnswerRe: Serialization for Web Servicemembereschneider10013:17 24 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Jan 2004
Editor: Nishant Sivakumar
Copyright 2004 by eschneider100
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project