WCF Data contracts, enums, and why they can cause you pain.

WCF is a great technology,but sometimes you run into a problem with it that’ll be really difficult to solve.  The problem I ran into today was with a self-hosted service, a Silverlight client, and the PollingDuplexHttp binding.  Now, aside from all the problems with getting a self-hosted WCF service to work with Silverlight, for some reason I was getting the invocation message across correctly, but I was getting a timeout on the response.  I eventually nailed it down to one of the members in my data contract that contained an enum that looked something like this:

enum myEnum
{
  value1=1,
  value2=2
}

In the data contract, I had a field of type myEnum that had never been assigned a value (since I hadn’t written that code yet), which normally isn’t a problem.  In this case however, it made the WCF deserialization process fall apart, and caused a timeout exception.  As it turns out, in .net the default value for any enum is 0, which usually maps to the first value in the enum.  Had I done this:

enum myEnum
{
  value1,
  value2
}

I would have been fine, since in this case the integer values are implied, and an unassigned enum would have been set to value1.  Instead, I wanted to set the enum values manually to match a legacy app, so I had no value 0, so WCF didn’t know how to interpret it.  I was able to solve the problem by making sure to actually assign a value to the enum (a good idea anyway), and to modify the declaration a bit to keep things neat:

enum myEnum
{
  undefined=0,
  value1=1,
  value2=2
}

Yes, the undefined value doesn’t mean much, but at least it serializes and makes the WCF call work.  With this change you don’t actually have to assign a value to enum members to make them returnable, which helps to reduce coupling.  Not that tricky when you get down to it, but finding the problem was probably a day’s worth of ruling out all the other issues with different versions of Silverlight, a tricky binding like the duplex HTTP, and settings that weren’t matched on the client and server. 

Almost 10 years with .net, and still finding out basic stuff like this.  It really is impossible to know everything.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s