filling combobox from xml - asp.net

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

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.

Post file to ashx page on different server

I have a asp.net web site where the user chooses some files with a fileUpload Control. Then the files need to be posted to another server
My domain is [http://www.mydomain.com]
The address where i have to upload the files is something like: [https://www.externaldomain.com/upload.ashx?asd2t423eqwdq]
I have tried the following:
Dim uploadedFiles As HttpFileCollection = Request.Files
Dim userPostedFile As HttpPostedFile = uploadedFiles(0)
Dim filePath As String
filePath = "https://www.externaldomain.com/upload.ashx?asd2t423eqwdq" & "/" & userPostedFile.FileName
userPostedFile.SaveAs(filePath)
But i get an error:
The SaveAs method is configured to require a rooted path, and the path 'https://www.externaldomain.com/upload.ashx?asd2t423eqwdq/Core CSS 3.pdf' is not rooted
I searched the internet, but all i could find were examples on how to upload to the page's server.
EDIT:
I used HttpWebRequest to access the link and it partialy worked. I also need to send 2 POST parameters, username and password.
This is how my code looks like now:
Dim link As String = "https://www.externaldomain.com/upload.ashx?e9879cc77c764220ae80"
Dim req As HttpWebRequest = WebRequest.Create(link)
Dim boundary As String = "-----"
req.ContentType = "multipart/form-data; boundary=" + boundary
req.Method = "POST"
Dim username As String = "test"
Dim userpass As String = "123456"
Dim credentials() As Byte = Encoding.UTF8.GetBytes("username=" & username & "&password=" & userpass & "--\r\n" & boundary & "--\r\n")
Dim separators() As Byte = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n")
Dim uploadedFiles As HttpFileCollection = Request.Files //this is where i take the file that the user wants to upload
Dim userPostedFile As HttpPostedFile = uploadedFiles(0)
//i convert the file to a byte array
Dim binaryReader As IO.BinaryReader
Dim fileBytes() As Byte
binaryReader = New BinaryReader(userPostedFile.InputStream)
fileBytes = binaryReader.ReadBytes(userPostedFile.ContentLength)
//'get the request length
req.ContentLength += credentials.Length
req.ContentLength += userPostedFile.ContentLength
req.ContentLength += separators.Length
req.ContentLength += 1
Dim dataStream As Stream
dataStream = req.GetRequestStream
dataStream.Write(credentials, 0, credentials.Length)
dataStream.Write(separators, 0, separators.Length)
dataStream.Write(fileBytes, 0, fileBytes.Length)
dataStream.Close()
Dim response As HttpWebResponse = req.GetResponse
The error i get is "forbidden". The username and password are 100% correct. I think the problem is that i do not create the request correctly. If i post only the credentials i get the error saying that i have no file...
Any ideas?
Eventually I used the code provided here http://aspnetupload.com/
I compiled it into a dll and added a reference to my solution.
It works :)

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

What are valid values for the MediaType Property on a HttpWebRequest

What are valid values for the MediaType Property on a HttpWebRequest?
I want to do something like this:
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim req As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(New Uri(url)), System.Net.HttpWebRequest)
' Add the current authentication cookie to the request
Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName)
Dim authenticationCookie As New System.Net.Cookie(FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, HttpContext.Current.Request.Url.Authority)
req.CookieContainer = New System.Net.CookieContainer()
req.CookieContainer.Add(authenticationCookie)
req.MediaType = "PRINT"
Dim res As System.Net.WebResponse = req.GetResponse()
'Read data
Dim ResponseStream As Stream = res.GetResponseStream()
'Write content into the MemoryStream
Dim resReader As New BinaryReader(ResponseStream)
Dim docStream As New MemoryStream(resReader.ReadBytes(CInt(res.ContentLength)))
Thanks.
I think this wikipedia page should give you a fairly comprehensive list of media types:
Media Types

Resources