Solved

Serializing an IEnumberable Class

Posted on 2010-08-31
9
685 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
9 Comments
 
LVL 16

Assisted Solution

by:SriVaddadi
SriVaddadi earned 500 total points
Comment Utility
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
Comment Utility
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 500 total points
Comment Utility
0
 
LVL 3

Author Comment

by:kmcbrearty
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 16

Assisted Solution

by:SriVaddadi
SriVaddadi earned 500 total points
Comment Utility
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
Comment Utility
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 500 total points
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Email Body 4 45
Cannot add a service reference to WCF service to my project 3 39
Windows Service with UDP 2 26
Duplicate a row 2 28
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
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…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

763 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

6 Experts available now in Live!

Get 1:1 Help Now