Serializing an IEnumberable Class

I need to be able to serialize the class that can be found on this Telerik blog.

Download Class

I am trying to do this from within a Silverlight project to cache the data to the IsolatedStorageFile using the XMLSerializer.  The problem that I am having is that I am getting an error message stating


To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy. Telerik.Data.DataTable does not implement Add(System.Object).

I have been trying to modify the class to include an "Add" method but I have been unable to get it to work and I am uncertain as to what I am doing wrong.
LVL 3
kmcbreartyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

 
SriVaddadiCommented:
You WCF service is returning an observable collection of dictionary right. the value part of the dictionary is an object.  

I guess you are passing an object on which there are some properties defined which are not xml serializable. Could you elaborate your question on that front?

I think error message is misleading you and there is absolutelty nothing you need to do with DataTable object
0
 
kmcbreartyAuthor Commented:
To answer your first question, yes my WCF service is returning an observable collection of dictionary. More specifically it is returnning IEnumerable(Of Dictionary(Of String, Object)). I then take this collection and load it into the Telerik DataTable using the constructor.

I could serialize the dictionary collection ro the Telerik DataTable and it wouldn't matter to me but niether will work. When I try to serialize teh Telerik DataTable I am getting the error message that I stated. When I try to serialize the collection of dictionary I get a message indicating that objects that implement IDictionary are not supported.
In both cases the code that I am using is attached.

Public Sub Write(ByVal obj As Object)
        CheckAvailableSpace()
        CreateDirectory()

        Dim fs As IsolatedStorageFileStream
        fs = mStore.OpenFile(FullFilePath, FileMode.Create)

        Dim serializer As XmlSerializer = New XmlSerializer(obj.GetType)
        serializer.Serialize(fs, obj)
        fs.Close()
    End Sub

Open in new window

0
 
SriVaddadiCommented:
0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

 
kmcbreartyAuthor Commented:
I will look into these options and let you know.  Just out of curiosity though, your post suggests that this is supported in future versions of this class.  Do you happen to know why using .Net 4.0 and Silverlight 4.0 that it would still be using the .Net 2.0 version of the XMLSerializer?
0
 
SriVaddadiCommented:
Well, I am not really aware yet whether if its supported in the latest version. I m still trying to find some information. Will keep you posted of any updates.
0
 
kmcbreartyAuthor Commented:
I like the solution you listed from http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx.  The issue that I am not sure how to wrap it back up as an IEnumerable object.  The issue here being that I am not entirely clear on exactly what is being done with the code that generated the IEnumerable object.

This was created from a data table with the following code.
Dim table As DataTable = mgr.GetResults
            Dim columns = table.Columns.Cast(Of DataColumn)()

            t = table.AsEnumerable.Select(Function(r) columns.Select(Function(c) New With { _
                  .Column = c.ColumnName, _
                  .Value = r(c) _
            }).ToDictionary(Function(i) i.Column, Function(i) If(i.Value Is DBNull.Value, Nothing, i.Value)))

Open in new window

0
 
SriVaddadiCommented:
The SerializableDictionary is derived from generic dictionary which implements Ienumerable. So you do not need to do any thing specific to make it Ienumerable object as it is already an ienumerable object.

1. table.AsEnumerable returns an Ienumerable of datarow
2. AsEnumerable.Select return an Ienumerable of anonymous type with column name and row value
3. ToDictionary returns a dictionary object with key as column name and value as row value.

Linq extension methods were used to achieve this. It is as good as iterating through each data row and for each data column in the data table and build a dictionary.

Hope you are clear
0
 
kmcbreartyAuthor Commented:
Thank you for helping me understand what is going on.  With this information I was able to create a working solution for what I needed.  

I have attached the code for anyone who is reading this in the future so they can see the end result.  This includes a copy of the SerializableDictionary class taken from http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx.
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Xml.Serialization


<XmlRoot("dictionary")> _
Public Class SerializableDictionary(Of TKey, TValue)
    Inherits Dictionary(Of TKey, TValue)
    Implements IXmlSerializable

#Region "IXmlSerializable Members"
    Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema
        Return Nothing
    End Function

    Public Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml
        Dim keySerializer As New XmlSerializer(GetType(TKey))
        Dim valueSerializer As New XmlSerializer(GetType(TValue))
        Dim wasEmpty As Boolean = reader.IsEmptyElement
        reader.Read()

        If wasEmpty Then
            Return
        End If

        While reader.NodeType <> System.Xml.XmlNodeType.EndElement
            reader.ReadStartElement("item")
            reader.ReadStartElement("key")

            Dim key As TKey = DirectCast(keySerializer.Deserialize(reader), TKey)
            reader.ReadEndElement()
            reader.ReadStartElement("value")

            Dim value As TValue = DirectCast(valueSerializer.Deserialize(reader), TValue)
            reader.ReadEndElement()
            Me.Add(key, value)
            reader.ReadEndElement()
            reader.MoveToContent()
        End While

        reader.ReadEndElement()
    End Sub

    Public Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements IXmlSerializable.WriteXml
        Dim keySerializer As New XmlSerializer(GetType(TKey))
        Dim valueSerializer As New XmlSerializer(GetType(TValue))

        For Each key As TKey In Me.Keys
            writer.WriteStartElement("item")

            writer.WriteStartElement("key")

            keySerializer.Serialize(writer, key)

            writer.WriteEndElement()

            writer.WriteStartElement("value")

            Dim value As TValue = Me(key)
            valueSerializer.Serialize(writer, value)

            writer.WriteEndElement()

            writer.WriteEndElement()
        Next
    End Sub
#End Region

End Class




    Private Sub WriteDataTable(ByVal source As IEnumerable(Of Dictionary(Of String, Object)))
        ' Serialize the data
        Dim lst As New List(Of SerializableDictionary(Of String, Object))
        Dim sdict As SerializableDictionary(Of String, Object)

        For Each item In source
            sdict = New SerializableDictionary(Of String, Object)
            For Each Key As KeyValuePair(Of String, Object) In item
                sdict.Add(Key.Key, Key.Value)
            Next
            lst.Add(sdict)
        Next

        ToFile(lst)
    End Sub

    Private Sub ToFile(ByVal obj As Object)
        CheckAvailableSpace()
        CreateDirectory()

        ' Open up a File Stream
        Dim fs As IsolatedStorageFileStream
        fs = mStore.OpenFile(FullFilePath, FileMode.Create)

        ' Use XML serilization to write out the object
        Dim serializer As XmlSerializer = New XmlSerializer(obj.GetType)
        serializer.Serialize(fs, obj)

        ' Close the file stream
        fs.Close()
    End Sub

    Private Function FromFile(ByVal Type As System.Type) As Object
        ' Open up a file stream
        Dim fs As IsolatedStorageFileStream
        fs = mStore.OpenFile(FullFilePath, FileMode.Open)

        ' Deserialize the data
        Dim serializer = New XmlSerializer(Type)
        Dim obj As Object = serializer.Deserialize(fs)

        ' Close the file stream and return the object
        fs.Close()
        Return obj
    End Function

Open in new window

0

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.