How to read a SOAP xml file using asp.net? - asp.net

I was trying to read an xml file and loads it in an xml document. However an error prompted me that the "Data at the root level is invalid. Line 1, position 1." I need to retrieve the message from the xml file.
Below is my code:
Dim xmlPath as String = Server.MapPath("~/res.xml")
Dim xmlDoc as New XmlDocument
Dim fs As New FileStream(xmlPath, FileMode.Open, FileAccess.Read)
xmlDoc.Load(fs)
Here is the content of the xml file:
--uuid:8asdsddf-sdf24-asdasd-3121-asdasdasdasd
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml";
Content-Transfer-Encoding: binary
Content-ID: <root.message#apache.org>
<SOAP-ENV:Envelope xmlns:SOAP-
ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header></SOAP-
ENV:Header><SOAP-ENV:Body><Status xmlns=""><Message>Success: 12345</Message></Status></SOAP-ENV:Body></SOAP-
ENV:Envelope>
--uuid:8asdsddf-sdf24-asdasd-3121-asdasdasdasd--
What should be the reason why the error prompted?

The following code should remove all the non xml string from file
Imports System.IO
Imports System.Xml
Module Module1
Const FILENAME As String = "c:\temp\test.xml"
Sub Main()
'Dim xmlPath As String = Server.MapPath("~/res.xml")
Dim xmlDoc As New XmlDocument
Dim reader As New StreamReader(FILENAME)
Dim xml As String = ""
Dim inputLine As String = ""
Dim foundTag = False
While (Not reader.EndOfStream)
inputLine = reader.ReadLine
If foundTag = False Then
If Not inputLine.StartsWith("<") Then Continue While
foundTag = True
End If
If Not inputLine.StartsWith("--") Then
xml = xml & inputLine
End If
End While
xmlDoc.LoadXml(xml)
End Sub
End Module

Related

Error trying to download an XML file

I'm trying to download an XML file, the file already exists in the specified path, I am not familiar with VB and probably this code is not right, I need help just in it to be able to download an existing xml file, here's the code:
Protected Sub DownloadFile(ByVal sPath As String)
Dim TargetFile As New System.IO.FileInfo(sPath)
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" +
TargetFile.Name)
Response.AddHeader("Content-Length", TargetFile.Length.ToString())
Response.ContentType = "text/xml"
Response.WriteFile(TargetFile.FullName)
Response.End()
End Sub
The error returned in the console:
Uncaught Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Contextualizing the problem:
I have serialized an object and created an XML file, then I would simply like to download this file, my difficulty is to download the file.
Dim oObj1 As New System.Xml.Serialization.XmlSerializer(GetType(eSocial.Eventos.evtTabHorTur.eSocial))
Dim sFileName = Date.Now.ToString("yyyyMMddHHmmss") & ".xml"
Dim sPath = Constantes.Ambiente.CaminhoSite & "temp\" & sFileName
Dim oFile As New System.IO.StreamWriter(sPath)
oObj1.Serialize(oFile, eSocialCamposXml)
oFile.Close()
You are saying you are having difficulty downloading but there is nothing in the code except showing writing a file and then serializing a file. You would be using a 'StreamReader' or similar manner to READ a file. Here is a simple example. Say I have an xml structure on a file location with the schema like:
<root>
<test>Data</test>
</root>
I could write this in VB.NET to get it:
Sub Main()
Dim xmlFile As XDocument
Dim fileLocation = "D:\\Test Code\\Test.xml"
Using sr = New StreamReader(fileLocation)
xmlFile = XDocument.Parse(sr.ReadToEnd())
End Using
Console.WriteLine(xmlFile.Root.Element("test").Value.ToString)
Console.ReadLine()
End Sub

filling combobox from xml

I want to fill my dropdownlist with all the payment methods, i should find the payment methods in an xml file that i have. this should be the xml code for the methods:
Dim xml As String
xml = "<?xml version=""1.0"" encoding=""UTF-8""?>"
xml &= "<gateways ua=""example-php-1.1"">"
xml &= "<merchant>"
xml &= " <account>123456</account>"
xml &= " <site_id>789</site_id>"
xml &= " <site_secure_code>112233</site_secure_code>"
xml &= "</merchant>"
xml &= "<customer>"
xml &= " <country>NL</country>"
xml &= " <locale>nl_NL</locale>"
xml &= "</customer>"
xml &= " </gateways>"
Dim apiURl As String
apiURl = "https://testapi.multisafepay.com/ewx/"
Dim httpWebRequest As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(apiURl)
httpWebRequest.Method = "POST"
httpWebRequest.ContentLength = System.Text.Encoding.UTF8.GetByteCount(xml)
httpWebRequest.ContentType = "application/x-www-form-urlencoded"
Dim streamWriter = New System.IO.StreamWriter(httpWebRequest.GetRequestStream())
streamWriter.Write(xml)
streamWriter.Close()
Dim httpWebResponse As System.Net.HttpWebResponse = httpWebRequest.GetResponse()
Dim streamReader = New System.IO.StreamReader(httpWebResponse.GetResponseStream())
Dim stringResult = streamReader.ReadToEnd()
Dim xmlstring As String = stringResult
Dim xd As System.Xml.XmlDocument = New System.Xml.XmlDocument()
xd.LoadXml(xmlstring)
the stringResult gives this Value:
<?xml version="1.0" encoding="UTF-8"?>
<gateways result="ok">
<gateways>
<gateway>
<id>IDEAL</id>
<description>iDEAL</description>
</gateway>
<gateway>
<id> MASTERCARD</id>
<description>Visa via Multipay</description>
</gateway>
<gateway>
<id> BANKTRANS</id>
<description> Bank Transfer</description>
</gateway>
<gateway>
<id> VISA</id>
<description> Visa CreditCards</description>
</gateway>
</gateways>
</gateways>
i need to get the value between the <id></id> tags in my ddlMethod how can i do this?
You can use SelectNodes() method to get specific nodes from XmlDocument passing suitable XPath string as the method parameter. Since SelectNodes() returns collection of XmlNode, you also need to specify which property of XmlNode to be displayed in the dropdown list control. In this case, I assume you want to display the text between <id> tags so we use InnerText property :
Dim xd As System.Xml.XmlDocument = New System.Xml.XmlDocument()
xd.LoadXml(xmlstring)
'set data source of dropdown to all <id> elements from XML'
ddlMethod.DataSource = xd.SelectNodes("//id")
ddlMethod.DataTextField = "InnerText"
ddlMethod.DataValueField = "InnerText"
ddlMethod.DataBind()
Only if available in the .NET framework version you're using, I'd suggest to switch to XDocument which is more modern XML library in .NET compared to the older XmlDocument. In various situations XDocument is more friendly to use than XmlDocument. Example using XDocument and LINQ style :
Dim xd As XDocument = XDocument.Parse(xmlstring)
'set data soutce of dropdown to *content* of all <id> elements from XML'
ddlMethod.DataSource = xd.Descendants("id").Select(Function(x) x.Value)
ddlMethod.DataBind()
i came up with this and it works for me:
Dim bytTeller As Byte
For bytTeller = 0 To xd.GetElementsByTagName("gateway").Count - 1
Dim root As XmlNode = xd.GetElementsByTagName("gateway").Item(bytTeller)
ddlMethod.Items.Add(root.ChildNodes(0).InnerText)
Next

Get the decrypted content of the section in web.config without saving

How can I get the content of the decrypted webconfig section before it saves the decrypted file: confg.Save()?
Dim confg As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim confgSect As ConfigurationSection = confg.GetSection("section")
If confgSect.SectionInformation.IsProtected Then
confgSect.SectionInformation.UnprotectSection()
confg.Save()
End If
Dim confg As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim confgSect As ConfigurationSection = confg.GetSection("section")
If confgSect.SectionInformation.IsProtected Then
confgSect.SectionInformation.UnprotectSection()
Dim xml As New System.Xml.XmlDocument
Dim node As System.Xml.XmlNodeList
Dim str As String
Dim answer As String
str = confgSect.SectionInformation.GetRawXml()
xml.LoadXml("<ROOT>" + str + "</ROOT>")
node = xml.GetElementsByTagName("TagnameHere")
answer= node(0).Attributes(1).Value
End If
My section in the webcobfig contains multiple tags, so I used xml to get each tag and get its value as an attribute.

xml response http post - convert request.inputstream to string - asp.net

I'm receiving an xml response and I now want to parse this.
Currently what I have to receive the XML response is:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
How can I go ahead now a process this and pick out the element values?
<subscription>
<reference>abc123</reference>
<status>active</status>
<customer>
<fname>Joe</fname>
<lname>bloggs</lname>
<company>Bloggs inc</company>
<phone>1234567890</phone>
<email>joebloggs#hotmail.com</email>
</customer>
</subscription>
If I have it in string format I can do this using
Dim xmlE As XElement = XElement.Parse(strXML) ' strXML is string version of XML
Dim strRef As String = xmlE.Element("reference")
Do I need to convert the request.inputstream to a strign format or is there another better way?
Thanks
Do I need to convert the request.inputstream to a strign format or is there another better way?
You could directly load it from the request stream, you don't need to convert it to a string:
Request.InputStream.Position = 0
Dim Xmlin = XDocument.Load(Request.InputStream)
Dim reference = Xmlin.Element("subscription").Element("reference").Value
or:
Dim reference = Xmlin.Descendants("reference").First().Value
In the end after much testing I could only get this to work:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
Dim strXml As String = Xmlin.ToString
Dim xmlE As XElement = XElement.Parse(strXml)
Dim strRef As String = xmlE.Element("reference")
Dim strStatus As String = xmlE.Element("status")
Dim strFname As String = xmlE.Element("customer").Element("fname").Value()
Dim strLname As String = xmlE.Element("customer").Element("lname").Value()
Dim strCompany As String = xmlE.Element("customer").Element("company").Value()
Dim strPhone As String = xmlE.Element("customer").Element("phone").Value()
Dim strEmail As String = xmlE.Element("customer").Element("email").Value()

How to parse an xml response from a post in vb.net

I am posting to a website to get data back. The site returns it as an xml. I am able to get the data into a string. But what i really want to do is to have each item in the xml in a different string field.
Sub lookup(ByVal Source As Object, ByVal e As EventArgs)
Dim wData As String
wData = WRequest("http://PostToThisSite.com", "POST","str=31&Password=pn&UserID=Q&Postcode="+txtPcode.Text)
Response.Write(wData)
End Sub
Function WRequest(URL As String, method As String, POSTdata As String) As String
Dim responseData As String = ""
Try
Dim hwrequest As Net.HttpWebRequest = Net.Webrequest.Create(URL)
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = true
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = method
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/x-www-form-urlencoded"
Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Dim postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
postStream.Close()
End If
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader = _
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
hwresponse.Close()
Catch e As Exception
responseData = "An error occurred: " & e.Message
End Try
Return responseData
End Function
The above code works and writes out a line...
Some Road City LU1 5QG
The Xml being returned is ..
<Address xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://site.co.uk/">
<strOrganisation />
<strProperty />
<strStreet>Some Road</strStreet>
<strLocality />
<strTown>City</strTown>
<strCounty />
<strPostcode>LU1 5QG</strPostcode>
<strDPS />
I want to be able to split these fields and set them to different text boxes on the page...help?
Load the xml string into an XmlDocument and extract the values with XPath:
Dim doc = new XmlDocument()
doc.LoadXml(yourXmlString)
Dim nsm = new XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("a", "http://site.co.uk/")
txtStreet.Text = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
Here's a working snippet:
Dim doc = New XmlDocument()
doc.LoadXml("<Address xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://site.co.uk/""><strOrganisation /> <strProperty /> <strStreet>Some Road</strStreet> <strLocality /> <strTown>City</strTown> <strCounty /> <strPostcode>LU1 5QG</strPostcode><strDPS /></Address>")
Dim nsm = New XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("a", "http://site.co.uk/")
Dim streetValue = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
Some things to note:
For XPath lookups, if your xml has a namespace you'll need to add it to an
XmlNameSpaceManager created from your XmlDocument's NameTable.
If you don't want to
bother with that, you can walk the node collections manually via
doc.ChildNodes[0].ChildNodes[0] etc.
Or try this, which is what I believe the author was asking.
' Use XML Reader
Dim xmlDoc = New XmlDocument
Dim xmlNode As Xml.XmlNode
xmlDoc.LoadXml(strResponse)
xmlNode = xmlDoc.SelectSingleNode("//" + "strStreet")
If Not xmlNode Is Nothing Then
Dim Street = xmlNode.InnerText
End If

Resources