Consuming data from webservice with vb.net - html

Im doing a webform in vb.net I'm consuming a webservice, Which returns me to all the countries
Only have 1 button Enviar that calls the countries.
Imports service_country = WebServiceVB2.country
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim serv_country As New service_country.country '--Create object'
Dim MyDoc As New System.Xml.XmlDocument
Dim MyXml As String = serv_country.GetCountries() '--Execute procedure from webservice'
MyDoc.LoadXml(MyXml) '--Read Myxml and convert to XML'
Dim SymbolText As String = MyDoc.SelectSingleNode("//NewDataSet/Table/Name").InnerText '--select the node'
Label1.Text = SymbolText
End Sub
My question is How can I select all the values that are inside the 'name'.
Actually it only shows one.
For Example:
Thanks in advance.

This was an interesting problem. Since data is coming as a webpage the open bracket was coming as "& l t ;" while the closing bracket was coming as "& g t ;". So these had to be replaced. I used xml linq to get the names :
Imports System.Xml
Imports System.Xml.Linq
Module Module1
Const URL As String = "http://www.webservicex.net/country.asmx/GetCountries"
Sub Main()
Dim doc1 As XDocument = XDocument.Load(URL)
Dim docStr As String = doc1.ToString()
docStr = docStr.Replace(">", ">")
docStr = docStr.Replace("<", "<")
Dim doc2 As XDocument = XDocument.Parse(docStr)
Dim root As XElement = doc2.Root
Dim defaultNs As XNamespace = root.GetDefaultNamespace()
Dim names() As String = doc2.Descendants(defaultNs + "Name").Select(Function(x) CType(x, String)).ToArray()
End Sub
End Module
Using WebUtility
Imports System.Xml
Imports System.Xml.Linq
Imports System.Text
Imports System.Net
Module Module1
Const URL As String = "http://www.webservicex.net/country.asmx/GetCountries"
Sub Main()
Dim xReader As XmlReader = XmlTextReader.Create(URL)
xReader.MoveToContent()
Dim doc As XDocument = XDocument.Parse(WebUtility.HtmlDecode("<?xml version=""1.0"" encoding=""iso-8859-9"" ?>" & xReader.ReadOuterXml))
Dim root As XElement = doc.Root
Dim defaultNs As XNamespace = root.GetDefaultNamespace()
Dim names() As String = doc.Descendants(defaultNs + "Name").Select(Function(x) CType(x, String)).ToArray()
End Sub
End Module

Related

VB.Net JSON data import

I am a teacher who has been given a subject teaching Digital Solutions. While I have experience in VB.net and VBA, I have not had experience with JSON.
I would like to use the data based on the URL in the code below.
If someone could assist with the code and add some annotations (notes) as to what specific lines do, this would be helpful. The code below is what I have tried to discover by myself from the internet and may be partially incorrect (especially the "Case" section).enter code here
Option Strict On
Imports System.Net
Imports System.IO
Imports System.Linq
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class WeatherMain
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim Sec1 As String
Try
request = DirectCast(WebRequest.Create("http://www.data.qld.gov.au/datastore/dump/2bbef99e-9974-49b9-a316-57402b00609c?format=json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JProperty In results
item.CreateReader()
Select Case item.Name
Case "Site"
Dim strResult = item.Value.ToString
Select Case strResult
Case "Gold Coast"
MsgBox("Gold Coast")
Case Else
MsgBox("Unable to handle " & strResult)
End Select
End Select
Next
Catch ex As Exception
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try
End Sub
End Class

Slicing a string to read a html document in VB

I was hoping someone could help me figure out why this script will not return the link names. I am trying to return a sub-string from 'http://textfiles.com/directory.html' which just writes the link names to the console, but I am struggling. The main problem - as far as I can see - is in the 'do until' loop. The working code outputs the html text to the console more for my sake than anything else (it does this successfully), but this feature may also help you guys understand the total picture I am facing. Maybe after seeing the code/ understanding my goal you guys can see where I am going wrong AND/OR suggest a better method for achieving my goal. Thanks a ton!
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
Dim line As String = ""
Dim lowBound As String = "<a href="""
Dim highBound As String = """>"
Console.WriteLine("Grab link names from textfiles.com")
Console.WriteLine("")
Dim siteName As String = "http://textfiles.com/directory.html"
Dim tmpString As StringBuilder = New StringBuilder
My.Computer.Network.DownloadFile(siteName, "C:\~\VisualStudio\BeginnerPractice\TextFileDotCom_GrabLinkNames\TextFileDotCom_GrabLinkNames\bin\debug\directory.html", False, 500)
Dim myReader As StreamReader = New StreamReader("C:\~\VisualStudio\BeginnerPractice\TextFileDotCom_GrabLinkNames\TextFileDotCom_GrabLinkNames\bin\debug\directory.html")
While Not IsNothing(line)
line = myReader.ReadLine()
If Not IsNothing(line) Then
tmpString.Append(line)
End If
End While
Dim pageText As String = tmpString.ToString
Console.WriteLine(pageText)
Dim intCounter As Integer = 1
Do Until intCounter >= Len(pageText)
Dim checkSub As String = Mid(pageText, intCounter + 1, (Len(pageText) - intCounter))
Dim positLow As Integer = InStr(checkSub, lowBound)
Dim positHigh As Integer = InStr(checkSub, highBound)
If (positLow > 0 And positHigh > 0) And positLow < positHigh Then
Dim indexLow As Integer = checkSub.IndexOf(lowBound)
Dim indexHigh As Integer = checkSub.IndexOf(highBound)
Dim foundLink As String = checkSub.Substring(indexLow + Len(lowBound), indexHigh - Len(highBound))
Console.WriteLine(foundLink)
intCounter = intCounter + (Len(lowBound) + Len(highBound) + Len(foundLink) - 1)
Else
intCounter = Len(pageText)
End If
Loop
Console.ReadLine()
myReader.Close()
My.Computer.FileSystem.DeleteFile("C:\~\VisualStudio\BeginnerPractice\TextFileDotCom_GrabLinkNames\TextFileDotCom_GrabLinkNames\bin\debug\directory.html")
End Sub
End Module

VB.net Get text/string from html element

I'm having major trouble trying to get bits of elements and returning the strings.
I have a few exmaples of trying to get the strings and what not but failing hard.
HTML Phrasing is difficult for me to do so help would be appreciated.
Explantion of what I need:
I need to get the strinsg of different elements off this site when entering a IP
http://www.ip-tracker.org/
I need pretty much all the details but into labels or text boxes.
Or this with xml phrasing
http://ip-api.com/xml/8.8.8.8
So here is the exmaple that i've used so far but haven't got far with it.
Exmaple 1:
Dim client As New WebClient
Dim ip As String
Dim city As String
Dim Region As String
Private Function GetIp()
Try
Dim Page As String = client.DownloadString("http://www.ip-tracker.org/locator/ip-lookup.php?ip=82.16.38.43/")
ip = Page.Substring(Page.IndexOf("IP Address:") + 80)
ip = ip.Substring(0, city.IndexOf(" </td") + 30)
TextBox2.Text = ("IP Address: " + ip)
Catch ex As Exception
city = "Unable to lookup"
End Try
Return 0
End Function
To call it:
getViews()
Try xml linq
Imports System.Xml
Imports System.Xml.Linq
Module Module1
Dim url As String = "http://ip-api.com/xml/8.8.8.8"
Sub Main()
Dim query As XElement = XElement.Load(url)
Dim status As String = query.Element("status").Value
Dim country As String = query.Element("country").Value
Dim region As String = query.Element("region").Value
Dim regionName As String = query.Element("region").Value
Dim city As String = query.Element("city").Value
Dim zip As String = query.Element("zip").Value
Dim lat As Double = query.Element("lat").Value
Dim lon As Double = query.Element("lon").Value
Dim timezone As String = query.Element("timezone").Value
Dim isp As String = query.Element("isp").Value
Dim org As String = query.Element("org").Value
Dim _as As String = query.Element("as").Value
Dim subQuery As String = query.Element("query").Value
End Sub
End Module

How modify VB.Net code for save webpages as mht automatically?

I have a simple VB.Net program for saving webpages as mht format
currently I'm using the following way:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("http://www.google.com")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim SaveFileDialog1 As New SaveFileDialog()
SaveFileDialog1.Filter = "mht files (*.mht)|*.mht|All files (*.*)|*.*"
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
fileNamePath = SaveFileDialog1.FileName
SavePage(WebBrowser1.Url.ToString, fileNamePath)
End If
End Sub
Private Sub SavePage(ByVal Url As String, ByVal FilePath As String)
Dim iMessage As CDO.Message = New CDO.Message
iMessage.CreateMHTMLBody(Url, CDO.CdoMHTMLFlags.cdoSuppressObjects, "", "")
Dim adodbstream As ADODB.Stream = New ADODB.Stream
adodbstream.Type = ADODB.StreamTypeEnum.adTypeText
adodbstream.Charset = "UTF-8"
adodbstream.Open()
iMessage.DataSource.SaveToObject(adodbstream, "_Stream")
adodbstream.SaveToFile(FilePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
End Sub
My code work fine, but the save process is like a normal save page in a browser. Right-Click > Save page as ... and select a direction with a name for saving file
Is there a way that save operation to be performed automatically? without any popup windows, just give the program a direction and a file name in the code
for example :
SavePage("http://google.com", "C:\google.mht")
this code didn't work and i have error Write to file failed. for the following code
adodbstream.SaveToFile(FilePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
Imports ADODB
Imports CDO
Public Class Form1
Dim fileNamePath = "C:\"
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button1.Click
WebBrowser1.Navigate(TextBox1.Text)
End Sub
Private Sub SavePage(ByVal Url As String, ByVal FilePath As String)
Try
Dim iMessage As CDO.Message = New CDO.Message
iMessage.CreateMHTMLBody(Url, CDO.CdoMHTMLFlags.cdoSuppressObjects, "", "")
Dim adodbstream As ADODB.Stream = New ADODB.Stream
adodbstream.Type = ADODB.StreamTypeEnum.adTypeText
adodbstream.Charset = "UTF-8"
adodbstream.Open()
iMessage.DataSource.SaveToObject(adodbstream, "_Stream")
adodbstream.SaveToFile(FilePath & CheckAndClean(TextBox1.Text) & ".mht", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
Catch ex As Exception
End Try
End Sub
Private Function CheckAndClean(ByVal StringToCheck As String) As String
Dim sIllegal As String = "\,/,:,*,?," & Chr(34) & ",<,>,|"
Dim arIllegal() As String = Split(sIllegal, ",")
Dim sReturn As String
sReturn = StringToCheck
For i = 0 To arIllegal.Length - 1
sReturn = Replace(sReturn, arIllegal(i), "")
Next
Return sReturn
End Function
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
SavePage(TextBox1.Text, fileNamePath)
End Sub
Try:
adodbstream.SaveToFile(FilePath & "Filename.mht", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)

sending email in vb.net in HTML formatted page

I made email form in vb.net it works but i need to send a mail using html format which i made that also works but when i receive mail the value written in text box is not coming in mail. what is problem in this?
Imports System
Imports System.Net.Mail
Imports System.Net
Imports System.IO
Imports System.Configuration
Partial Class Form
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub submit_button_Click(sender As Object, e As EventArgs) Handles submit_button.Click
SendHTMLMail()
End Sub
' Method Which is used to Get HTML File and replace HTML File values with dynamic values and send mail
Public Sub SendHTMLMail()
Dim reader As New StreamReader(Server.MapPath("html.html"))
Dim readFile As String = reader.ReadToEnd()
Dim myString As String = ""
myString = readFile
myString = myString.Replace("$$Company_Name$$", "Company_Name")
myString = myString.Replace("$$Contact_Person_Name$$", "Txt_ContactPerson.Text")
myString = myString.Replace("$$Contact_Person_Mobile_No$$", "Txt_Contact_No.Text")
myString = myString.Replace("$$Telephone_No$$", "Txt_TelNo.Text")
myString = myString.Replace("$$Email_Id$$", "Txt_Email.Text")
myString = myString.Replace("$$Registered_Address$$", "Txt_Address.Text")
myString = myString.Replace("$$Year_Of_Commencement_Of_Business$$", "Txt_CommenceYear.Text")
myString = myString.Replace("$$Income_TAX_PAN_No$$", "Txt_IncomeTax.Text")
myString = myString.Replace("$$CST_No$$", "Txt_CSTNo.Text")
myString = myString.Replace("$$VAT_TIN_No$$", "Txt_VatNo.Text")
myString = myString.Replace("$$Type_Of_Business_Entity$$", "RadioButtonList1.SelectedValue.ToString")
myString = myString.Replace("$$Full_Details$$", "")
myString = myString.Replace("$$Business_History$$", "Txt_BusinessHistory.Text")
myString = myString.Replace("$$No_Of_Employees$$", "Txt_NoOfEmployees.Text ")
myString = myString.Replace("$$Annual_Turnover$$", "")
myString = myString.Replace("$$References$$", "")
Dim MyMailMessage As New MailMessage()
MyMailMessage.From = New MailAddress("test#eternalbs.com", "Eternal")
MyMailMessage.To.Add("test#eternalbs.com")
MyMailMessage.Subject = "Eternal"
MyMailMessage.Body = myString.ToString()
MyMailMessage.IsBodyHtml = True
' Dim SMTPServer As New SmtpClient("smtp.gmail.com")
Dim SMTPServer As New SmtpClient()
SMTPServer.Host = "208.91.198.227"
SMTPServer.Port = 587
SMTPServer.Credentials = New System.Net.NetworkCredential("test#eternalbs.com", "admin123")
'SMTPServer.EnableSsl = True
Try
SMTPServer.Send(MyMailMessage)
Response.Write("Successfull")
Catch ex As SmtpException
Response.Write(ex)
End Try
End Sub
End Class
For receving the value of any textbox which user has inserted, the value must not be in double inverted commas. In the SendHTMLmail() function, the second parameter where you want the textbox value to be captured, u just need to remove the double inverted commas
myString = myString.Replace("$$Contact_Person_Name$$", Txt_ContactPerson.Text)
Try this for every textbox whose value u want to capture. Hope it helps.