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:


<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.


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:


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 🙂

7 replies
  1. Anonymous
    Anonymous says:

    Thank You very much. It helped me a lot.

    One change I have done to fix the XmlException: Name cannot begin with the '.' character, hexadecimal value 0x00

    UniCode to UTF8

    Corrected line:
    dsObjects.ReadXml(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(sXML)));

    Thank You,
    Anjum Rizwi


Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *