Thursday, September 2, 2010

Serializing A C# Object Might Drop Your Attribute If You're Not Careful

I was trying to serialize an object the class for which had been created by the .NET wsdl tool built in to Visual Studio 2010; the object represented an element (ContactInfo) with a single optional attribute (SendData) of type xs:boolean.  I wanted to generate the attribute so that it looked like this:

<ContactInfo SendData="true" />

so I did this in the C# with the corresponding wsdl-generated object: 

contactInfo.SendData = true;

But this generated only: 

<ContactInfo />

What the heck?  I set the property to true; why wasn't the corresponding attribute appearing?  After googling around, a bit, I found this (https://issues.apache.org/jira/browse/AXIS-2155): 

when you use .NET to generate client proxy classes(in our case we generate C# classes) the wsdl tool in .NET generates a XXXspecified along with XXX in the .cs file for primitive types to indicate whether they are specified or not. Eg.,

if the element in schema looks like this:

        <xsd:element name="zip" type="xsd:int" minOccurs="0"/>

then the file generate will have attributes like this in C#:

        private int zipField;

        private bool zipFieldSpecified;

So I really shouldn't have ignored that SendDataSpecified property of my contactInfo object.  It makes sense; if it's a primitive type, there is not a way to indicate not to include the optional element since you can't assign null to a primitive type (and Nullable doesn't count).  So now I do this and I'm all happy: 

contactInfo.SendDataSpecified = true;
contactInfo.SendData = true;

makes 

<ContactInfo SendData="true" />