Why is everyone so down on using DataSets in .NET Web Services? Sure, I’ll
admit that using DataSets directly as Web Service parameters are indeed a
problem. But why throw the baby out with the bath water?
For the uninitiated, DataSets are a problem as Web Service parameters because
XML that is automatically generated as the parameter is a DiffGram of the
DataSet. Unfortunately DiffGrams are simply not interop-friendly. At the end of
the day the obvious use of DataSets in .NET Web Services are simply a bad idea.
But if we deal with DataSets as XML instead of a class to be serialized we
can actually achieve some real benefits. If you have experienced DataSets, you
know that you can specify an .xsd as the schema of the DataSet. What that means
is that you can deliver the contents of the DataSet with relevant schema as an
XML document. Since the resulting XML document can refer to a specific schema,
the consumers of the Web Service (whether they are using Java, WebSphere, or
.NET) will receive a self-describing, strongly typed piece of information.
But how does this work? The trick is wrapping your DataSet in an
XmlDataDocument. By specifying your Web Service method like so:
[WebMethod]
public XmlDocument GetAllTheData()
{
return new XmlDataDocument(yourDataSet);
}
This works because the XmlDataDocument derives from XmlDocument so that the
XmlSerializer serializes it as an XML document. Whether the 'yourDataSet' field
is a TypedDataSet or just a DataSet with an .xsd specified for its schema, the
Web Service will export it as vanilla XML that can be consumed by any number of
clients.