?
Solved

Serializing an IEnumberable Class

Posted on 2010-08-31
9
Medium Priority
?
707 Views
Last Modified: 2013-11-12
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.
0
Comment
Question by:kmcbrearty
  • 4
  • 4
8 Comments
 
LVL 16

Assisted Solution

by:SriVaddadi
SriVaddadi earned 2000 total points
ID: 33580041
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
 
LVL 3

Author Comment

by:kmcbrearty
ID: 33580201
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
 
LVL 16

Assisted Solution

by:SriVaddadi
SriVaddadi earned 2000 total points
ID: 33580439
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Author Comment

by:kmcbrearty
ID: 33580494
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
 
LVL 16

Assisted Solution

by:SriVaddadi
SriVaddadi earned 2000 total points
ID: 33580645
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
 
LVL 3

Author Comment

by:kmcbrearty
ID: 33581424
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
 
LVL 16

Assisted Solution

by:SriVaddadi
SriVaddadi earned 2000 total points
ID: 33585895
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
 
LVL 3

Accepted Solution

by:
kmcbrearty earned 0 total points
ID: 33589944
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

862 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