How do I load the below structure into VB.Net array / object / class? and how do I get access to specific element?
I retrieved it from the binance api using this link:
https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=30m&limit=2
[
[
1571896800000,
"7412.72000000",
"7414.38000000",
"7361.01000000",
"7376.28000000",
"964.39453100",
1571898599999,
"7124637.09263142"
,8360,
"491.13171700",
"3627861.01587878",
"0"
],
[
1571898600000,
"7376.39000000",
"7395.06000000",
"7337.99000000",
"7370.76000000",
"926.16601400",
1571900399999,
"6820821.48483493",
7666,
"449.47121800",
"3311765.73197726",
"0"
]
]
i know how to parse string, i wonder if there is better / easier way.
This is how i retrieve the data from the API:
Function APICall2(ByVal Security As String, ByVal command As String, Optional ByVal param1 As String = "", Optional ByVal param2 As String = "", Optional ByVal param3 As String = "")
Dim APIUrl As String
APIUrl = "https://api.binance.com/api/v3/" + command + "?symbol=" + Security + "&interval=" + param1 + "&limit=1"
Dim Request As System.Net.HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(APIUrl), System.Net.HttpWebRequest)
Dim Response As System.Net.HttpWebResponse = DirectCast(Request.GetResponse(), System.Net.HttpWebResponse)
Dim Read = New System.IO.StreamReader(Response.GetResponseStream).ReadToEnd
APICall2 = Read
End Function
Like the comments suggested, install Newtonsoft.Json.Net to assist with parsing the json data. Then, it's as simple as
'Array option
Dim stringArray= Newtonsoft.Json.JsonConvert.DeserializeObject(Of String())(yourJsonString)
'List option
Dim listOfStrings = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of String))(yourJsonString)
This essentially parses json "structure" and loads it into your desired collection type.
Related
I want to create API for yobit. For now, I will do something very simple, namely get info.
In Python, the code sort of looks like this
url = 'https://yobit.net/tapi'
values['method'] = method
values['nonce'] = str(int(time.time()))
body = urlencode(values)
signature = hmac.new(self.secret, body, hashlib.sha512).hexdigest()
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': self.key,
'Sign': signature
}
I basically want to replace code hmac.new(self.secret, body, hashlib.sha512).hexdigest() with vb.net equivalent.
This my current code
Public Overrides Sub readbalances()
Dim secret = _secret
Dim url = "https://yobit.net/tapi"
Dim key = New Tuple(Of String, String)("Key", _apiKey)
Dim parameters = "method=getInfo&nonce=" + Str(Int(DateTime.Now))
Dim sig = New System.Security.Cryptography.HMACSHA512().ToString 'What should I put here?
Dim sigtupple = New Tuple(Of String, String)("Sign", sig)
Dim result = CookieAwareWebClient.downloadString1("url", {key, sigtupple}, parameters)
End Sub
What should I do?
Content of downloadString1 is the following but let's just say it performs as expected
Public Shared Function downloadString1(url As String, headers As Tuple(Of String, String)(), postdata As String) As String
Dim wc = New CookieAwareWebClient
For Each header In headers
wc.Headers.Add(header.Item1, header.Item2)
Next
Dim result = wc.UploadString(url, postdata)
Return result
End Function
I am trying to write simple application for myself and when i try to call
getInfo method i always get a error into the response. Key, sign, method or nonce is incorrect. I found a number of examples but i still can't find mistake in my code. Could anyone help me with it?
The code works fine for hitbtc. I know yobit is a bit different but I think I have accomodate that.
My code:
Protected Shared Function readStrings(signatureheader As String, host As String, pathandQuery As String, post As String, secret As String, hasher As System.Security.Cryptography.HMAC, otherHeaders As Tuple(Of String, String)()) As String
'apikey=98998BEEB8796455044F02E4864984F4
'secret=44b7659167ffc38bb34fa35b5c816cf5
hasher.Key = exchanges.getBytes(secret)
Dim url = host + pathandQuery ' url = "https://yobit.net/tapi/"
Dim wc = New CookieAwareWebClient()
Dim sigHash2 = ""
If post = "" Then
sigHash2 = CalculateSignature2(pathandQuery, hasher)
Else
'post = "method=getInfo&nonce=636431012620"
sigHash2 = CalculateSignature2(post, hasher) 'sighash2= "ece0a3c4af0c68dedb1f840d0aef0fd5fb9fc5e808105c4e6590aa39f4643679af5da52b97d595cd2277642eb27b8a357793082007abe1a3bab8de8df24f80d2"
End If
wc.Headers.Add(signatureheader, sigHash2) ' SignatureHeader ="Sign"
Dim response = ""
For Each oh In otherHeaders ' otherHeaders =(0) {(Key, 98998BEEB8796455044F02E4864984F4)} System.Tuple(Of String, String)
wc.Headers.Add(oh.Item1, oh.Item2)
Next
'- wc.Headers {Sign: ece0a3c4af0c68dedb1f840d0aef0fd5fb9fc5e808105c4e6590aa39f4643679af5da52b97d595cd2277642eb27b8a357793082007abe1a3bab8de8df24f80d2 Key: 98998BEEB8796455044F02E4864984F4 } System.Net.WebHeaderCollection
'url = "https://yobit.net/tapi/"
'post = "method=getInfo&nonce=636431012620"
If post = "" Then
response = wc.DownloadString(url)
Else
response = wc.UploadString(url, post) 'response = response "{"success":0,"error":"invalid key, sign, method or nonce"}" String
End If
Return response
End Function
The code has been tested succesfully for hitbtc.
So the crypto part is correct. I put it here anyway for completeness
Protected Shared Function CalculateSignature2(text As String, hasher As System.Security.Cryptography.HMAC) As String
Dim siginhash = hasher.ComputeHash(exchanges.getBytes(text))
Dim sighash = exchanges.getString(siginhash)
Return sighash
End Function
So,
for sanity check
This code works
Public Overrides Sub readbalances()
Dim response = readStrings("X-Signature", "https://api.hitbtc.com", "/api/1/trading/balance?nonce=" + exchanges.getNonce().ToString + "&apikey=" + _apiKey, "", _secret, New System.Security.Cryptography.HMACSHA512(), {})
End Sub
With yobit things are different. I got to use post instead of get. I got to add more headers. However, I think I have fixed that.
It doesn't work.
The python function for yobit API is this I just need to translate that to vb.net which I think I have done faithfully
API Call Authentication in Python ( Working PHP example )
I think the mistake is around here
request_url = "https://yobit.net/tapi";
request_body = "method=TradeHistory&pair=ltc_btc&nonce=123";
signature = hmac_sha512(request_body,yobit_secret);
http_headers = {
"Content-Type":"application/x-www-form-urlencoded",
"Key":yobit_public_key,
"Sign":signature
}
response = http_post_request(request_url,request_body,http_headers);
result = json_decode(response.text);
There the stuff that I copied is method=getInfo&nonce=636431012620 which is what I put in post.
So that seems right.
Looks like it works.
I just need to change the nonce so that it's between 0 to 2^31
So this is the error
post = "method=getInfo&nonce=636431012620
The nonce shouldn't be that big. At most it should be
2147483646
Also though not documented, I must add
content type as one of the header. This is the final solution
Dim nonce = exchanges.getNonce().ToString
Dim content = hashObject("", nonce, "method=getInfo&nonce=")
Dim sighash = computeSig(content)
Dim result = CookieAwareWebClient.downloadString1("https://yobit.net/tapi/", content, {New Tuple(Of String, String)("Key", _apiKey), New Tuple(Of String, String)("Sign", sighash), New Tuple(Of String, String)("Content-Type", "application/x-www-form-urlencoded")})
So I added New Tuple(Of String, String)("Content-Type", "application/x-www-form-urlencoded") as one of the headers
Protected Overridable Function computeSig(content As String) As String
Dim hasher = New System.Security.Cryptography.HMACSHA512(System.Text.Encoding.UTF8.GetBytes(_secret))
Return CalculateSignature2(content, hasher)
End Function
Public Shared Function CalculateSignature2(content As String, hasher As System.Security.Cryptography.HMAC) As String
Dim siginhash = hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(content))
Dim sighash = exchanges.getString(siginhash) 'convert bytes to string
Return sighash
End Function
Public Shared Function downloadString1(url As String, post As String, otherHeaders As Tuple(Of String, String)()) As String
Dim wc = New CookieAwareWebClient()
For Each oh In otherHeaders
wc.Headers.Add(oh.Item1, oh.Item2)
Next
Dim response = String.Empty
Try
If post = "" Then
response = wc.DownloadString(url)
Else
response = wc.UploadString(url, post)
End If
Catch ex As Exception
Dim a = 1
End Try
Return response
End Function
What is the best approach to send a Pushover via VBA?
In Pushover website code example, I didn't find a VBA example.
He is the Function.
PS: I use an auxiliar function to format strings
TesteFunction:
Public Sub Test()
Debug.Print PushOverPost("myApplication", "mySubscriptionGroup", "Hello Stackoverflow!")
End Sub
PushoverFunction:
' Send a post via PushOver
' #param In application as String: The application's token
' #param In group as String: The user/group token
' #param In message as String: The message that you want to send
' #return as String(): The post response
Public Function PushOverPost(ByVal application As String, ByVal group As String, ByVal message As String) As String
Dim xhttp As Object, params As String, url As String
Set xhttp = CreateObject("MSXML2.ServerXMLHTTP")
params = StringFormat("token={0}&user={1}&message={2}", application, group, message)
url = "https://api.pushover.net/1/messages.json"
With xhttp
.Open "POST", url, False
.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
.send params
PushOverPost = .responseText
End With
End Function
Auxiliar Function:
' Generate a string using .NET format, i.e. {0}, {1}, {2} ...
' #param In strValue as String: A composite format string that includes one or more format items
' #param In arrParames as Variant: Zero or more objects to format.
' #return as String: A copy of format in which the format items have been replaced by the string representations of the corresponding arguments.
' #example: Debug.Print StringFormat("My name is {0} {1}. Hey!", "Mauricio", "Arieira")
Public Function StringFormat(ByVal strValue As String, ParamArray arrParames() As Variant) As String
Dim i As Integer
For i = LBound(arrParames()) To UBound(arrParames())
strValue = Replace(strValue, "{" & CStr(i) & "}", CStr(arrParames(i)))
Next
StringFormat = strValue
End Function
I can't seem to work out how to get a value from my string using VB.net
If I have a string in my textbox that says:
WWW-Authenticate: Digest realm="MyServer",qop="auth",algorithm="MD5",maxbuf=1000,nonce="3b010c090c0a0000c0a80157c7007f03c5",opaque="4e6573732041636365737320436f6e74"
How can I get each of the values after the = in the string.
I have tried using
Dim s = "WWW-Authenticate: Digest realm='MyServer',qop='auth',algorithm='MD5',maxbuf=1000,nonce='3b010c090c0a0000c0a80157c7007f03c5',opaque='4e6573732041636365737320436f6e74'"
Dim pattern = "="
Dim matches = Regex.Matches(s, pattern)
Dim values = matches.OfType(Of Match).Select(Function(m) m.Value)
For Each v In values
MsgBox(v)
Next
But it only returns the = in the messagebox.
I want to be able to get just the part after the = sign.
Anyone able to help?
I have tried using the following but it still includes the realm= qop= etc.. in the string. (but includes it at the end of the next item.
Dim s = "WWW-Authenticate: Digest realm='Ness Access Control',qop='auth',algorithm='MD5',maxbuf=1000,nonce='3b010c090c0a0000c0a80157c7007f03c5',opaque='4e6573732041636365737320436f6e74'"
Dim result_array As Array = Split(s, "=", 6)
For Each v In result_array
MsgBox(v)
Next
Regular Expressions!
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim s As String = "WWW-Authenticate: Digest realm='MyServer',qop='auth',algorithm='MD5',maxbuf=1000,nonce='3b010c090c0a0000c0a80157c7007f03c5',opaque='4e6573732041636365737320436f6e74'"
'Regular Expression, matches word before equals, and word after equals
Dim r As New Regex("(\w+)\='([^']+)'")
'All the matches!
Dim matches As MatchCollection = r.Matches(s)
For Each m As Match In matches
'm.Groups(1) = realm, qop, algorithm...
'm.Groups(2) = MyServer, auth, MD5...
Console.WriteLine(m.Groups(2))
Next
Console.ReadLine()
End Sub
End Module
And if you want everything in a nice key-value dictionary:
Dim dict As New Dictionary(Of String, String)
For Each m As Match In matches
'm.Groups(1) = realm, qop, algorithm...
'm.Groups(2) = MyServer, auth, MD5...
dict(m.Groups(1).ToString()) = dict(m.Groups(2).ToString())
Next
A case for a specific string extension.
How to transform a specific formatted string in a Dictionary with keys and values
Public Module StringModuleExtensions
<Extension()>
Public Function ToStringDictionary(ByVal str as String, _
ByVal OuterSeparator as Char, _
ByVal NameValueSeparator as Char) _
As Dictionary(of String, String)
Dim dicText = New Dictionary(Of String, String)()
if Not String.IsNullOrEmpty(str) then
Dim arrStrings() = str.TrimEnd(OuterSeparator).Split(OuterSeparator)
For Each s in arrStrings
Dim posSep = s.IndexOf(NameValueSeparator)
Dim name = s.Substring(0, posSep)
Dim value = s.Substring(posSep + 1)
dicText.Add(name, value)
Next
End If
return dicText
End Function
End Module
Call with
Dim test = "WWW-Authenticate: Digest realm=""MyServer"",qop=""auth"",algorithm=""MD5"", maxbuf=1000,nonce=""3b010c090c0a0000c0a80157c7007f03c5"",opaque=""4e6573732041636365737320436f6e74"""
Dim dict = test.ToStringDictionary(","c, "="c)
For Each s in dict.Keys
Console.WriteLine(dict(s))
Next
(probably you need to remove the WWW-Authenticate line before.
You are looking for the split() function.
Dim logArray() As String
logArray = Split(s, "=")
For count = 0 To logArr.Length - 1
MsgBox(logArray(count))
Next
Hey all i am in need of some help looping thru my Dictionary list. I can not seem to find the correct syntax in order to do so.
Here is my code:
Dim all = New Dictionary(Of String, Object)()
Dim info = New Dictionary(Of String, Object)()
Dim theShows As String = String.Empty
info!Logo = channel.SelectSingleNode(".//img").Attributes("src").Value
info!Channel = .SelectSingleNode("channel.//span[#class='channel']").ChildNodes(1).ChildNodes(0).InnerText
info!Station = .SelectSingleNode("channel.//span[#class='channel']").ChildNodes(1).ChildNodes(2).InnerText
info!Shows = From tag In channel.SelectNodes(".//a[#class='thickbox']")
Select New With {channel.Show = tag.Attributes("title").Value, channel.Link = tag.Attributes("href").Value}
all.Add(info!Station, info.Item("Shows"))
theShows = all.Item("Shows") '<--Doesnt work...
I just want to extract whatever is in "Shows" from the all dictionary.
Your code,
all.Add(info!Station, info.Item("Shows"))
theShows = all.Item("Shows")
The value of info!Station is being used as the KEY value in the all dictionary. Then you attempt to access the value using the constant string "Shows". I'm not sure what your intention was but
theShows = all.Item(info!Station)
should return the value of Shows that was stored using the Key info!Station.
If you want the list of shows as a string, you can do this,
Dim Shows as String = ""
For Each item in theShows
Shows &= item.Show & vbNewLine
Next
You can loop like this
For Each pair As KeyValuePair(Of String, String) In dict
MsgBox(pair.Key & " - " & pair.Value)
Next
source : VB.Net Dictionary
Winston