Solved

Serializing an IEnumberable Class

Posted on 2010-08-31
9
698 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
9 Comments
 
LVL 16

Assisted Solution

by:SriVaddadi
SriVaddadi earned 500 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 500 total points
ID: 33580439
0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
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 500 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 500 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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
need to convert function to c# 5 53
Put File 6 32
C# Change the instruction to user. 11 35
web api controller with multiple posts that accept different objects 1 19
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
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…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

740 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