VB.Net JSON data import - json

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

Related

How can I show my JSON results in a Textbox instead of writing to the Console?

I'm running into a little problem that I haven't found a way to to solve.
I haven't found a forum where this specific problem is addressed, I really hope to find some help.
Here is my code:
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://pastebin.com/raw/dWjmfW8N"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim jsontxt As String
jsontxt = reader.ReadToEnd()
Dim myJObject = JObject.Parse(jsontxt)
For Each match In myJObject("matches")
Console.WriteLine(match("http")("host").ToString)
Next
End Sub
End Class
Here is the output:
223.16.205.13
190.74.163.58
71.7.168.29
117.146.53.244
31.170.146.28
118.36.122.169
123.7.117.78
113.61.154.182
36.48.37.191
113.253.179.234
124.13.29.41
180.122.74.183
121.157.114.93
39.78.35.216
176.82.1.100
201.143.142.75
222.117.29.229
89.228.209.185
59.153.89.245
148.170.162.37
112.160.243.23
62.101.254.177
190.141.161.149
121.132.177.79
79.165.124.174
118.39.91.43
220.83.82.58
220.161.101.195
190.218.188.86
123.241.174.77
219.71.218.113
81.198.205.2
1.64.205.1
190.204.66.180
203.163.241.36
36.34.148.33
221.124.127.89
115.29.210.231
39.121.63.13
178.160.38.191
117.146.55.217
149.91.99.49
220.93.231.104
49.245.71.40
211.44.70.107
37.119.247.51
222.101.54.200
178.163.102.223
119.198.145.129
188.26.240.141
115.29.233.160
190.164.29.145
94.133.185.144
181.37.196.134
116.88.213.9
115.2.194.11
1.226.12.161
178.63.73.210
49.149.194.242
14.32.29.251
59.0.191.68
58.122.168.43
142.129.230.137
105.145.89.51
201.243.97.65
175.37.162.102
186.88.141.126
105.148.43.100
60.179.173.21
69.115.51.207
90.171.193.132
14.64.76.165
121.127.95.80
175.211.168.48
99.240.74.72
58.153.174.2
119.77.168.142
121.170.47.232
58.243.20.124
199.247.243.234
47.111.76.211
93.72.213.251
218.32.44.73
220.83.90.204
119.158.102.20
95.109.55.204
106.5.19.223
190.199.215.69
190.218.57.249
36.102.72.163
219.78.162.215
177.199.151.96
196.93.125.34
211.58.150.166
180.131.163.40
93.156.97.81
159.89.22.81
130.0.55.156
186.93.202.111
195.252.44.173
What I want to do is to transfer that console output to my Textbox1.Text. Can anyone please show me a way to solve this?
A somewhat simplified method, using WebClient's DownloadStringTaskAsync to download the JSON.
You don't need special treatment here, strings that represent IpAddresses are just numbers and dots and the source encoding is probably UTF8.
After that, just parse the JSON and Select() the property values you care about, transform the resulting Enumerable(Of JToken) to an array of strings and set the array as the source of a TextBox.Lines property.
You can store the lines collection for any other use, in case it's needed.
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using client As New WebClient()
Dim json = Await client.DownloadStringTaskAsync([The URL])
Dim parsed = JObject.Parse(json)
Dim lines = parsed("matches").
Where(Function(jt) jt("http") IsNot Nothing).
Select(Function(jt) jt("http")("host").ToString()).ToArray()
TextBox1.Lines = lines
End Using
End Sub
There's no need to transfer anything. If you want the data in a TextBox then put it in a TextBox. You can then output the same data using Console.WriteLine or Debug.WriteLine. You can use a loop:
Dim hosts As New List(Of String)
For Each match In myJObject("matches")
hosts.Add(match("http")("host").ToString())
Next
Dim text = String.Join(Environment.NewLine, hosts)
myTextBox.Text = text
Console.WriteLine(text)
You could also use LINQ:
Dim text = String.Join(Environment.NewLine, myJObject("matches").Select(Function(match) match("http")("host").ToString()))
myTextBox.Text = text
Console.WriteLine(text)
Alternative approach to display collection of things in Winforms are ListView, DataGridView or other collection controls depends on desired usage.
Add ListView control in designer and next code will fill it with received values.
Shared ReadOnly client As HttpClient = New HttpClient()
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim response As HttpResponseMessage =
Await client.GetAsync("https://pastebin.com/raw/dWjmfW8N")
response.EnsureSuccessStatusCode()
Dim jsonBody As String = Await response.Content.ReadAsStringAsync()
Dim myJObject = JObject.Parse(jsonBody)
ListView1.Items.Clear()
For Each match In myJObject("matches")
ListView1.Items.Add(match("http")("host").ToString)
Next
End Sub

Consuming data from webservice with vb.net

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

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 results from a class to other class

How can i send results from a class to other class, the results it from my mysql results.
example first class it databaseConnection and i want to send the result from select method to other class.
Here my code:
Dim data As ArrayList
Public Function selectAll() As ArrayList
Dim mySelectQuery As String = "SELECT * FROM users"
Dim myConnection As New MySqlConnection(connectionString)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
' Always call Read before accessing data.
data = myReader
' always call Close when done reading.
myReader.Close()
' Close the connection when done with it.
myConnection.Close()
End Function
i updated a code to look more clear
and receiver Method look like this.
Private Sub home_Load(sender As Object, e As EventArgs) Handles MyBase.Load
db = New db()
Dim r = db.selectAll()
MsgBox("It work" & db.selectAll().ToString())
End Sub
You can do this numerous ways.
However, i would probably output the results to a variable in the first function. Then simply access the variable as needed from the second.
Example:
in first method:
Dim list As New List(Of String)
While myReader.Read()
list.add(myreader.GetString(0))
End While
second:
Dim listTransfer as list(Of String)
Foreach ele as String in classname.list ' Replace classname '
listTransfer.add(ele)
Next

how to parse html contents returned as a response from a webserver and show a specific tag value in a combobox in desktop application in vb.net

i am trying to fetch some data from Url using Httpwebrequest/response, i am getting response which i am showing in a msgbox. It show whole HTML contents.
Now my i want to fetch a specific tag(TD tag) value and show all its value in a combobox in vb.net desktop application.
my code to get response from webserver is :
enter code here
Imports System.IO
Imports System.Net
Imports System.Xml
Imports System.Text.Encoder
Public Class login
Private Sub login_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End
End Sub
Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint
End Sub
Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
Dim strId As String = txt_uid.Text
Dim strPwd As String = txt_pwd.Text
Dim oEncoder As New System.Text.ASCIIEncoding
Dim postData As String = "UM_username=" + strId
postData += ("&UM_password=" + strPwd)
Dim data As Byte() = oEncoder.GetBytes(postData)
MsgBox(postData)
Dim webStream As Stream
Dim webResponse As String = ""
Dim req As HttpWebRequest
Dim res As HttpWebResponse
Dim Output As String
'Dim Posit1 As Int32
'Dim Posit2 As Int32
req = WebRequest.Create("http://localhost/basic_framework/index.php?menu=login&UM_email=" & strId & "&UM_password=" & strPwd)
req.ContentType = "application/x-www-form-urlencoded"
req.KeepAlive = False
req.Method = "POST"
res = req.GetResponse()
webStream = res.GetResponseStream()
Dim webStreamReader As New StreamReader(webStream)
While webStreamReader.Peek >= 0
Output = webStreamReader.ReadToEnd()
RichTextBox1.Text = Output
Msgbox(Output)
End While
End Sub
End Class
this code get the response from url and show it in a richtextbox or msgbox
Now i want to get a specific tag value (say, td, option values) and show it in a combobox in my vb.net application form dynamically.It would be needed to parse html content then get that tag value . Please suggest me a way......
If parsing needed , how to parse html contents to get only specific tag value in a combobox in vb.net form
Well...if you can be sure that your request returns valid XHTML (which is XML indeed), you might be able to use an XPath expression.
For the most complicated cases (e.g., an AJAX web-site, etc.) you could use HTMLUnit library with iKVM.