Monthly Archives: September 2016

The DataContractSerializer is a Dirty Little Peeping Tom

I had a problem today with my SelfSerializer class and the DataContractSerializer. I’ve got this test which was throwing an annoying ‘Object graph for type ‘SelfSerializer’ contains cycles and cannot be serialized if reference tracking is disabled’ error:

    <TestMethod>
    Public Sub SelfSerializerSerializationTest_XMLSerializer()
        Try
            Dim token As New SelfSerializer
            Dim dcs As XmlSerializer = New XmlSerializer(GetType(SelfSerializer))
            Dim xml As String = String.Empty
            Using stream As New StringWriter(), writer As XmlWriter = XmlWriter.Create(stream)
                'Serialize the item to the stream using the namespace supplied
                dcs.Serialize(writer, token)
                writer.Flush()
                'Read the stream and return it as a string
                xml = stream.ToString
            End Using
            Debug.Print(xml)
            Dim newToken As SelfSerializer
            Dim sr As New StringReader(xml)
            Dim reader As XmlReader = XmlReader.Create(sr)
            dcs = New XmlSerializer(GetType(SelfSerializer))
            newToken = CType(dcs.Deserialize(reader), SelfSerializer)
            reader.Close()
            sr.Close()
            Assert.IsTrue(newToken IsNot Nothing)
        Catch ex As Exception
            Debug.Print(ex.Message)
            Throw
        End Try
    End Sub

What’s happening internally is that the DataContractSerializer is using reflection to peep into the private parts of my class!

So to prevent this filthy little activity I have to add the DataContract attribute to the SelfSerializer class and IgnoreDataMember to the two private fields I use internally.

Frankly it’s all a bit Benny Hill…

bennyhill

<cue YakketySax music>