Deserialization workaround in C#

Workaround for a deserialization bug i C# .NET when using a Web Service

A "Web Reference" is easy to add to a C# project, and it works more or less as well and is as easy as in Java using Eclipse/WTP. However, there is a serious problem that can cause really weird errors in some cases. Everything seems to work, up until the point when you are trying to retrieve properties from objects that you received from the Web Service, and they turn out to be null. If the objects seem ok, but their properties are null and there's is no sensible reason for them being so, you have probably stumbled on this bug.

The problem is caused by an obscure bug when C# is expected to deserialize the objects in another namespace than that of the web service class.

For example, if you have declared your Web Service in the package se.upp.foobar.bletch, and the data classes being sent are located in se.upp.foobar.data, this error can occur. If you move all the classes into the same package on the server and recreate the Web Service and the Web Reference, it will work.

Doing that is rarely an attractive solution. There is a workaround on the client side that you can use instead:

Open Web References, double-click the added reference and then double-click one of the class names, to got to the actual source code for the Web Reference. Find the class definitions for the data classes.

It can look like this:

[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://data.foobar.upp.se")]
    public partial class myDataBean {
        private int countrowsField;

Simply change the name of the namespace to the one used for the service class - even though the object actually does belong in data.foobar.upp.se!:

[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://bletch.foobar.upp.se")]
    public partial class myDataBean {
        private int countrowsField;

... and amazingly enough, it starts working.