Thursday, March 10, 2011

WCF DataContract serialization and deserialization in Silverlight

Here is how you can do serialization and deserialization of WCF DataContracts in Silverlight. This is needed when you use MessageContracts in WCF by wrapping DataContracts as XmlElement.

Serialization code:

DataContractSerializer serialize = new DataContractSerializer(request.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream,request);
string res = Encoding.UTF8.GetString(stream.ToArray(),0,stream.ToArray().GetLength(0));
TextReader reader = new StringReader(res);
XDocument doc = XDocument.Load(reader);
XElement elt = (XElement)doc.FirstNode;

you can pass the elt in your MessageContract and send to the WCF service.

Deserialization code:

Once you receive the response from WCF service as XElement, this is how you can deserialize that to object.

XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(elt.CreateReader());
DataContractSerializer serialize = new DataContractSerializer(reader);
result - serialize.ReadObject(reader);

No comments:

Post a Comment