Processing Processing

WCF .NET Serialization

You may or may not know that data serialization plays a huge part in how Windows Communication Foundation (WCF) works.  When incorporating WCF services into your .NET application, one of the primary functions of the DataContract and DataMember attributes is to tell the WCF framework how to represent the data to client applications that are generated by either Visual Studio or svcutil.exe for use by your .NET code.  The DataContract (or CollectionDataContract for lists or collections) attribute specifies class definitions, and the DataMember attribute specifies properties.  In the example below, the Age property will not be visible to client applications because it is not properly attributed for use by WCF.

[DataContract]
public class Dog
{
 [DataMember]
 public int TailLength { get; set; }

 public int Age { get; set; }
 
}

Recently I had a need to store the incoming data from a WCF service call for asynchronous processing later.  In particular, I wanted to store individual items in a CollectionDataContract type that was coming across the wire from my service client rather than the whole request.  I also wanted only to store the information that WCF was sending, not the entire object, so I didn't want to use a standard XmlSerializer or other serializer because, using the example above, I did not want to include the Age property in my serialization as it had not been sent to me.

Enter the DataContractSerializer.  It's included in the System.Runtime.Serialization namespace.  It uses the same serialization processes that WCF does to serialize and deserialize objects based on the appropriate DataContract and DataMember attributes.  This allows us to serialize and optionally store incoming WCF requests as a whole or in whatever parts we choose.  Here's a generics-based Serialize and Deserialize method using the DataContractSerializer.

         public static t WcfDeserialize<t>(string data)
            where t : class
        {
            DataContractSerializer ser = new DataContractSerializer(typeof(t));
            return ser.ReadObject(XmlReader.Create(new StringReader(data))) as t;
        }

         public static string WcfSerialize<t>(t obj)
            where t : class
        {
            string val;
            DataContractSerializer ser = new DataContractSerializer(typeof(t));
           
            using (MemoryStream memoryStream = new MemoryStream())
            {
                ser.WriteObject(memoryStream, obj);
                byte[] data = new byte[memoryStream.Length];
                Array.Copy(memoryStream.GetBuffer(), data, data.Length);
                val = Encoding.UTF8.GetString(data);
            }

            return val;
        }

Share It
Couto Solutions’ team of social media experts can deliver a unified community branding experience across all of your web properties.