Imports System.Xml
Imports System.Net
Imports System.IO

Namespace CSFramework_Utilities

    Public Class XMLData

        Public Shared Function XMLStringFromDataset(ByVal ds As DataSet) As String
            Dim sw As New StringWriter()
            ds.WriteXml(sw, XmlWriteMode.IgnoreSchema)
            Return sw.ToString()
        End Function

        Public Shared Function DownloadXMLAsDataset(ByVal url As String, Optional ByVal credentials As Net.NetworkCredential = Nothing) As DataSet

            Dim myXMLReader As XmlReader
            Dim myDataSet As New DataSet
            If credentials IsNot Nothing Then
                Dim myXMLResolver As XmlUrlResolver = New XmlUrlResolver
                myXMLResolver.Credentials = credentials
                Dim myXMLSettings As XmlReaderSettings = New XmlReaderSettings
                myXMLSettings.XmlResolver = myXMLResolver
                myXMLReader = XmlReader.Create(url, myXMLSettings)
            Else
                myXMLReader = XmlReader.Create(url)
            End If
            myDataSet.ReadXml(myXMLReader)
            Return myDataSet
        End Function


        Public Shared Function DownloadXMLWithDatasetPost(ByVal url As String, ByVal datasetToPost As DataSet, ByVal credentials As System.Net.NetworkCredential) As String


            Dim xmlrequest As HttpWebRequest = WebRequest.Create(url)
            xmlrequest.ContentType = "text/xml"
            xmlrequest.Method = WebRequestMethods.Http.Post
            xmlrequest.Credentials = credentials
            xmlrequest.Timeout = 2000000
            Try

                Dim newStream As Stream = xmlrequest.GetRequestStream()
                datasetToPost.WriteXml(newStream)
                newStream.Close()

                Dim xmlresponse As WebResponse = xmlrequest.GetResponse()
                Dim responseStr As String = ConvertStreamToString(xmlresponse.GetResponseStream)


                Return responseStr

            Catch ex As Exception
                Return "DownloadXMLWithDatasetPost ERROR: " & vbCrLf & ex.ToString
            End Try

        End Function

        Public Shared Function ConvertStreamToString(ByVal InputStream As System.IO.Stream) As String
            Dim sr As System.IO.StreamReader = New System.IO.StreamReader(InputStream)
            Dim responseStr As String = sr.ReadToEnd()
            Return responseStr
        End Function

        Public Shared Function DatasetFromXML(ByVal xml As String) As DataSet

            Dim dataSet As DataSet = New DataSet


            Dim xmlSR As System.IO.StringReader = New System.IO.StringReader(xml)

            dataSet.ReadXml(xmlSR)

            Return dataSet

        End Function


    End Class

End Namespace