Tuesday 19 July 2011

C# 4.0 WCF Tuple Serialization

.NET 4.0 contains a new data structure called Tuples.  A brief introduction of Tuples  are found here here.  This post will discuss the using Tuples as a return type for WCF clients that use both .NET 4 and earlier version of .NET. 

Are Tuples Serializable?
With a  bit of inspection with Reflector we can tell that Tuples are, in fact, seralizable:
image
(On a side note, the Silverlight API is different and Tuples are not seralizable. See this blog post for more information)
Since we know that they are serializable, the next step is to create a WCF service that has a method that returns a tuple.
The Service
The goal is to create a very simple service method that returns a Tuple.  This is easily done by modifying the default WCF template that is provided by Visual Studio.
  1. [ServiceContract]
  2.     public interface IService1
  3.     {
  4.  
  5.         [OperationContract]
  6.         Tuple<bool,int> GetData(int value);
  7.     }

  1. public class Service1 : IService1
  2.     {
  3.         public Tuple<bool,int> GetData(int value)
  4.         {
  5.             return new Tuple<bool, int>(true,value);
  6.         }
  7.     }
.NET 4 Client
First, lets test our application using a .NET 4 client.  Using a very simple console application we are able to test our service:

  1. static void Main(string[] args)
  2.         {
  3.  
  4.             var client = new ServiceReference1.Service1Client();
  5.             Tuple<bool,int> test = client.GetData(10);
  6.             
  7.             Console.WriteLine(test.Item1);
  8.             Console.WriteLine(test.Item2);
  9.  
  10.             Console.ReadLine();
  11.  
  12.         }
After we run it, as you might expect,  the build succeeds and the output is "true” and 10.

.NET 3.5 or below client
If we change the framework version to 3.5 or lower in that console application, we’ll get a syntax error since Tuples are not available in those version:
 CropperCapture[4]
To overcome this, we need to change the console application to use a Web Reference instead of a Service Reference.  First delete the current service reference, then click to add another Service Reference.  When adding the Service Reference (screenshot below) click on the Advanced button.
CropperCapture[5]

In the Advanced window, click “Add Web Reference..”

CropperCapture[6]

Type in the URL for the WCF service and add the web reference

CropperCapture[7]

Lastly, change the code to use the Web Reference instead of the Service Reference:
  1. static void Main(string[] args)
  2.         {
  3.  
  4.             var client = new Service1();
  5.             TupleOfbooleanint test = client.GetData(10,true);
  6.             
  7.             Console.WriteLine(test.m_Item1);
  8.             Console.WriteLine(test.m_Item2);
  9.  
  10.             Console.ReadLine();
  11.  
  12.         }
Voilà!  The console outputs “true” and 10.

No comments:

Post a Comment