maplocationsfinder.findlocationsasync trouble - vb.net

Im doing exactly the same as in this question:
How can I call MapLocationFinder.FindLocationsAsync() to get the coordinates for an address without already knowing the latitude and longitude?
However my result.locations list keeps running into an error while result.status is success
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim addressToGeocode As String = "Microsoft"
Dim queryHint As New BasicGeoposition With {.Latitude = 47.643, .Longitude = -122.131}
Dim hintPoint As New Geopoint(queryHint)
Dim result As MapLocationFinderResult = Await MapLocationFinder.FindLocationsAsync(addressToGeocode, hintPoint, 3)
If result.Status = MapLocationFinderStatus.Success Then
Dim test = result.Locations(0) 'xxx
End If
End Sub
"No type information for MapGeocoder.dll"
Have you any helpful references for this?

Related

No Locations in MapLocationFinderResult

I was testing the example by microsoft https://learn.microsoft.com/en-us/windows/uwp/maps-and-location/geocoding
This code should give me a simple output (result = (47.6406099647284,-122.129339994863))
However I get an out of range exception on result.Locations(0). So I dont get any locations in my result.
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim addressToGeocode As String = "Microsoft"
Dim queryHint As New BasicGeoposition With {.Latitude = 47.643, .Longitude = -122.131}
Dim hintPoint As New Geopoint(queryHint)
Dim result As MapLocationFinderResult = Await MapLocationFinder.FindLocationsAsync(addressToGeocode, hintPoint, 3)
If result.Status = MapLocationFinderStatus.Success Then
Dim test = result.Locations(0)
Label1.Text = $"result = ({result.Locations(0).Point.Position.Latitude},{result.Locations(0).Point.Position.Longitude})"
End If
End Sub
If I try to debug native code I get an error "MapGeocoder.pdb could not be loaded". I dont know if this causes the same trouble with the locations.

The GUI is not moving properly

I'm doing a little widget that shows the price of bitcoin using Binance API here
I'm not using Json format as I Just need to parse one string, eventhough I know many of you will say to use json. Anyway, I want to keep the software as simple as possible, but there is a little problem.
I'm downloading the source with webclient and Updating it using a timer.
I think I'm doing a mistake creating every time the new webclient because when I want to move the form, Is not properly mooving even if its not freezing.
The code I'm using is:
Private Sub webclientbtc()
Dim wc As New Net.WebClient
Dim WBTC As IO.Stream = Nothing
wc.Encoding = Encoding.UTF8
WBTC = wc.OpenRead("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR")
Dim btc As String
Using rd As New IO.StreamReader(WBTC)
btc = rd.ReadToEnd
End Using
'---------BTC PRICE---------'
Dim textBefore As String = """lastPrice"":"""
Dim textAfter As String = ""","
Dim startPosition As Integer = btc.IndexOf(textBefore)
startPosition += textBefore.Length
Dim endPosition As Integer = btc.IndexOf(textAfter, startPosition)
Dim textFound As String = btc.Substring(startPosition, endPosition - startPosition)
Dim dNumber As Double = Val(textFound.ToString)
Label1.Text = dNumber.ToString("n2")
'-------------------------------------'
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
webclientbtc()
End Sub
Timer interval is on 1000 ms, which is great to keep me update.
Any idea on how I can avoid the creations of new webclient at every update?
Thanks
Simplified, and using TAP:
Private wc as New WebClient()
Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim s = Await wc.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR")
Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(s)
Label1.Text = d("lastPrice")
End Sub
You need to reference newtonsoft json package and imports it, as well as imports system.collections.generic
If the answer by Caius Jard is too good, you can avoid the use of a JSON deserialiser by using a regex:
Imports System.Net
Imports System.Text.RegularExpressions
Public Class Form1
Dim tim As New Timer()
Private Async Sub UpdateBtc(sender As Object, e As EventArgs)
' temporarily disable the timer in case the web request takes a long time
tim.Enabled = False
' using New Uri() makes sure it is a proper URI:
Dim url = New Uri("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR")
Dim rawJson As String
Using wb As New WebClient()
rawJson = Await wb.DownloadStringTaskAsync(url)
End Using
Dim re = New Regex("""lastPrice"":\s*""([0-9.-]+)""")
Dim lastPrice = re.Match(rawJson)?.Groups(1)?.Value
Dim p As Decimal
lblLastPrice.Text = If(Decimal.TryParse(lastPrice, p), p.ToString("N2"), "Fetch error.")
tim.Enabled = True
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
UpdateBtc(Nothing, EventArgs.Empty)
tim.Interval = 3000
AddHandler tim.Tick, AddressOf UpdateBtc
tim.Start()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If tim IsNot Nothing Then
tim.Stop()
RemoveHandler tim.Tick, AddressOf UpdateBtc
tim.Dispose()
End If
End Sub
End Class
There's no need to re-use the WebClient, creating it is not what is taking up the time.
I prefer to instantiate timers myself: there is no requirement to do so.
It is better to use descriptive names for controls: "Label1" tells you nothing.

Adding reactions by a bot in VB

My bot sends an embed message to a specific channel, after that it automatically ads a reaction to the message.
Examples: "😊" and "😂"
Button to send the embed: (works fine)
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim embed As New EmbedBuilder With {
.ThumbnailUrl = discord.CurrentUser.GetAvatarUrl,
.Title = "Just title.",
.Description = "Enjoy",
.Color = New Discord.Color(255, 0, 0)
}
discord.GetGuild("12345..").GetTextChannel("54321..").SendMessageAsync("", False, embed)
End Sub
Now how to make it add the two reactions after the message is sent? ("😊" and "😂")
I figured out that it could work with the message received handler, here's what I tried. (I'm not sure if it works)
Private Async Function onMsg(message As SocketMessage) As Task
If message.Source = MessageSource.Bot Then
Dim reaction As SocketReaction
Dim rMessage = CType(Await message.Channel.GetMessageAsync(message.Id), RestUserMessage)
If reaction.Emote.Name.Equals("😊") AndAlso
reaction.Emote.Name.Equals("😂")
Else
Dim my_emo1 As Emoji = ("😊")
Dim my_emo2 As Emoji = ("😀")
rMessage.AddReactionAsync(my_emo1)
rMessage.AddReactionAsync(my_emo2)
End If
End Function
Using your current code:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim embed As New EmbedBuilder With {
.ThumbnailUrl = discord.CurrentUser.GetAvatarUrl,
.Title = "Just title.",
.Description = "Enjoy",
.Color = New Discord.Color(255, 0, 0)
}
Dim msg = Await discord.GetGuild("12345..").GetTextChannel("54321..").SendMessageAsync(embed:=embed.Build)
Dim my_emo1 As New Emoji("😊")
Dim my_emo2 As New Emoji("😀")
Await msg.AddReactionAsync(my_emo1)
Await msg.AddReactionAsync(my_emo2)
End Sub

Unsure of how to send an api auth key in vb

I am trying to make a small stat checking app for Fortnite Battle Royale. The TRN Api requires a key to be sent, which I do not have a clue how to do. Thanks in advance.
Public Class Form1
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim webClient As New System.Net.WebClient
Dim Platform As String = ""
Dim UName As String = ""
Dim TRNApiKey As String = "f4d79aad-381b-4b91-87f1-2a1c2ee14cb6"
Dim fortniteStatslookup As String
Dim URL As String
Select Case cboPlatform.Text
Case = "PC"
Platform = "pc"
Case = "Xbox"
Platform = "xbl"
Case = "Playstation"
Platform = "psn"
End Select
UName = txtUName.Text
URL = "https://api.fortnitetracker.com/v1/profile/" & Platform & "/" & UName
webClient.Headers.Add("f4d79aad-381b-4b91-87f1-2a1c2ee14cb6", URL)
fortniteStatslookup = webClient.DownloadString(URL)
txtOutput.Text = fortniteStatslookup
End Sub
End Class
See: MSDN Webclient.Headers documentation
System.Net.WebClient.Headers take a key-value pair, so you will want something like:
webClient.Headers.Add("key", "f4d79aad-381b-4b91-87f1-2a1c2ee14cb6")
or
webClient.Headers.Add("APIkey", "f4d79aad-381b-4b91-87f1-2a1c2ee14cb6")

How to wait for get request without freezing client

I have a simple button which sends a get request to retrieve a txt file on my website. Problem is it freezes the application while retrieving the info. How can I make it so the application doesn't freeze while waiting for the result?
Private Sub cmd_ClickMe_Click(sender As Object, e As EventArgs) Handles cmd_ClickMe.Click
Dim request As String = String.Format("http://www.*****/database/test.txt")
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(request)
MessageBox.Show(result)
End Sub
I've also tried the following but it doesn't work (says "webClient.DownloadStringAsync(myUri)" does not produce a value:
Private Sub cmd_ClickMe_Click_1(sender As Object, e As EventArgs) Handles cmd_ClickMe.Click
Dim request As String = String.Format("http://www.****.com/database/test.txt")
Dim webClient As New System.Net.WebClient
Dim myUri As Uri = New Uri(request)
Dim result As String = webClient.DownloadStringAsync(myUri)
MessageBox.Show(result)
End Sub
Use DownloadStringAsync(Uri) instead of the DownloadString(uri).
The DownloadStringAsync method does not block the calling thread.
Here is an example how to use it:
Dim wc As New WebClient
' Specify that you get alerted
' when the download completes.
AddHandler wc.DownloadStringCompleted, AddressOf AlertStringDownloaded
Dim uri As New Uri("http:\\changeMe.com") 'Pass the URL to here. This is just an example
wc.DownloadStringAsync(uri)
End Sub
Public Shared Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
' If the string request went as planned and wasn't cancelled:
If e.Cancelled = False AndAlso e.Error Is Nothing Then
Dim myString As String = CStr(e.Result) 'Use e.Result to get the String
MessageBox.Show(myString)
End If
End Sub