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:
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 🙂
really Helpful..
Thanks for posting this, I dig the simplicity of this approach and it will prove helpful to me in the future.
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
It helped me a lot.
Thank You,
and
Anjum Rizwi
Coz he got the error as me too
and Fix it Good work
Abd el aziz
what if xml is large??
It does not matter how large is the XML. You just need to adjust the WCF services to allow bigger requests.
on client site, i try to get the table inside the dataset. it is empty actually. Anyone can help?