System.Threading.Tasks error when trying to call API - vb.net

I am new to vb.net code. I have to call external API from vb.net. I tried the code below but it is throwing an error - getting issue as
System.Threading.Tasks.k`1
Public Shared Async Function GetToken_saka() As Task(Of sakaweb)
Dim req As New HttpRequestMessage(HttpMethod.Post, "https://api.qa.se.com/token")
' req.Content = New FormUrlEncodedContent(New Dictionary < String, String > {
' {"client_id", "your client_id"},
' {"client_secret", "your client_secret"},
' {"grant_type", "client_credentials"}
'});
Dim dct As New Dictionary(Of String, String)
dct.Add("client_id", "your_client_id")
dct.Add("client_secret", "your_client_secret")
dct.Add("grant_type", "client_credentials")
Dim htc As New HttpClient
req.Content = New FormUrlEncodedContent(dct)
Dim response = Await htc.SendAsync(req)
response.EnsureSuccessStatusCode()
'Dim payload = JObject.Parse(Await response.Content.ReadAsStringAsync())
Dim payload = JsonConvert.DeserializeObject(response.ToString)
Dim token = payload.Value(Of String)("access_token")
Dim t1 As sakaweb = Nothing
Return t1
'Dim t1 As New Task("K")
'Return t1
End Function

Related

Google Sheets API V4 VB Net BatchUpdate - Upload

I am attempting to load the contents of a CSV file directly to an existing Google Sheet using the batch update method.
The problem is that my code is only uploading the last record, but from what I can tell the request object has all the data.
So far I am able to loop through the CSV file and cast each row to a Google Sheets ValueRange and add each ValueRange to a data object in order to apply it to the RequestBody required by the Google Sheets API.
This is all based on the API documentation available from Google.
Google Sheets API V4 Batch Update
I tossed in a few Message Boxes just to see what is happening in the background.
Below is the code I am using currently, and a sample set of data you can put into a csv file to run.
It appears that I am missing something with the upload request itself, if anyone has any input or experience with this I can't seem to get past this.
*Note: this code is simply a VB .Net winform app with a single button added to the form.
Imports System.Threading
Imports Google.Apis.Sheets.v4
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Microsoft.VisualBasic.FileIO
Imports Google.Apis.Sheets.v4.Data
Imports Data = Google.Apis.Sheets.v4.Data
Public Class Form1
Dim ClientID As String = "<GOOGLE CLIENT>.apps.googleusercontent.com"
Dim ClientSecret As String = "<CLIENT SECRET>"
Dim Scopes As String() = {SheetsService.Scope.Spreadsheets}
Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientID,
.ClientSecret = ClientSecret},
Scopes, "user",
CancellationToken.None).Result
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim r As Integer = 1
Dim oblist = New List(Of Object)
Dim sheetsService As SheetsService = New SheetsService(New BaseClientService.Initializer With {
.HttpClientInitializer = credential,
.ApplicationName = "Google-SheetsSample/0.1"
})
Dim spreadsheetId As String = "<SPREADSHEET ID>"
Dim valueInputOption As String = "RAW"
Dim valueRanges As ValueRange = New ValueRange()
Dim data As List(Of Data.ValueRange) = New List(Of Data.ValueRange)
Dim tfp As New TextFieldParser("<PATH TO CSV FILE I WANT TO UPLOAD>")
tfp.SetDelimiters(",")
tfp.TextFieldType = FieldType.Delimited
'tfp.ReadLine() ' skip header
While tfp.EndOfData = False
Dim fields = tfp.ReadFields()
Dim range2 As String = "A" & r ' range to update
valueRanges.MajorDimension = "ROWS" '"ROWS";//COLUMNS
valueRanges.Range = range2 ' apply range to ValueRnage
' My csv has 12 fields
oblist = New List(Of Object)() From {
fields(0), fields(1), fields(2), fields(3), fields(4), fields(5), fields(6), fields(7), fields(8), fields(9), fields(10), fields(11)
}
valueRanges.Values = New List(Of IList(Of Object)) From { ' add list of objects pulled from TextFieldParser to ValueRange
oblist
}
data.Add(valueRanges) ' Add valueRange to data for RequestBody
r += 1 ' Increment Range
End While
MsgBox("Count of value ranges in data object : " & data.Count)
Dim requestBody As Data.BatchUpdateValuesRequest = New Data.BatchUpdateValuesRequest()
requestBody.ValueInputOption = valueInputOption
requestBody.Data = data
MsgBox("Request body data : " & requestBody.Data.Count)
Dim request As SpreadsheetsResource.ValuesResource.BatchUpdateRequest = sheetsService.Spreadsheets.Values.BatchUpdate(requestBody, spreadsheetId)
Dim response As Data.BatchUpdateValuesResponse = request.Execute()
MsgBox("Count of Rows uploaded to google sheet : " & response.TotalUpdatedRows)
End Sub
End Class
CSV - EXAMPLE -
Column 1,Column 2,Column 3,Column 4,Column 5,Column 6,Column 7,Column 8,Column 9,Column 10,Column 11,Column 12
ex12,ex34,ex56,ex78,ex100,ex122,ex144,ex166,ex188,ex210,ex232,ex254
ex13,ex35,ex57,ex79,ex101,ex123,ex145,ex167,ex189,ex211,ex233,ex255
ex14,ex36,ex58,ex80,ex102,ex124,ex146,ex168,ex190,ex212,ex234,ex256
ex15,ex37,ex59,ex81,ex103,ex125,ex147,ex169,ex191,ex213,ex235,ex257
ex16,ex38,ex60,ex82,ex104,ex126,ex148,ex170,ex192,ex214,ex236,ex258
ex17,ex39,ex61,ex83,ex105,ex127,ex149,ex171,ex193,ex215,ex237,ex259
ex18,ex40,ex62,ex84,ex106,ex128,ex150,ex172,ex194,ex216,ex238,ex260
ex19,ex41,ex63,ex85,ex107,ex129,ex151,ex173,ex195,ex217,ex239,ex261
ex20,ex42,ex64,ex86,ex108,ex130,ex152,ex174,ex196,ex218,ex240,ex262
ex21,ex43,ex65,ex87,ex109,ex131,ex153,ex175,ex197,ex219,ex241,ex263
Here I create one code .. The difference is only you pass List to ValueRange whereas there should be IList ..
But for conversion from list to Ilist I used objList.ToList () and I don't know it's drawback you need to check
And also you have to create new object of valueRange within while loop
Dim sheetId = FileId
Dim service = GetGoogleAPPSheetService()
Dim val_range As ValueRange
Dim DataList As List(Of ValueRange) = New List(Of ValueRange)
Dim I As Integer = 0
Dim objList As List(Of Object)
Dim objMainList As List(Of IList(Of Object))
Dim objIlIst As IList(Of Object)
Dim objImainList As IList(Of IList(Of Object))
For Each dr As DataRow In dt.Rows
I += 1
val_range = New ValueRange
val_range.Range = "A" & I.ToString
objList = New List(Of Object) From {dr(0).ToString, dr(1).ToString}
objMainList = New List(Of IList(Of Object)) From {objList.ToList()}
val_range.Values = objMainList.ToList
DataList.Add(val_range)
Next
Dim req_body As BatchUpdateValuesRequest = New BatchUpdateValuesRequest
req_body.ValueInputOption = "RAW"
req_body.Data = DataList.ToList
Dim request As SpreadsheetsResource.ValuesResource.BatchUpdateRequest = service.Spreadsheets.Values.BatchUpdate(req_body, sheetId)
Dim response As BatchUpdateValuesResponse = request.Execute
MsgBox("Count of Rows uploaded to google sheet : " & response.TotalUpdatedRows)
Catch ex As Exception
Throw ex
End Try

How do I insert new sheet in Existing google spreadsheet using vb.net?

I am manage to create spreadsheet on google drive using following code.
Now I want to add new sheets in that created spreadsheet.
When I Create new spreadsheet , it contains default sheet having name Sheet1 but I want to rename that sheet or insert more than one sheets in Spreadsheet
Public Function Create(ByVal FileName As String) As String
Try
Dim service = GetGoogleAPPDriveService()
Dim fileMetadata = New Google.Apis.Drive.v3.Data.File()
fileMetadata.Name = FileName
fileMetadata.MimeType = "application/vnd.google-apps.spreadsheet"
Dim request As FilesResource.CreateRequest = service.Files.Create(fileMetadata)
request.SupportsTeamDrives = True
request.Fields = "id"
System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllcertification)
Dim file = request.Execute
Return file.Id
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPDriveService() As DriveService
Try
Dim Scopes1 As String() = {DriveService.Scope.Drive, DriveService.Scope.DriveFile}
Dim ClientId As String = ""
Dim ClientSecret As String = ""
Dim UserCredentials As UserCredential
Dim stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientId = GoogleClientSecrets.Load(stream).Secrets.ClientId
Dim stream1 = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientSecret = GoogleClientSecrets.Load(stream1).Secrets.ClientSecret
Dim cs = New ClientSecrets()
cs.ClientId = ClientId
cs.ClientSecret = ClientSecret
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(cs, Scopes1, Environment.UserName,
CancellationToken.None, New FileDataStore("MyAppsToken", True)).Result
Dim service = New DriveService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function
Public Function AcceptAllcertification(ByVal sender As Object, ByVal Certification As X509Certificate, ByVal Chain As X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
You need to use the Sheets API for that. Have a look at the AddSheetRequest
Its hard to identify which request has to be used in .net from json file .
I succeed to add sheet in existing Spread sheet . Here I am put vb.net code if any one needed
Public Function Addsheet(ByVal FileId As String, ByVal sheetName As String) As String
Try
Dim serv = GetGoogleAPPSheetService()
Dim updatesheet = New BatchUpdateSpreadsheetRequest
Dim Req_Request As Request = New Request
Dim Req_AddSheet As New AddSheetRequest
Dim prop As New SheetProperties
prop.Title = sheetName
Req_AddSheet.Properties = prop
Req_Request.AddSheet = Req_AddSheet
Dim IList_req As IList(Of Request)
Dim List_req1 = New List(Of Request)
List_req1.Add(Req_Request)
IList_req = List_req1.ToList
updatesheet.Requests = IList_req
Dim req = serv.Spreadsheets.BatchUpdate(updatesheet, FileId)
Dim response = req.Execute
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPSheetService() As SheetsService
Try
Dim UserCredentials As UserCredential
Using stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "token.json" 'System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)
'credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json")
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
End Using
Dim service = New SheetsService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function

VB API Result converts decimal numbers

I have a simple API Post like this
<HttpPost>
Public Function testPost() As IEnumerable(Of sp_select)
Dim _tmplist As New List(Of sp_select)
Dim _Content = jsonSerializer.Deserialize(Of myparams)(Request.Content.ReadAsStringAsync().Result)
Dim mandant = _Content.mandant
Using mycon As New dal_globalDataContext
Dim _result = mycon.sp_select(CType(mandant, Decimal)).ToList
If Not _result.Any = False Then
For Each entry In _result
_tmplist.Add(entry)
Next
End If
End Using
Return _tmplist
End Function
All good. But If I parse the result like this:
Public Sub testPost()
Dim client = New System.Net.Http.HttpClient()
client.BaseAddress = New Uri("http://localhost:62068")
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Accept.Add(New System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"))
Dim _datasource As IEnumerable(Of Object) = Nothing
Dim _content = New With {.mandant = 0}
Dim serializer As New JavaScriptSerializer()
Dim arrayJson As String = serializer.Serialize(_content)
Dim responseTask = client.PostAsync("/actionapi/dataSource/testPost/", New StringContent(arrayJson))
responseTask.Wait()
Dim result = responseTask.Result
If result.IsSuccessStatusCode Then
Dim readTask = result.Content.ReadAsAsync(Of IList(Of sp_select))()
readTask.Wait()
_datasource = readTask.Result
Any decimal property of the class has an decimal point. So 1 will be 1.0
Do you know how to prevent this behaviour?

BatchUpdate Rows in Google Sheets using VB.Net

Im having trouble updating rows in Google Sheets using VB.Net.
This is my code:
Dim service = New SheetsService(New BaseClientService.Initializer() With {.HttpClientInitializer = credential, .ApplicationName = ApplicationName})
Dim spreadsheetId As String = "1mW-ndDolz_uECCMmAmKZ-sANoM9H53eqc231g98I06U"
Dim spreadsheet As Spreadsheet = Nothing
Dim content As BatchUpdateSpreadsheetRequest = New BatchUpdateSpreadsheetRequest()
Dim request As Request = New Request()
Dim deleteDimensionRequest As DeleteDimensionRequest = New DeleteDimensionRequest()
Dim dimensionRange As DimensionRange = New DimensionRange()
dimensionRange.Dimension = "A:B"
dimensionRange.StartIndex = 0
dimensionRange.EndIndex = 3
dimensionRange.SheetId = 0
deleteDimensionRequest.Range = dimensionRange
Dim requests As IList(Of Object) = New List(Of Object)()
requests.Add(request)
content.Requests = requests
Try
service.Spreadsheets.BatchUpdate(content, spreadsheetId)
Catch e As IOException
MsgBox(e.Message)
End Try
It shows me an Error saying
Unable to cast object of type
'System.Collections.Generic.List1[System.Object]' to type
'System.Collections.Generic.IList1[Google.Apis.Sheets.v4.Data.Request]'.
What Am I doing wrong here?
I have no idea how VB.NET works, but based on your sample code and the error message, I would assume the problem is this line:
Dim requests As IList(Of Object) = New List(Of Object)()
It should probably be:
Dim requests As IList(Of Request) = New List(Of Request)()
I am sure its working but I don't know its drawbacks
Dim requests As IList(Of Request)
dim Req1 as List(Of Request) = new List(Of Request)
Req1.Add(request)
Requests = Req1.ToList()
content.Requests = requests

The given credentials or configuration format does not fits to the storage provider (Sharpbox)

I am new to cloud storage, I encountered this error
The given credentials or configuration format does not fits to the storage provider
when I tried to read a txt file with token (uploadMe sub). I am using vb. Looking forward to your reply.
My code:
Dim ConsumerKey As String = "******************"
Dim ConsumerSecret As String = "*****************"
Dim config As DropBoxConfiguration = DropBoxConfiguration.GetStandardConfiguration()
Dim requestToken As DropBoxRequestToken
Private Sub AuthorizeMe()
config.AuthorizationCallBack = New Uri("http://www.google.com")
requestToken = DropBoxStorageProviderTools.GetDropBoxRequestToken(config, ConsumerKey, ConsumerSecret)
Dim AuthorizationUrl As String = DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(config, requestToken)
Process.Start(AuthorizationUrl)
End Sub
Private Sub saveMyAuth()
Dim accessToken As ICloudStorageAccessToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(config, ConsumerKey, ConsumerSecret, requestToken)
Dim DropboxStorage As New CloudStorage()
DropboxStorage.Open(config, accessToken)
Dim File As FileStream = New FileStream("c:\TEMP\MyToken.txt", FileMode.Create, System.IO.FileAccess.Write)
DropboxStorage.SerializeSecurityTokenToStream(requestToken, File)
File.Close()
End Sub
Private Sub uploadme()
Try
Dim configio As DropBoxConfiguration = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox)
Dim DropboxStorage As New CloudStorage()
Dim accessToken As ICloudStorageAccessToken
Using fs = File.Open("C:\TEMP\MyToken.txt", FileMode.Open, FileAccess.Read, FileShare.None)
accessToken = DropboxStorage.DeserializeSecurityToken(fs)
End Using
DropboxStorage.Open(configio, accessToken)
Dim srcFile = Environment.ExpandEnvironmentVariables("C:\TEMP\mysqlbackup.xml")
DropboxStorage.UploadFile(srcFile, "/")
DropboxStorage.Close()
Catch ex As Exception
Console.Beep()
Console.Write(ex.Message, "")
End Try
End Sub