Yossi Dahan [BizTalk]

Google
 

Tuesday, October 03, 2006

Another important point about enums and web services

In most programming languages, when declaring an enumetation, you can assign to each member both a string representation and a value of a specific type.

This is an importat reason begind the enumerated type conceept - to be able to give a meaningful name to a value.

In the Xml world, however, enumerations are more limited. they are thought of more as a restricted list of allowable values, and less a tranlsation between a value and a name, and so - it is not possible to provide to representations for an enumeration member, you can only specifiy a list of allowed values.

This is useful enough, albeit limited.

The grave danger, though, is when switching between the two.

if you have a web service that returns an enum which is declated as such -

Public Enum MyEnum
X = 2
Y = 87
End Enum


and you look at the wsdl generated for this enum you will see something like -

<s:simpletype name="MyEnum">
<s:restriction base="s:string">
<s:enumeration value="X">
<s:enumeration value="Y">
</s:restriction>
</s:simpleType>


As you can see, there is no mentioning of the values 2 and 87.

This means that if you add a reference to this web service the proxy generated will include an enum defined as -

Public Enum MyEnum
X
Y
End Enum


And so - when the message get serialised on the web service end Y (for example) goes into the xml, but when it gets deserialised on the client end, Y is deserialised as 1 and not 87 which was it's original value.

You can see, I'm sure, that this can be quite dangerous.
There are two ways around this - one would be to return the underlying value and not the enumeration memeber. you loose your "friendly name" and the well defined list of possible values, but you know the value is absolutely correct.

On the other hand you can ensure you always use ordnial, 0 based, values for your enumeration members (which is exactly like not specifying then to begin with). you loose the ability to have specific values in, but get to keep the enumerations in the picture and that well defined list of possible values

0 Comments:

Post a Comment

<< Home