Passing DataSet to a WCF Method

Recently I've made a simple WCF service that had a method that takes a MemoryStream parameter. After some time I had to add another method that should take a whole DataSet as parameter. And then my problems begun!

After I've added the method and refreshed the service reference of my client the proxy class generator decided to create his own MemoryStream class in the namespace of my WCF service! Then I knew that the true evil of DataSets is back (for more informations see Scott Hanselmann's post about using DataSets in web services). The solution - use the DataSet's methods to get the data in XML format and pass the XML string instead of the DataSet itself to the service. Here is a sample code:
IService.vb:
<ServiceContract()> _
Public Interface IService
<OperationContract()> _
Function PassDataSet( _
ByVal
sXMLSchema As String _
, ByVal sXML As String) As Boolean
End Interface

Note that because we do not know the schema of the DataSet in the service we also pass the XML schema of the DataSet.
Service.vb:
Public Class Service
Implements IService
Public Function PassDataSet( _
ByVal sXMLSchema As String _
, ByVal sXML As String) As Boolean Implements IService.PassDataSet
Dim dsObjects As New Data.DataSet
'First read the schema of the DataSet
dsObjects.ReadXmlSchema _
(New MemoryStream(Text.Encoding.Unicode.GetBytes(sXMLSchema)))
'Then read the data itself
dsObjects.ReadXml _
(New MemoryStream(Text.Encoding.Unicode.GetBytes(sXML)))
'Here do what ever you like with your DataSet
'Finally return a value to the client
Return True
End Function
End Class

And finally here is how you call the method:
Client:
'Create and instance of the client proxy for the service.
Dim proxy As New ServiceClient()
Dim dsDataSet As New DataSet()
'Here load your data in your DataSet
'Finally call the service
proxy.PassDataSet(dsDataSet.GetXmlSchema(), dsDataSet.GetXml())

Now you can enjoy your WCF service that accepts a DataSet :)

Labels: , ,