The data from your XmlWriter
is not immediately populated to the underlying StringWriter
. So you should flush the writer after writing:
dcs.WriteObject(writer, message)
writer.Flush()
xml = stream.ToString()
Question
I'm testing sending a complex message object over a WCF service and getting various serialization errors. In order to simplify things I'm trying to cut it down to just testing the DataContractSerializer
, for which I've written the following test based on the code here:
Dim message As TLAMessage = MockFactory.GetMessage
Dim dcs As DataContractSerializer = New DataContractSerializer(GetType(TLAMessage))
Dim xml As String = String.Empty
Using stream As New StringWriter(), writer As XmlWriter = XmlWriter.Create(stream)
dcs.WriteObject(writer, message)
xml = stream.ToString
End Using
Debug.Print(xml)
Dim newMessage As TLAMessage
Dim sr As New StringReader(xml)
Dim reader As XmlReader = XmlReader.Create(sr)
dcs = New DataContractSerializer(GetType(TLAMessage))
newMessage = CType(dcs.ReadObject(reader, True), TLAMessage) 'Error here
reader.Close()
sr.Close()
Assert.IsTrue(newMessage IsNot Nothing)
However this gets an unusual error in itself on the call to ReadObject
: Unexpected end of file while parsing Name has occurred. Line 1, position 6144
It appears to be a buffering error but I can't see how to 'ReadToEnd' on the string. I've tried using a MemoryStream
: Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(xml))
and a StreamWriter
but each of those has come with their own errors or are not compatible with the ReadObject
method of the DataContractSerializer
which takes a variety of different overloads.
Note that adapting the code from the MSDN page works fine but requires serializing to a file, however I wanted to serialize to and from a string but I think that I'm missing something vital.
Am I missing something obvious in the code above?
Solution
The data from your XmlWriter
is not immediately populated to the underlying StringWriter
. So you should flush the writer after writing:
dcs.WriteObject(writer, message)
writer.Flush()
xml = stream.ToString()