How to parse an xml response from a post in vb.net - asp.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

Related

How to read a SOAP xml file using 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

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()

Getting rid of duplication in a VB list box

Using ASP/VB, I'm trying to get rid of some duplication in a list box that is coming from an XML document.
Sorry if this is a daft question, I'm new to this.
I've tried various things, but nothing has worked. Here is the code - thanks for any help / assistance!
Function getAssets(ByVal siteid As String) As String
Dim oAssets As New Xteam.XteamWebService
Dim strAssets As String = ""
Dim oDoc As New XmlDocument
'Dim oNode As XmlNode
strAssets = oAssets.ReadHAssetCodes(siteid)
oDoc.LoadXml(strAssets)
For Each Node As XmlNode In oDoc.SelectSingleNode("XteamAssets")
lstHAssets.Items.Add(New ListItem(Node("hassetdescription").InnerText, Node("hassetcode").InnerText))
Next
lstHAssets.Items.Insert(0, "--Please Select--")
Return "ToSender"
End Function
There's probably a more efficient way but this will work.
Function getAssets(ByVal siteid As String) As String
Dim oAssets As New Xteam.XteamWebService
Dim strAssets As String = ""
Dim oDoc As New XmlDocument '
Dim oNode As XmlNode
strAssets = oAssets.ReadHAssetCodes(siteid)
oDoc.LoadXml(strAssets)
Dim strAryUniqueValues as string()
Dim strUniqueValues as string = ""
Dim i as int = 0
Dim strSearchPair as string
For Each Node As XmlNode In oDoc.SelectSingleNode("XteamAssets")
strSearchPair = "~" & Node("hassetdescription").InnerText & "/" & Node("hassetcode").InnerText & "~"
' see if these values have been included already, if not then add them
if instr(strUniqueValues,strSearchPair) = -1 then
strAryUniqueValues(i) = strSearchPair
strUniqueValues = strUniqueValues & strAryUniqueValues(i)
i = i + 1
end if
Next
'now loop back through and build your listbox
Dim strAryPair as string()
For each strPair in strAryUniqueValues
strAryPair = split(strPair,"/")
lstHAssets.Items.Add(New ListItem(Replace(strAryPair(0),"~",""),Replace(strAryPair(1),"~",""))
Next
lstHAssets.Items.Insert(0, "--Please Select--")
Return "ToSender"
End Function

exporting rdlc report into pdf on button click

Hi can any one help me out for this.
I have RDLC Report displayed on my web page using asp.net And C#.net I want to export it to PDF on button click.
Please can you help me?
Thanks
I did something like this a while ago. Below is the code I used in the page_load event of a page. It is in VB and isn't the best code in the world but might help you get a solution..
Dim jobid As Integer = Request("jobid")
Dim rv As New Microsoft.Reporting.WebForms.ReportViewer
Dim r As String = "apps/Reports/legal_document.rdlc"
Dim ds As New jobmanagerTableAdapters.JobInformationTableAdapter
Dim ds2 As New ordermanagementTableAdapters.RecoveryItemsInformationTableAdapter
Dim ds3 As New expensemanagerTableAdapters.tbl_expensesTableAdapter
Dim ds4 As New ordermanagementTableAdapters.tbl_orders_collection_itemsTableAdapter
Dim ds5 As New attachmentsmanagerTableAdapters.tbl_attachmentsTableAdapter
Dim ds6 As New notesmanagerTableAdapters.tbl_notesTableAdapter
Dim ds7 As New payments_managerTableAdapters.tbl_paymentsTableAdapter
Dim rptSource1 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource2 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource3 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource4 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource5 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource6 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptsource7 As New Microsoft.Reporting.WebForms.ReportDataSource
rptSource1.Name = "jobmanager_JobInformation"
rptSource1.Value = ds.GetJobInfobyJobID(jobid)
rptSource2.Name = "ordermanagement_RecoveryItemsInformation"
rptSource2.Value = ds2.GetRecoveryItemsbyJobIDOrderID(jobid, 0)
rptSource3.Name = "expensemanager_tbl_expenses"
rptSource3.Value = ds3.GetExpensesbyJobIDOrderID(jobid, 0)
rptSource4.Name = "ordermanagement_tbl_orders_collection_items"
rptSource4.Value = ds4.GetDataByJobIDOrderID(jobid, 0)
rptSource5.Name = "attachmentsmanager_tbl_attachments"
rptSource5.Value = ds5.GetAllAttachmentsbyJobID(jobid)
rptSource6.Name = "notesmanager_tbl_notes"
rptSource6.Value = ds6.GetAllNotesbyJobID(jobid)
rptsource7.Name = "payments_manager_tbl_payments"
rptsource7.Value = ds7.GetPaymentsbyJobID(jobid)
rv.LocalReport.DataSources.Clear()
rv.LocalReport.ReportPath = r.ToString
rv.LocalReport.DataSources.Add(rptSource1)
rv.LocalReport.DataSources.Add(rptSource2)
rv.LocalReport.DataSources.Add(rptSource3)
rv.LocalReport.DataSources.Add(rptSource4)
rv.LocalReport.DataSources.Add(rptSource5)
rv.LocalReport.DataSources.Add(rptSource6)
rv.LocalReport.DataSources.Add(rptsource7)
'Page.Controls.Add(rv)
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
'Get folder on web server from web.config
Dim FolderLocation As String
FolderLocation = Server.MapPath("reports")
'First delete existing file
Dim filepath As String = FolderLocation & "\legal.PDF"
File.Delete(filepath)
'Then create new pdf file
bytes = rv.LocalReport.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Dim fs As New FileStream(FolderLocation & "\legal.PDF", FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs.Close()
Response.Redirect("reports/legal.pdf")

Resources