VB.net Unable to cast object of type System.Collections.Generic.list to type string - vb.net

Please forgive me in advanced for my lack of coding knowledge.
I'm using a NuGet package called KuCoin.Net and have everything setup and connected. I can run the command and Place a Buy order so I know my Api settings are correct. The issue I'm having is when I run the following code:
Public Async Function GetBalancesAsync() As Task
Dim kucoinClient = New KucoinClient(New KucoinClientOptions() With {
.ApiCredentials = New KucoinApiCredentials("xxx", "xxx", "xxx"),
.LogLevel = LogLevel.Debug,
.RequestTimeout = TimeSpan.FromSeconds(60),
.FuturesApiOptions = New KucoinRestApiClientOptions With {
.ApiCredentials = New KucoinApiCredentials("xxx", "xxx", "xxx"),
.AutoTimestamp = False
}})
Dim accountData = Await kucoinClient.SpotApi.Account.GetAccountsAsync()
MessageBox.show(accountData.data)
End Function
I guess I'm needing to convert the list to a string so I can display it into a Messagebox.
The Error I recieve is as follows:
Unable to cast object of type 'System.Collections.Generic.List`1[Kucoin.Net.Objects.Models.Spot.KucoinAccount]' to type 'System.String'
Here is some additional info if this helps
Error
accountData
Any help is much appreciated

You can generate your String yourself using a StringBuilder while enumerating through accountData.Data:
Dim sb As New System.Text.StringBuilder
For Each account As Kucoin.Net.Objects.Models.Spot.KucoinAccount In accountData.data
sb.AppendLine(account.ToString)
Next
MessageBox(sb.ToString())
You can change account.ToString to something more appropriate like accout.Number perhaps (see the properties the KucoinAccount object has).

Related

Net.Http.StringContent date format

I'm trying to upload a file with some metadata to a Web API. Everything is fine within the developer environment. But when the same API is hosted in Azure I get the following date parsing error:
Conversion from string "31/03/2019 11:33:52" to type 'Date' is not valid.
I guess StringContent should write the date on ISO 8601 format and it does not.
Next is a simplification of my procedure:
Public Async Function UploadDocFile(oHttpClient as HttpClient, url as string, ByVal oByteArray as Byte(), exs As List(Of Exception)) As Task(Of Boolean)
Dim retval As Boolean
Dim formContent = New Net.Http.MultipartFormDataContent From {
{New Net.Http.StringContent("DateCreated"), now},
{New Net.Http.StreamContent(New IO.MemoryStream(oDocfile.Stream)), "pdf", "pdf.jpg"}
}
Dim response = Await oHttpClient.PostAsync(url, formContent)
If response.StatusCode = 200 Then
retval = True
Else
exs.Add(New Exception(response.ReasonPhrase))
End If
Return retval
End Function
You are using a Collection Initializer to add items to the MultipartFormDataContent; you're expected to follow this overload of the Add method, which accepts two parameters of type HttpContent and String, respectively.
Thus, the second value enclosed in the braces ({}) should be the name of the data content, not its value. On the other hand, the parameter passed to the StringContent constructor should be the value (content), not the name. You basically have them swapped out. If you'd had Option Strict set to On (which is something you should do, BTW), you would've gotten a compiler error and would've easily identified the mistake.
Your code should look something like this:
Dim formContent = New Net.Http.MultipartFormDataContent From
{
{New Net.Http.StringContent(Now.ToString("SomeFormat")), "DateCreated"},
' More values.
}
..where SomeFormat is a format supported by the web API that you're using.

How do I get the Kind of Elements in an Array using Roslyn

I am trying to get the Type that is iterated through using Roslyn. I can get the fact that the object is defined as String() using
Dim ElementTypeInfo As TypeInfo = SemanticModel.GetTypeInfo(ForEachStatement.Expression)
Dim expressionType As ITypeSymbol = ElementTypeInfo.Type
and in the Visual Studio debugger I can look at expressionType.ElementType and find out it is a String. But when I try to access ElementType in code I get an error saying the ElementType is not a member of ITypeSymbol.
If you know that expressionType is going to be an array, you can cast it to IArrayTypeSymbol. After that, you will be able to access its ElementType:
Dim expressionType = DirectCast(elementTypeInfo.Type, IArrayTypeSymbol)
Dim elementType As ITypeSymbol = expressionType.ElementType

RESTful API call in SSIS package

As part of a SSIS (2005) package I am calling a RESTful API through a script component (VB.NET). I am getting the records back OK. The problem I have though is processing the format it comes back in so I can output it (split into the separate output columns) within the data flow and write into a SQL table. Don't know where to start - anyone got any ideas? I have no control over the API so am stuck with this format.
Here is the schema as per the API documentation:
{StatusMessage : <string>, Unit : <string> [ { VehicleID : <int>, RegistrationNumber : <string>, DistanceTravelled : <double>} ] }
And here is a sample of the data returned (it comes back as a single line of text):
{"VehicleDistance":
[
{
"VehicleId":508767,
"RegistrationNumber":"BJ63 NYO",
"DistanceTravelled":0.09322560578584671
},
{
"VehicleId":508788,
"RegistrationNumber":"BJ63 NYL",
"DistanceTravelled":6.1591048240661621
},
{
"VehicleId":508977,
"RegistrationNumber":"PE12 LLC",
"DistanceTravelled":60.975761413574219
},
{
"VehicleId":510092,
"RegistrationNumber":"BJ64 FCY",
"DistanceTravelled":14.369173049926758
},
{
"VehicleId":510456,
"RegistrationNumber":"BJ63 NYY",
"DistanceTravelled":4.04599142074585
},
{
"VehicleId":513574,
"RegistrationNumber":"BL64 AEM",
"DistanceTravelled":302.150390625
}
],
"StatusMessage":null,
"Unit":"imperial",
"HttpStatus":200
}
This is Javscript Object Notation AKA JSON and you need to deserialise it. The problem is that using SSIS is tricky with third party tools that are popular (and fast) but VB.Net actually has a built in class to serialise and deserialise JSON called JavaScriptSerializer
First add a Reference to your project called System.Web.Extensions and then you can use the JavaScriptSerializer to deserialise your JSON.
I've put your JSON in a file for easier handling so first I have to...
Dim sJSON As String = ""
Using swReadFile As New System.IO.StreamReader("E:\JSON.txt")
sJSON = swReadFile.ReadToEnd()
End Using
The rest is the pertinent bit, so first add 2 Imports...
Imports System.Collections.Generic
Imports System.Web.Script.Serialization
Then for example we can...
Dim lvSerializer As JavaScriptSerializer = New JavaScriptSerializer()
lvSerializer.MaxJsonLength = 2147483644
Dim dictParsedJSONPairs As Dictionary(Of String, Object) = lvSerializer.Deserialize(Of Dictionary(Of String, Object))(sJSON)
If dictParsedJSONPairs.ContainsKey("VehicleDistance") AndAlso _
TypeOf dictParsedJSONPairs("VehicleDistance") Is ArrayList Then
Dim ArrayEntries As ArrayList = DirectCast(dictParsedJSONPairs("VehicleDistance"), ArrayList)
For Each ArrayEntry As Object In ArrayEntries
Dim DictEntry As Dictionary(Of String, Object) = DirectCast(ArrayEntry, Dictionary(Of String, Object))
If DictEntry.ContainsKey("VehicleId") Then Console.WriteLine("VehichleId:" & DictEntry("VehicleId"))
Next
End If
If dictParsedJSONPairs.ContainsKey("Unit") Then
Console.WriteLine("Unit is " & dictParsedJSONPairs.Item("Unit"))
End If
Clearly you should research JSON before launching into serious use. The object can be nested JSON (i.e. Dictionary(Of String, Object)), a number of some sort, a string or an ArrayList
It could be a bit late but you may want to have a look at json.net from Newtonsoft (website). The component provided contains .Net 2.0 version.
Using it in a SSIS script task is quite simple. I did it in SSIS2008 based on .Net 3.5 to parse JSON string like below. And according to the document, it should work for .Net 2.0 version as well.
//I assume you had obtained JSON in string format
string JasonBuffer;
//define Json object
JObject jObject = JObject.Parse(JasonBuffer);
//In my example the Json object starts with result
JArray Results = (JArray)jObject["result"];
//loop the result
foreach (JObject Result in Results)
{
//for simple object
JObject joCustomer = (JObject)Result["Customer"];
//do something...
//for complex object continue drill down
foreach (JObject joSection in Result["Sections"])
{
foreach (JObject joDepartment in joSection["Departments"])
{
foreach (JObject joItem in joDepartment["Items"])
{
}
You can find some actual code here: link

Windows Phone VB Web Request

does anybody has an idea how I can perform an asynchronus Post Request in VB.Net for Windows Phone 8?
I tried a lot but nothing worked... also this http://msdn.microsoft.com/de-de/library/system.net.httpwebrequest.begingetrequeststream.aspx didn't work.
Thanks a lot.
I had to figure this out for myself a while ago. Let me see what I can do to help.
Posting a web request is actually simpler than that link shows. Here's what I do.
First, I create a MultipartFormDataContent:
Dim form as New MultipartFormDataContent()
Next, I add each string I want to send like this:
form.Add(New StringContent("String to sent"), "name of the string you are sending")
Next, create a HttpClient:
Dim httpClient as HttpClient = new HttpClient()
Next, we'll create a HttpResponseMessage and post your information to the url of your choice:
Dim response as HttpResponseMessage = Await httpClient.PostAsync("www.yoururl.com/wherever", form)
Then, I usually need the response as a string, so I read the response to a string:
Dim responseString as String = Await response.Content.ReadAsStringAsync()
This will give you the response you wanted, if that's what you wanted.
Here's an example of a method I use:
Public Async Function GetItems() As Task
Dim getUrl As String = "https://myapiurl.com/v3/get"
Dim responseText As String = String.Empty
Dim detailType As String = "complete"
Try
Dim httpClient As HttpClient = New HttpClient()
Dim form As New MultipartFormDataContent()
form.Add(New StringContent(roamingSettings.Values("ConsumerKey").ToString()), "consumer_key")
form.Add(New StringContent(roamingSettings.Values("access_token").ToString()), "access_token")
form.Add(New StringContent(detailType.ToString()), "detailType")
Dim response As HttpResponseMessage = Await httpClient.PostAsync(getUrl, form)
responseText = Await response.Content.ReadAsStringAsync()
Catch ex As Exception
End Try
End Function
If you aren't using the Http client libraries, you need to install them like this:
What you need to do to use the HttpClient, is to navigate in Visual Studio, go to Tools->Library Package Manager->Manage Nuget Packages for this solution. When there, search the online section for HttpClient and make sure you have "Include Prerelease" selected in the listbox above the results. (Default is set to "Stable Only")
Then install the package with the ID of Microsoft.Net.Http
Then you'll need to add an Import statement at the beginning of the document you are using it in.
Let me know if this is what you were looking for.
Thanks,
SonofNun

VB.NET Deserialize JSON to anonymous object using newtonsoft returned error

I would like to deserialize the returned JSON from a service call in VB.NET to an anonymous type but I was having error. It works in C# using dynamic type but i dont know how to do it in VB.
Here is my JSON returned from a web service call:
{"format":"png","height":564,"width":864}
Here is my VB code json above assigned to param text:
Dim testObj = Newtonsoft.Json.JsonConvert.DeserializeObject(text)
But when i tried to access testObj.format, an exception was thrown with message
{"Public member 'format' on type 'JObject' not found."}
I already have added Option Strict Off. I dont want to use an Object/Class to deserialize the JSON. If its in C# assigning this to dynamic type will be working fine.
Can anyone please help? I am not expert in VB but I need to have this running on VB. TIA
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim testObj = js.Deserialize(source, New Object().GetType())
Then you can access the key(attribute name)/values via:
value=testobj(key)
One more thing, you can access your Newtonsoft key(attribute name)/values through:
value=testObj.item(key)
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim DeSerialObjEventData = New With {.Prop1 = String.Empty, .Prop2 = String.Empty, .Prop3 = String.Empty}...
Dim testObj = js.DeserializeAnnonomusType(source, DeSerialObjEventData)