Function is trying to convert to boolean somewhere - vb.net

I have a function in Winforms VB.Net and when I call this function I keep getting an exception saying I can't convert a String to Boolean. However, I can't see where it is trying to convert anything to a Boolean. Code is below
Public Async Function UploadArrayToDropbox(client As DropboxClient, folder As String, fileName As String, fileArray As ArrayList) As Task
Dim stream As New MemoryStream
Using r As StreamWriter = New StreamWriter(stream)
For i As Integer = 0 To fileArray.Count - 1
r.WriteLine(fileArray(i).ToString)
Next
r.Flush()
stream.Position = 0
Using rd As StreamReader = New StreamReader(stream)
Dim response = Await client.Files.UploadAsync(Convert.ToString(folder & Convert.ToString("/")) & fileName, WriteMode.Overwrite.Instance, rd.ReadToEnd)
rd.Close()
End Using
r.Close()
End Using
End Function

Dim response = Await client.Files.UploadAsync(Convert.ToString(folder & Convert.ToString("/")) & fileName, WriteMode.Overwrite.Instance, rd.ReadToEnd)
Should be
Dim response = Await client.Files.UploadAsync(Convert.ToString(folder & Convert.ToString("/")) & fileName, WriteMode.Overwrite.Instance, body:=rd)
From Maurice ;)

Related

how to use ZoomNet DownloadFileAsync

I'm using a Nuget package Jericho /ZoomNet, trying to download a zoom recording (mp4) [winform App]
I'm not sure how the DownloadFileAsync() works to save the File from the Stream, I keep getting task cancelled exception
Can you point to any similar examples ?
UPDATE
So i talked to the Author of the package,
he made a beta release to download large files more efficiently, and also showed me you can add your own client object to control the timeout according to file size, also using the ConfigureAwait(False) was necessary.
Dim myHttpClient = New HttpClient() With {
.Timeout = TimeSpan.FromMinutes(10) }
Dim azoomClient = New ZoomClient(connectionInfo,
myHttpClient)
Dim sourceStream = Await
azoomClient.CloudRecordings.DownloadFileAsync(fdownloadFileName, ct).ConfigureAwait(False)
Using outStream = File.OpenWrite(DestFileName)
sourceStream.CopyTo(outStream)
End Using
This is the code I've tried
Private azoomClient = New ZoomClient(connectionInfo)
Dim fdownloadFileName As String = "c:\zoomrec1.mp4"
Dim ct As New Threading.CancellationToken
Dim sourceStream As Stream
sourceStream = Await azoomClient.CloudRecordings.DownloadFileAsync(fdownloadFileName, ct).ConfigureAwait(False)
DumpStream(sourceStream, DestFileName)
Private Async Function DumpStream(ByVal outStream As Stream, ByVal outputFileName As String) As Task
Try
' Dump the contents of a stream to a file
outStream.Flush()
Dim SavePos As Long = outStream.Position ' Save the original position in the stream
outStream.Seek(0, SeekOrigin.Begin)
Dim f As Stream = File.OpenWrite(outputFileName)
CopyStream(outStream, f)
outStream.Position = SavePos ' Go back to the original postion in the stream
f.Close()
Catch ex As Exception
MessageBox.Show("Error:DumpStream()>" & ex.Message)
End Try
End Function
Public Shared Sub CopyStream(ByVal input As Stream, ByVal output As Stream)
Try
' Copy the contents of one stream to another stream
Dim buf As Byte() = New Byte(8 * 1024 - 1) {} ' A buffer for storing data while copying
Dim len As Integer
len = input.Read(buf, 0, buf.Length)
While len > 0
output.Write(buf, 0, len)
len = input.Read(buf, 0, buf.Length)
End While
Catch ex As Exception
MessageBox.Show("Error:CopyStream()>" & ex.Message)
End Try
End Sub
'''
i can get the download url filename with this call,
'''
Dim apiKey = "abc" Dim apiSecret = "123"
Dim connectionInfo As New JwtConnectionInfo(apiKey, apiSecret)
Dim v As Object = azoomClient.CloudRecordings.GetRecordingInformationAsync(MeetingID)
Dim modelsRecording = Await v
downloadFileName = CStr(modelsRecording.RecordingFiles.Where(Function(z)
z.FileType = Models.RecordingFileType.Video)(0).DownloadUrl)
'''
I updated the code above with a working solution.

Docusign download file from template which get illegal characters in file base64string format using Chilkat and rest api

I can get file from template which passing templateid and documentid, when retrun from api , i will get as base64string format, and when i try to convert as byte,
I get an error "Additional information: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
Here the code which i used to download file from template
Dim rest As New Chilkat.Rest
Dim success As Boolean
Dim bTls As Boolean = True
Dim port As Integer = 443
Dim bAutoReconnect As Boolean = True
success = rest.Connect("demo.docusign.net", port, bTls, bAutoReconnect)
If (success <> True) Then
Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
rest.AddHeader("X-DocuSign-Authentication", "{ ""Username"": ""DocuSign#example.com"", ""Password"":""DocuSign_password"", ""IntegratorKey"":""DocuSign_Integrator_Key"" }")
Dim sbResponseBody As New Chilkat.StringBuilder
success = rest.FullRequestNoBodySb("GET", "/restapi/v2.1/accounts/xxxx/templates/xxxx-xxxx-xxxx-xxxx-xxxx/documents/x", sbResponseBody)
If (success <> True) Then
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
Dim respStatusCode As Integer = rest.ResponseStatusCode
If (respStatusCode >= 400) Then
Debug.WriteLine("Response Status Code = " & respStatusCode)
Debug.WriteLine("Response Header:")
Debug.WriteLine(rest.ResponseHeader)
Debug.WriteLine("Response Body:")
Debug.WriteLine(sbResponseBody.GetAsString())
Exit Sub
End If
Dim jsonResponse As New Chilkat.JsonObject
jsonResponse.LoadSb(sbResponseBody)
Dim pdfBytes As Byte() = Convert.FromBase64String(sbResponseBody.ToString)
Regards,
Aravind
i changed my code from chilkat dll to Docusing dll 3.0.0 , using docusing dll i can download file from envelope, here i past my code , it will useful to some other developer.I am used .net framework code download file from file stream.
Private Function DoWnload(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As String
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using outFile As New System.IO.FileStream("C:\File.pdf", IO.FileMode.Create, IO.FileAccess.Write)
Do
bytesRead = results.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
End Using
Return ""
End Function
Dim envelopeDocItems As List(Of EnvelopeDocItem) = New List(Of EnvelopeDocItem) From {
New EnvelopeDocItem With {
.Name = "Combined",
.Type = "content",
.DocumentId = "combined"
},
New EnvelopeDocItem With {
.Name = "Zip archive",
.Type = "zip",
.DocumentId = "archive"
}
Thanks to Inbar Gazit...
Thanks and Regards,
Aravind
Here is an example: https://www.example-code.com/vbnet/docusign_download_envelope_document.asp
Also see the other VB.NET DocuSign examples: https://www.example-code.com/vbnet/docusign.asp

sending file telegram bot VB.NET

please help, I want to send a file (android.apk) from the bot telegram to the user, but the file the user received is not in the format (apk), how do I resolve this. I use vb.net and the Telegram.Bot library. this my code:
Public Async Function sendMessageFile(ByVal destID As String, ByVal Path As String, Optional ByVal
DescriptionFile As String = "") As Task
Try
Dim objReader As StreamReader
Dim objFS As FileStream
Dim errorf As String = ""
Try
If File.Exists(Path) Then
objFS = New FileStream(Path, FileMode.Open)
objReader = New StreamReader(objFS)
Await bott.SendDocumentAsync(destID, objFS, DescriptionFile)
objReader.Close()
objFS.Close()
objReader.Dispose()
objFS.Dispose()
objFS = Nothing
objReader = Nothing
Else
errorf = "File not found!"
End If
Catch ex As Exception
errorf = ex.Message
End Try
Catch e As Exception
log("sendMessageFile - " & e.Message)
End Try
End Function
'// this code sending file to user
Case "/download"
Await bott.SendChatActionAsync(ID, Telegram.Bot.Types.Enums.ChatAction.UploadDocument)
Const file As String = "C:\Resources\debug.apk"
Await sendMessageFile(ID, file, "TESTING")
'// screenshoot
https://prnt.sc/qf09sn

Neo4j 2.3.0-M01 cypher query from VB.NET failing

Recently installed new version of Neo4j on Windows 7 Prof PC. Able to create nodes using API batch inserts. Cypher queries from web interface work but now fail from VB.NET code at the line after the comment 'retrieve results of query, which will be in JSon. This ran okay on the previous Neo4j version (2.2.x)
Public Shared Function DBQuery(URI As String, PostString As String) As DataView
'runs query and returns JSon results as a dataview
'Uses POST method to access Neo4j Server API
Dim S As String = ""
Dim HttpWReq As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URI)
HttpWReq.Method = "POST"
HttpWReq.ContentType = "application/json"
HttpWReq.Accept = "application/json"
Dim B1() As Byte = System.Text.Encoding.Unicode.GetBytes(PostString, 0, Len(PostString))
'POST query
'http://blog.micic.ch/net/using-neo4j-graph-db-with-c-net
HttpWReq.Connection = "Open"
HttpWReq.ContentLength = B1.Length
Dim newStream As IO.Stream = HttpWReq.GetRequestStream()
'this method closes stream before calling getResponse
Using newStream
newStream.Write(B1, 0, B1.Length)
End Using
'retrieve results of query, which will be in JSon
Dim HttpWResp As System.Net.HttpWebResponse = CType(HttpWReq.GetResponse(), System.Net.HttpWebResponse)
HttpWReq.KeepAlive = False
HttpWReq.Timeout = 15000000
Dim E As System.Text.Encoding = System.Text.Encoding.GetEncoding(HttpWResp.CharacterSet)
Dim SR As IO.StreamReader = New IO.StreamReader(HttpWResp.GetResponseStream, encoding:=E)
S = SR.ReadToEnd 'JSon result
Return JSonToDV(S)
End Function
Documentation for v2.3.0 indicates the need for a different conf file setting, but this is not working. The documentation is at http://neo4j.com/docs/2.3.0-M01/server-configuration.html . The neo4j-server.properties file originally had no entry for org.neo4j.server.database.location=data/graph.db. Adding the suggested line (org.neo4j.server.database.location="C:/Data/Neo4j/UMLS/graph.db") and then the database failed to start. Would appreciate suggested solutions.
The problem was not with Neo4j 2.3.0 but with the VB.NET code. The corrected code, which works is:
Public Shared Function DBQuery(URI As String, PostString As String, method As EnumLib.WebServiceMethod) As DataView
'Used for individual API calls; see BulkUpload for other method
'Uses POST method to access Neo4j Server API
Dim ID As Long = 0
Dim HttpWReq As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URI)
Select Case method
Case EnumLib.WebServiceMethod.POST
HttpWReq.Method = "POST"
Case EnumLib.WebServiceMethod.GET
HttpWReq.Method = "GET"
End Select
HttpWReq.ContentType = "application/json"
HttpWReq.Accept = "application/json"
Dim B1() As Byte = System.Text.Encoding.UTF8.GetBytes(PostString, 0, Len(PostString))
'http://blog.micic.ch/net/using-neo4j-graph-db-with-c-net
HttpWReq.Connection = "Open"
Dim S As String = ""
Try
HttpWReq.ContentLength = B1.Length
Dim newStream As IO.Stream = HttpWReq.GetRequestStream()
'this method closes stream before calling getResponse
Using newStream
newStream.Write(B1, 0, B1.Length)
End Using
Dim HttpWResp As System.Net.HttpWebResponse = CType(HttpWReq.GetResponse(), System.Net.HttpWebResponse)
Dim E As System.Text.Encoding = System.Text.Encoding.GetEncoding(HttpWResp.CharacterSet)
Dim SR As IO.StreamReader = New IO.StreamReader(HttpWResp.GetResponseStream, encoding:=E)
S = SR.ReadToEnd
Catch ex As System.Net.WebException
MsgBox("Message: " & vbLf & ex.Message)
Dim RS As IO.StreamReader = New IO.StreamReader(ex.Response.GetResponseStream)
Dim SS As String = RS.ReadToEnd
PostReturnString = "WebException Error: " & ex.Message & vbLf & vbLf & ex.Status & vbLf & vbLf & SS
' MsgBox("Status: " & vbLf & ex.Status & vbLf & vbLf & SS)
End Try
Return JSonToDV(S)
End Function

streamwriter in windows store app - write text to file in VB

Does anybody have VB code to emulate Streamwriter for Windows Store?
I know it's been replaced by StorageFolder class but there is no VB sample in MSDN and I can't seem to translate properly from c# examples. Any help would be appreciated. I am just trying to write text (CSV) to a file and save it to the documents folder. In the code below windows store want a stream instead of strPath when I try dim-ing a streamwriter. (been playing with pickerdialog too, but that might be the next hurdle).
Dim strpath As String = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary & "\" & strFileName
'Build String for file*******************
Dim swExport As StreamWriter = New StreamWriter(strpath)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Possibly the simplest approach would be to use a MemoryStream if you like StreamWriter, so something like:
Dim sessionData As New MemoryStream()
' TODO: stage data in sessionData
Dim swExport As StreamWriter = New StreamWriter(sessionData)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Dim file As StorageFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync("towns.json", CreationCollisionOption.ReplaceExisting)
Using (fileStream As Stream = await file.OpenStreamForWriteAsync())
sessionData.Seek(0, SeekOrigin.Begin)
await sessionData.CopyToAsync(fileStream)
await fileStream.FlushAsync()
End Using
I was making it too difficult. To write to a file I just needed to use storagefolder and storagefile. I have also included the FileSavePicker in the code (note that filetypechoices is mandatory)
Private Async Function btnExport_Click(sender As Object, e As RoutedEventArgs) As Task
'Calls Filepicker to determine location
'Calls Sqlite to select ALL
'Creates CSV file to be saved at location chosen
'save to file
Dim intCount As Integer = "5"
Dim x As Integer
Dim strLine As String 'hold each line for export file
'Create FileName based on date
Dim strDate As String = Date.Today.ToString("MMddyyyy")
Dim strFileName As String = "Export" & strDate & ".csv"
' Configure save file dialog box
Dim dlgPicker As New Windows.Storage.Pickers.FileSavePicker
'add types for picker (manditory field)
Dim types = New List(Of String)
types.Add(".csv")
types.Add(".txt")
'set picker parameters
dlgPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads
dlgPicker.SuggestedFileName = strFileName '"Document" '
dlgPicker.FileTypeChoices.Add("CSV/TXT", types) 'manditory
dlgPicker.DefaultFileExtension = ".csv" 'Filter files by extension
dlgPicker.CommitButtonText = "Save"
' Show save file dialog box
Dim SaveCSV = Await dlgPicker.PickSaveFileAsync()
'************************get data************
Dim sbExport As Text.StringBuilder = New Text.StringBuilder
sbExport.AppendLine(strHeader)
For x = 0 To intCount - 1
strLine = "Get the text you want to write here"
sbExport.AppendLine(strLine)
Next x
'************************************
'write data to file
Await FileIO.WriteTextAsync(SaveCSV, sbExport.ToString)
Dim mb As MessageDialog = New MessageDialog("Done")
Await mb.ShowAsync()
End Function