Wednesday, January 02, 2008

XML Serialization: what can be XML serialized and what cannot be ?

Few points that you would like to know about XML serialization that may be also important if you are planning to face an interview soon :P)

Realize that XML serialization:
1> XML serialization can only be applied to classes that contain a public default (parameterless) constructor. If you create a class in the Web service that does not have a public default constructor, the Web service will still compile, but when attempting to generate the proxy class on the client's end you'll receive an error message.

2> Read-only class properties are NOT serialized. That is, if a property in the class has only a get accessor, and not a set accessor as well, the property will not be serialized.

3> ONLY public properties and fields are serialized. Private properties are not serialized.

4> To serialize a strongly-typed collection of objects, have the class derived from System.Collections.CollectionBase adding an Add() method and an indexer.
Alternatively you can send an array of the specified type.

On the last point, consider the case where you want a Web service method to accept a set of custom class instances. For example, imagine you wanted to build a Web method that accepted a number of instances of type CreditCardInfo. One option is to have the method accept an array of type CreditCardInfo, like so:

[WebMethod()]
public void FooBar(CreditCardInfo [] collectionOfCCInfos)
{
...
}
Another option is to create a strongly-typed collection class derived from System.Collections.CollectionBase. You'd then pass in an instance of this strongly-typed collection class. For example, you'd first create the class:

public class CreditCardInfoCollection : System.Collections.CollectionBase
{
public void Add(CreditCardInfo cc)
{
this.InnerList.Add(cc);
}

public CreditCardInfo this[int index]
{
get { return (CreditCardInfo) this.InnerList[index]; }
set { this.InnerList[index] = value; }
}
}
And then you'd have the Web service method accept an input of this strongly-typed collection class:
[WebMethod()]
public void FooBar(CreditCardInfoCollection collectionOfCCInfos)
{
...
}

See this article for more details on web services and XML related basics...
http://aspnet.4guysfromrolla.com/articles/121703-1.aspx


btw, Happy New Year 2008 :)
Happy programming - DJ

No comments: