How to upload file on Google Drive using vb.net? - vb.net

I need help uploading the file to Google Drive.
Everything works fine but with an error during first trial.
During the debug at request.upload the cursor don't wait (wait for the file to upload) and skips to the next line Dim responsefile As New Data.File and I get nothing in request.ResponseBody.
After that I run the function cursor actually waits on request.upload and it uploads file successfully.
I don't know what is actually happening. I checked the data every time and it is the same.
Public Async Function UploadFile3(service As DriveService, FilePath As String) As Tasks.Task(Of Data.File)
If service3.ApplicationName <> "netGDriveApi" Then CreateService()
If IO.File.Exists(FilePath) Then
Dim body As New Data.File()
body.Name = IO.Path.GetFileName(FilePath)
body.Description = "BackUP file"
body.MimeType = "application/octet-stream"
'body.FileExtension = ".bak"
'-------------------------------------------------UPLOAD FILE PROCESS-------------------------------------------------------------
Dim byteArray As Byte() = IO.File.ReadAllBytes(FilePath)
Dim stream As New IO.MemoryStream(byteArray)
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.
Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.
responsefile = request.ResponseBody
If IsNothing(responsefile) Then
MessageBox.Show("Try Again")
Else
MessageBox.Show(responsefile.Id.ToString)
End If
Catch e As Exception
MessageBox.Show("An error occurred: " + e.Message)
Return Nothing
End Try
Else
MessageBox.Show("FILE DOES NOT EXISTS." + FilePath)
Return Nothing
End If
End Function

request.UploadAsync() returns a Task(Of IUploadProgress). At the very least, you should be examining the result of this task. It might give you clues as to the cause of your problems.
For example, while debugging you could do something like the following:
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
Dim Upload As IUploadProgress = Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.
If Upload.Status <> UploadStatus.Completed Then
Dim ex As Exception = Upload.Exception
MessageBox.Show(ex.Message, "UploadAsync Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return Nothing
Else
MessageBox.Show(Upload.Status.ToString, "Upload Status:")
End If
Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.
responsefile = request.ResponseBody
Always check what information methods return, and use that information as necessary in your production code.

The line Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType). Problem is here.
Thanks to #stevec to guide me the error.
The drive service is service3 and in the above line its just written service.Files.Create.
So the actual rectified answer is
Dim request As FilesResource.CreateMediaUpload = service3.Files.Create(body, stream, body.MimeType)

Related

upload files to dropbox using dropbox api

i'm working in a console app that is going to be executed in a server every week, basically it generates a report in excel and then it has to upload it to a folder in dropbox, i've trying a lot of stuff for that last part i finally got this code that does not work but doesn't throw any exception (before i had one that throw and invalid folder format)
Dim _path As String
_path = "/Pruebas/" & Path.GetFileName(FilePath)
Try
Dim rawData = File.ReadAllBytes(FilePath)
Dim str = System.Text.Encoding.Default.GetString(rawData)
Using mem = New MemoryStream(Encoding.UTF8.GetBytes(str))
Dim Up = I.Files.UploadAsync(_path, body:=mem)
MsgBox("Successfully Uploaded")
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
it doesn't throw exception but also doens't work, any help i'll be thankfull.
try this.
Dim Up = I.Files.UploadAsync(_path, WriteMode.Overwrite.Instance, body:=mem)
Link to documentation: http://dropbox.github.io/dropbox-sdk-dotnet/html/M_Dropbox_Api_Files_Routes_FilesUserRoutes_UploadAsync_1.htm

When writing to a file, how do I correctly resolve access to path is denied?

Here is my code:
Dim htmlFile = "\\folder\test.htm"
If File.Exists(htmlFile) Then
File.Delete(htmlFile)
End If
Using strWriter As StreamWriter = New StreamWriter(htmlFile, False)
strWriter.Write("content")
End Using
It works most of the time but occasionally I'll get an exception of "Access to the path '\folder\test.htm' is denied." The exception occurs on this line:
Using strWriter As StreamWriter = New StreamWriter(fileName, False)
How can I ensure that it always creates a new file and never causes an exception?
This routine waits some time in case of error betweens 2 servers writing the same file:
Retry_IT:
try
Dim htmlFile = "\\folder\test.htm"
If File.Exists(htmlFile) Then
File.Delete(htmlFile)
End If
Using strWriter As StreamWriter = New StreamWriter(htmlFile, False)
strWriter.Write("content")
End Using
Catch Exception
Thread.sleep(2000) '2 seconds
Goto Retry_It
End Try

File.Copy not working - no error

Please take a look at this code. For some reason that I can't figure out, the File.Delete() line isn't getting fired and I'm not getting an error.
' hard-coded for testing
Dim path As String = "C:\Program Files (x86)\Test\Program\Program.exe"
Dim appDir As String = My.Application.Info.DirectoryPath
Dim iniPath As String = appDir & "\config.ini"
Dim outputPath As String = appDir & "\output.ini"
Dim textLine As String = ""
Dim reader = File.OpenText(iniPath)
Dim writer = New StreamWriter(outputPath)
' Read the lines in the ini file until the pathToExecutable line is found and write the path to that line
While (InlineAssignHelper(textLine, reader.ReadLine())) IsNot Nothing
If textLine.StartsWith("pathToExecutable=") Then
writer.WriteLine("pathToExecutable=" & path)
Else
writer.WriteLine(textLine)
End If
End While
reader.Dispose()
reader.Close()
writer.Dispose()
writer.Close()
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Return path
You stated that you are not getting an error, but if you don't implement exception handling, you're most probably getting errors and throwing them away (pun intended).
Use a try/catch around any of your System.IO.File operations, and even more, you can implement specific handles and catch specific exceptions.
Try
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Catch ioException As IOException
'The specified file is in use.
MessageBox.Show(ioException.Message)
Catch ex As Exception
'Some other error apart for file in use.
MessageBox.Show(ex.Message)
End Try
Ericosg's suggestion about using a try/catch lead me to the issue: I had the file open in a streamreader earlier in my code, but never closed it there.

FileExist not working vb.net

I really can not understand why the exception is triggered.
I created this code that performs some checks for the correctness of the license.
The function isittrial occurs if the trial software is creating a hidden file, this file is then checked with File.exist.
The problem is the following:
the file is created by isittrial but for some strange reason you enable the exception of file.exist, what can I do to fix it?
I really can not understand why it does not work.
isittrial() 'this function make the file to check
Dim percorsoCompleto As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
Try
If My.Computer.FileSystem.FileExists(directory) Then
Dim fileReader As String
Dim dire As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
fileReader = My.Computer.FileSystem.ReadAllText(directory,
System.Text.Encoding.UTF32)
Dim check = DeCryptIt(fileReader, "aspanet")
Dim datadecripted As String = DeCryptIt(Registry.GetValue("HKEY_CURRENT_USER\Software\cc", "end", ""), "aspanet")
If Date.Now < check And check <> datadecripted Then
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
Else
End If
Else
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
End If
Catch ex As Exception
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
'DeActivate()
'ForceActivation()
End Try
This line
If My.Computer.FileSystem.FileExists(directory) Then
seems to test for the existence of a file passing the name of a directory (or an empty string or whatever, we can see how this variable is initialized). In every case the result will be false.
Then your code jumps to an else block with the same error message of the exception fooling your perception of the error.
Try instead
Dim percorsoCompleto As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
percorsoCompleto = Path.Combine(percorsoCompleto, "Software", "cc.txt")
Try
If My.Computer.FileSystem.FileExists(percorsoCompleto) Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(percorsoCompleto,
System.Text.Encoding.UTF32)
.....
Notice that I have removed the path concatenation with a more fail safe call to Path.Combine

How do I upload data to a server with valid SSL certificate using a client vb.net program?

I am working on a program and uploads a shipping manifest to a the shippers website. When I try to upload, I get a nondescript error back from their server, and when checking with the shipper, they tell me that "there is an issue with the SSL" I am using.
I've spent quite a bit of time piecing together code that, from what I seem to understand, is supposed to work, but I'm not making any progress. As far as I know everything else is fine with the upload, but there is a problem with my SSL certificate
If I understand what this code is supposed to do correctly, I should get a certificate from the shippers website, which allows certification to my program for a space of time during which I can upload the data. I'm really not sure that this is what my code is doing at all, but the only code examples I have seen show it something like this.
Here's my code with the URLs changed:
'This references a custom class that compiles the manifest I'm going to upload
Dim StringToUpload As String = Compile_Manifest(MyDate, UseTestDB)
Dim webClient As New System.Net.WebClient
webClient.Credentials = System.Net.CredentialCache.DefaultCredentials
'From what I understand,
'this is supposed to set up properties used in next section of code
System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Ssl3
System.Net.ServicePointManager.ServerCertificateValidationCallback = _
AddressOf AcceptAllCertifications
'I can see that this reaches the server,
'but I don't know how it relates to the next section of code
'that actually uploads the manifest
Dim ServerRequest As System.Net.WebRequest = _
System.Net.WebRequest.Create("https://www.certify.some-shippper.com:443/somefolder")
Dim ServerResponse As System.Net.WebResponse
ServerResponse = ServerRequest.GetResponse()
ServerResponse.Close()
'This code works for the upload of the manifest,
'and it seems the above code is unrelated and does not use a SSL certificate.
'When this code runs I get the same error back from the shippers server,
'indicating an issue with my SSL, with or without the two sections of code above.
Dim StrResult As String = ""
Dim WrappedString As String = TransmitPLD.WrapPldFile(StringToUpload)
'This references a custom class that wraps the data to upload
'in information from the shipper.
Dim ByesToUpload As Byte() = _
System.Web.HttpUtility.UrlEncodeToBytes(WrappedString, _
System.Text.ASCIIEncoding.ASCII)
Dim Result As Byte() = _
webClient.UploadData("https://www.certify.some-shippper.com:443/somefolder", _
ByesToUpload)
StrResult = System.Web.HttpUtility.UrlDecode(Result, _
System.Text.ASCIIEncoding.ASCII)
MessageBox.Show(StrResult)
So it turns out I went about it the wrong way. I needed to upload my data through System.Net.WebRequest and it takes care of the certificates for me. Not implementing all the parts of the code I needed, it didn't handle the retrieval of the shipper's certificate.
In case anyone else gets confused about the matter like I did, here's my working code for anyone to see, adapt and use. My resource for fixing the code (and by that I mean starting from scratch) was the MSDN page for the WebRequest class, and it has code examples much the same as what I have below in C++, C#, and VB.NET and here is the link.
First there are some global variables that need to be set and class that needs to be created for to store the upload response:
' This is set in the function that Upload function
' and uploads the data in the ReadCallback sub
Private Shared WrappedString As String
' This is used to wait for the callback in the Upload function
Private Shared allDone As New Threading.ManualResetEvent(False)
Friend Class RequestState
' This class stores the request state of the request.
Public request As Net.WebRequest
Public Sub New()
request = Nothing
End Sub ' New
End Class ' RequestState
Then there is a sub needed for the upload part web request which will be called further below in the upload function:
Private Shared Sub ReadCallback(asynchronousResult As IAsyncResult)
Try
Dim myRequestState As RequestState = CType(asynchronousResult.AsyncState, RequestState)
Dim myWebRequest As Net.WebRequest = myRequestState.request
' End the request.
Dim streamResponse As IO.Stream = myWebRequest.EndGetRequestStream(asynchronousResult)
' Convert the string into a byte array.
Dim byteArray As Byte() = System.Text.Encoding.ASCII.GetBytes(WrappedString)
' Write the data to the stream.
streamResponse.Write(byteArray, 0, byteArray.Length)
streamResponse.Close()
' Allow the main thread to resume.
allDone.Set()
Catch ex As Exception
Throw New Exception("Error in " & Reflection.MethodBase.GetCurrentMethod.Name.ToString & " **" & ex.Message, ex)
End Try
End Sub ' ReadCallback
Finally, this is the function that should be called to upload the data, which uses all the code above:
Public Shared Function Upload(ByVal MyDate As Date) As String
Dim StrResult As String = ""
UploadSucess = False
Try
' This is my code that builds the manifest that I want to upload
Dim StringToUpload As String = Compile_PLD200(MyDate)
WrappedString = TransmitPLD.WrapPldFile(StringToUpload)
Dim myWebRequest As Net.WebRequest
myWebRequest = Net.WebRequest.Create("https://www.some.website.com:443/someplace")
' Create an instance of the RequestState and assign
' myWebRequest to it's request field.
Dim myRequestState As New RequestState()
myRequestState.request = myWebRequest
myWebRequest.ContentType = "multipart/mixed; boundary=BOUNDARY"
myRequestState.request.Method = "POST"
' Start the asynchronous 'BeginGetRequestStream' method call.
Dim r As IAsyncResult = CType(myWebRequest.BeginGetRequestStream(AddressOf ReadCallback, myRequestState), IAsyncResult)
' Pause the current thread until the async operation completes.
allDone.WaitOne()
' Send the Post and get the response.
Dim myWebResponse As Net.WebResponse = myWebRequest.GetResponse()
Dim streamResponse As IO.Stream = myWebResponse.GetResponseStream()
Dim streamRead As New IO.StreamReader(streamResponse)
Dim readBuff(256) As [Char]
Dim count As Integer = streamRead.Read(readBuff, 0, 256)
While count > 0
Dim outputData As New [String](readBuff, 0, count)
Console.WriteLine(outputData)
count = streamRead.Read(readBuff, 0, 256)
StrResult += outputData
End While
' Close the Stream Object.
streamResponse.Close()
streamRead.Close()
' Release the HttpWebResponse Resource.
myWebResponse.Close()
Catch ex As Exception
Throw New Exception("Error in " & Reflection.MethodBase.GetCurrentMethod.Name.ToString & " **" & ex.Message, ex)
End Try
Return StrResult
End Function ' Upload
Again here is the MSDN page for the WebRequest class which has a code example too.
Hope this helps anyone who was stuck like I was. And any criticisms as to the implementation of the code are welcome. This just happen to do what I want, I can't say it is the most efficient implementation.