Web Service Transparency

.NET support for web services is excellent in creating illusion of transparency. General process is quite straightforward:

  • On the server we create a web service, decorating publicly visible methods with [WebMethod] attribute.
  • On the client we add a web reference to the service, and proxy code is automatically generated for us by VIsual Studio. We can then call web service methods almost as if they were local methods.

All arguments and return values get magically XML-serialized, transmitted to the peer, and de-serialized to something very close to the original form. Ideally, this whole process should be automatic and seamless.

Imperfect Transparency of Enums

It turns out that enums are not as transparent as we'd like them to be. There are three sticky issues:

  1. If server-side code declares an enum and assigns specific numeric values to its members, these values will not be visible to the client.
  2. If server-side code declares a [Flags] enum with "compound" mask values (as in White = Red|Green|Blue), it is not properly reflected on the client side.
  3. If server or client transmits an "illegal" value which is outside of the scope of the enum, it causes an exception in XML de-serializer on the other side.

Numeric Values Are Not Preserved

If we have server-side definition like this:

enum StatusCode {     Success = 200,     NotFound = 404,     Denied  = 401 } 

it is translated to client-side definition like this:

enum StatusCode {     Success = 1,     NotFound = 2     Denied  = 3 } 

Corresponding WSDL looks as follows:

<s:simpleType name="StatusCode">     <s:restriction base="s:string">         <s:enumeration value="Success"/>         <s:enumeration value="NotFound"/>         <s:enumeration value="Denied"/>     </s:restriction> </s:simpleType>

As one can see, there is no mension of numeric values in the WSDL. Proxy code generator on the client side does not have access to anything but WSDL. Therefore, it does not have a chance to get numeric values of enum members.

An important side effect of this phenomenon is that the relative order of enum members may not be preserved. For instance, in the example above, expression 
(StatusCode.NotFound > StatusCode.Denied)
 
is true on the server, and false on the client.

Relationships Between [Flags] Masks May Be Broken

Server-side declaration:

[Flags] enum UserRights { 	Read = 16, 	Write = 256, 	Delete = 1024, 	AllAccess = Read | Write | Delete } 

Client-side declaration (some insignificant decorations removed):

[Flags] enum UserRights {    Read = 1,    Write = 2,    Delete = 4,    AllAccess = 8 }

Corresponding WSDL:

<s:simpleType name="UserRights">     <s:restriction base="s:string">         <s:enumeration value="Read"/>         <s:enumeration value="Write"/>         <s:enumeration value="Delete"/>         <s:enumeration value="AllAccess"/>     </s:restriction> </s:simpleType>

Therefore, on the client UserRights.AllAccess lost its relationship to other user right values. On the server expression
(UserRights.AllAccess & UserRights.Read) != 0
is true, while on the client it is false.

This can lead to disastrous consequences.

Out-Of-Range Values Cause Exception on Receiving End

The following server-side code:

enum Test {     SomeValue = 1 }  [WebMethod] public Test GetValue() {    return (Test)512; } 

will cause "invalid XML document" exception on the client side when reading GetValue() response. This exception is related to how XML serializer works with enums. "Legal" values are transmitted as text. E.g. value of 1 would be transmitted as <Test>SomeValue</Test>. For [Flags] enums multiple text strings are transmitted to indicate concatenation of several masks, e.g. <UserRights>Read Write</UserRights>. However, out-of-range values are transmitted as stringified integers, e.g. <Test>512</Test>. These integers are not understood at the receiving end and cause exception.

Controlling Generated XML

It seems that .NET framework does not give you much leeway in controlling XML generated for enums. In particular, constructs like :

[XmlElement(typeof(int))] enum MyEnum {     ... } 

or

[XmlElement(DataType="integer")] enum MyEnum {     ... }

do compile, but fail miserably at run-time.

One useful attribute is [XmlEnum], which allows to change names of enum members. As we mentioned before, enum members are transmitted as literal strings. Therefore, if one has flags enum like this:

[Flags] enum MyMask {     VeryVeryLongFlagNameWillBeTransmittedToClient,     AnotherQuiteLongFlagNameAlongTheFirstOne,     EtCeteraEtCetera } 

generated XML can get quite verbose. To prevent this, transmitted literal strings may be changed using [XmlEnum]:

[Flags] enum MyMask {     [XmlEnum("VeryLong")] VeryVeryLongFlagNameWillBeTransmittedToClient,     [XmlEnum("Another")]  AnotherQuiteLongFlagNameAlongTheFirstOne,     [XmlEnum("EtCetera")] EtCeteraEtCetera } 

Conclusion

Extra caution must be excercised when transmitting enums over web service boundary. Behavior of XML serializer is not always straightforward for enums, and sometimes can cause serious incompatibilities between client and server. To ensure correct operation of software, one must keep in mind its limitations. If numeric values need to be preserved across the wire, they must be transferred as integers, not enums. In this case, however, client must have ad-hoc knowledge regarding what value means what.

.NET framework provides limited means of manipulating XML generated for enums. In particular, we were unable to find an attribute that would allow to automatically transmit enum as int.

转载地址:http://www.ikriv.com/dev/dotnet/WebServices_and_Enums.html

Web Services and C# Enums的更多相关文章

  1. Web Services and C# Enums -摘自网络

    Web Service Transparency .NET support for web services is excellent in creating illusion of transpar ...

  2. .NET RESTful Web Services入门

    很早之前看到过RESTful Web Services,并未在意,也没找相关资料进行学习.今天偶尔有一机会,就找了点资料进行研究,发现RESTful真是“简约而不简单”.下面用示例来说明: 1 项目结 ...

  3. 分分钟带你玩转 Web Services

    当大型需求被数个公司分割开来,各公司系统相互交换数据的问题就会接踵而来. 毕竟是多家不同的公司的产品,研发开发语言.采用技术框架基本上是百花齐放. 怎样让自家系统提供的服务具有跨平台.跨语言.跨各种防 ...

  4. BizTalk发布WS-Security的web services

    最近做个项目,biztalk跟OTM(Oracle Transportation Management)系统做对接,双方通过web services通讯,这部分是BizTalk发布WS-Securit ...

  5. BizTalk调用WS-Security的web services

    最近做个项目,biztalk跟OTM(Oracle Transportation Management)系统做对接,双方通过web services通讯,这部分是BizTalk调用OTM的web se ...

  6. 【整理】动态加载Web Services

    WebClient client = new WebClient(); String url = "http://localhost/MESAPIWebService/MESAPI.asmx ...

  7. RESTful Web Services初探

    RESTful Web Services初探 作者:杜刚 近几年,RESTful Web Services渐渐开始流行,大量用于解决异构系统间的通信问题.很多网站和应用提供的API,都是基于RESTf ...

  8. asp.net Ajax和web services

    新建一个web服务 using System; using System.Collections.Generic; using System.Linq; using System.Web; using ...

  9. SpringSide 部署showcase项目出现 JAX-RS (REST Web Services) 2.0 can not be installed错误!

    maven+springmvc错误 JAX-RS (REST Web Services) 2.0 can not be installed 项目problem提示错误 JAX-RS (REST Web ...

随机推荐

  1. 密码安全存储——PBKDF2、bcrypt、scrypt

    密码用单向哈希存储保证了数据库被脱后用户密码的安全. 由于彩虹表这种攻击方式的存在,一般认为md5,SHA1等单向算法的安全性是不够的.那如何选择合适的加密算法? 下面介绍业界几种高强度单向哈希算法, ...

  2. 创建文件夹c++

    linux #include <sys/types.h> #include <sys/stat.h> string filepath; mkdir(filepath.c_str ...

  3. CF446 (Div. 1)简单题解

    A .DZY Loves Sequences pro:给定长度为N的序列,你最多可以改变一个数的值,问最长严格上升子序列长度. N<1e5. sol:分几种情况,一种的不改变: 一种是改变,然后 ...

  4. seo:与优化相关的熊掌号

    可以做的有: 站点资源管理 天级收录(提交链接即可) 视频极速服务(暂只针对移动端体验优化)https://ziyuan.baidu.com/college/articleinfo?id=2411 原 ...

  5. hdoj-1114 (背包dp)

    题目链接 题意:已知n种coin的价值和体积  求装满容量为v背包的最小硬币价值 #include <algorithm> #include <cstdio> #include ...

  6. UE4 IOS 开发之传感器输入

    Iphone的传感器包括陀螺仪.加速计等. UE4提供了4个按键来收集这些传感器的3维数据.具体位置:ProjectSettings->Input. 其中Tilt数据可以反映Iphone目前的物 ...

  7. 模块化,AMD规范

    模块化:代码量比较大,可能会有几个人同时写一个页面,同样写在一个文件里面,可能会有冲突,模块化可以解决代码的冲突(匿名函数调用,自己调用自己,就是立即执行函数) 团队的分工更加的明确 异步的执行: A ...

  8. synchronized (string.intern())

    在jdk7下慎用String.intern()作为synchronized的对象锁: https://www.cnblogs.com/yhlx/p/3498387.html String.intern ...

  9. springboot收藏的博客

    1.纯洁的微笑:http://www.ityouknow.com/ 2.嘟嘟独立博客:http://tengj.top/ 3.http://blog.didispace.com/

  10. Singer 学习三 使用Singer进行mongodb 2 postgres 数据转换

    Singer 可以方便的进行数据的etl 处理,我们可以处理的数据可以是api 接口,也可以是数据库数据,或者 是文件 备注: 测试使用docker-compose 运行&&提供数据库 ...