2009-02-02

WCF Serialization

Some words before we start
I intend to start blog series of .NET technical blogs
I encourage you to add comments whether the post content meeting your expectation
I will try to keep the post short and technical.

So with that said lets dive into this post topic.
As you may know while passing complex type as parameter for WCF will be serialized using DataContractSerializer.

One thing you should notice about this serialization process is that unlike XmlSerializer it will not call the constructor or field initialization.

So if you declare the following contract
[DataContract]
public class MyCompositeType
{
private Guid m_id1 = Guid.NewGuid (); // will not happens during serialization
public MyCompositeType () // will not happens during serialization
{
Id2 = Guid.NewGuid ();
}
public Guid Id1
{
get { return m_id1; }
}
public Guid Id2 { get; private set; }

[DataMember]
public string StringValue { get; set; }
}

So do not expect that the ids (which is not data member) be initialized on the other side of the serialization process

The code sample for this post is available here

If we having the following service implementation:
public MyCompositeType GetDataUsingDataContract ( MyCompositeType composite )
{
composite.StringValue += " : " + composite.Id1.ToString () +
" : " + composite.Id2.ToString ();
return composite;
}

And we call it from the client like this:
static void Main ( string[] args )
{
MyProxy.SampleServiceClient svc = new MyProxy.SampleServiceClient ();
var composite = new MyCompositeType { StringValue = "Test" };

Console.WriteLine ("Id1 = {0} \nId2 = {1}",
composite.Id1.ToString (), composite.Id2.ToString ());

var response = svc.GetDataUsingDataContract (composite);

Console.WriteLine (response.StringValue);
Console.WriteLine ("Id1 = {0} \nId2 = {1}",
response.Id1.ToString (), response.Id2.ToString ());

Console.ReadLine ();
}

The ids will be initialized to none empty Guid only on the client side
Both at the server and the response ids will be empry




No comments: