Tuesday, May 22, 2007

WS Enumerations in ASMX

String little error i have run into when using enumerations from an ASMX.

Just in case you don't know, enumerations aren't automatically serialized when you use the XmlInclude attribute on your web service classes. Hence you can create a method called someything like "GetMyEnum" which return it. You don't ever actually have to call this method, but having it there forces .Net into serializing the enumeration for you and including it in any web service proxy definitions.

Now, we also know you can add the [Flags] attribute to any enumeration to allow you to perform bitwise calculations on the enumeration without created properties to store each setting. In most cases you simply apply the [Flags] attribute and that's all you need to do.

However, I found an issue here (anyone else?). On the actual enumeration definition, the integer value start from zero; on the web service proxy generated enumeration, it starts from 1 ! In other words:


On the server ...

[Flags]
public enum MyEnum
{
myfirst, //set to 0
mysecond, //set to 1
mythird, //set to 2
myfourth //set to 4
}

In the WS proxy ...

[Flags]
public enum MyEnum
{
myfirst, //set to 1
mysecond, //set to 2
mythird, //set to 4
myfourth //set to 8
}

The result is that your bitwise calculations that are sent from the client to the server are screwed up. The fix is irritating, but simple. Simply modify your original enumeration definition and start from 1 rather than 0.

No comments: