Google Drive v3 Resumable Upload - vb.net

I am trying to figure out how to use Google drive v3 resumable upload on vb.net to upload big files.
I've checked this https://developers.google.com/drive/v3/web/resumable-upload and was able to upload small files using basic upload but can't find any code samples for resumable upload using vb.net.

I managed to get it done, here's the final code in case somebody else needs:
Imports System.IO
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v3
Imports Google.Apis.Services
Imports Google.Apis.Upload
Imports Google.Apis.Util.Store
Module Module1
Dim credential As UserCredential
Dim ApplicationName As String = "NET"
Dim Scopes As String() = {DriveService.Scope.Drive}
Sub Main()
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
Dim service = New DriveService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
Task.Run(Async Function()
Await UploadFileAsync(service, credential.Token.AccessToken, "welcome.mp4", "video/mp4", DateTime.Now.ToString("HH:mm:ss tt"))
End Function).GetAwaiter().GetResult()
Console.WriteLine("Press any key to continue...")
Console.ReadKey()
End Sub
Private Async Function UploadFileAsync(service As DriveService, accessToken As String, filePath As String, mimeType As String, newFileName As String) As Task(Of Boolean)
Dim uri As Uri
Dim uploadStream = New System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Using client = New HttpClient()
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken)
client.DefaultRequestHeaders.Add("X-Upload-Content-Type", mimeType)
client.DefaultRequestHeaders.Add("X-Upload-Content-Length", uploadStream.Length.ToString())
Dim request = New HttpRequestMessage(HttpMethod.Post, "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable")
request.Content = New StringContent("{""name"": """ + newFileName + """, ""parents"":[""folder_id_goes_here""]}")
request.Content.Headers.ContentType = New MediaTypeHeaderValue("application/json")
Dim response = Await client.SendAsync(request)
uri = response.Headers.Location
End Using
Dim uploader = ResumableUpload.CreateFromUploadUri(uri, uploadStream, New ResumableUploadOptions())
AddHandler uploader.ProgressChanged, AddressOf Upload_ProgressChanged
Dim progress As IUploadProgress
progress = Await uploader.UploadAsync()
If progress.Status <> UploadStatus.Completed Then
While (Await uploader.ResumeAsync()).Status <> UploadStatus.Completed
Await Task.Delay(10000)
End While
End If
uploadStream.Dispose()
Return True
End Function
Private Sub Upload_ProgressChanged(progress As IUploadProgress)
Console.WriteLine(progress.Status.ToString() & " " & progress.BytesSent)
End Sub
End Module

Related

HttpClient Digest authentication VB.Net

I'm writing an .NET application that uses HttpClient to connect to the API and retrieve video.
The Documentation provided for "Cookie-based authentication" details the following to login:
Call GET /api/getNonce
In response you'll get a JSON object with realm and nonce (nonce is a session key for this user)
Calculate authentication hash auth_digest, using realm and nonce (see algorithm below)
Call and pass the "auth" parameter in the json request body GET /api/cookieLogin
Server will check authentication and set session cookies
Which then expands on "Calculating Authentication Hash" with the following steps:
Call GET /api/getNonce
In response you'll get a JSON object with realm and nonce
Translate user's username to the lower case
Check the required method ("GET" for HTTP GET requests, "POST" for HTTP POST
requests, "PLAY" for RTSP etc)
digest = md5_hex(user_name + ":" + realm + ":" + password)
partial_ha2 = md5_hex(method + ":")
simplified_ha2 = md5_hex(digest + ":" + nonce + ":" + partial_ha2)
auth_digest = base64(user_name + ":" + nonce + ":" + simplified_ha2)
Here auth_digest is the required authentication hash
I use this Article written in C# as a reference, converted it to VB.NET, change a little bit of code in it according to the requirement above and then implemented it into my program. But I always get an error like this
"The remote server returned an error: (403) Forbidden."
When I debug the program, the problem appears when reading DigestAuthFixer.vb class in GrabResponse Function on this line response = CType(request2.GetResponse(), HttpWebResponse) . I suspect that "auth_digest" didn't return the correct value so the web service to deny the request with a 403 error. My question is how to properly implement digest authentication using VB.Net ? Are there any standard methods or do I have to do it from scratch? Thanks in advance.
This is the code that I use to connect to the API and retrieve the video:
Download HTTPClient
Private Shared _host As String = "http://127.0.0.1:7001"
Private Shared _username As String = "user"
Private Shared _password As String = "password"
Dim auto As Boolean = False
Shared ReadOnly client As HttpClient = New HttpClient()
Public Async Function Download_HttpClient(ByVal cameraID As String _
, ByVal videoDT As String _
, ByVal duration As String _
, ByVal resolution As String _
, ByVal path As String) As Task(Of String)
Dim cookieContainer As New CookieContainer
Dim httpClientHandler As New HttpClientHandler
httpClientHandler.AllowAutoRedirect = True
httpClientHandler.UseCookies = True
httpClientHandler.CookieContainer = cookieContainer
Dim httpClient As New HttpClient(httpClientHandler)
Dim err As Boolean = False
Dim downloadFileName As String
'SET HTTPCLIENT HEADERS
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)")
'httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml")
httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+json,application/json")
httpClient.DefaultRequestHeaders.Add("Accept-Charset", "ISO-8859-1")
Dim downloadId As String = Nothing
Try
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 Or SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls
'GET USER RIGHTS
Dim login_url As String = _host + "/api/getNonce"
Dim login_parameter As String = "?user_name =" + _username + "&password=" + _password
Dim login_response As HttpResponseMessage = Await httpClient.GetAsync(login_url + login_parameter)
Dim login_contents As String = Await login_response.Content.ReadAsStringAsync()
'CALCULATE AUTHENTICATION HASH
Dim dir As String = "/dir/index.html"
Dim url As String = _host + "/api/getNonce"
Dim digest As NUI.DigestAuthFixer = New NUI.DigestAuthFixer(url, _username.ToLower, _password)
Dim auth As String = digest.GrabResponse(dir)
'CALL POST /api/cookieLogin
Dim client As HttpClient = New HttpClient
client.DefaultRequestHeaders.Accept.Add(New System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"))
Dim postData As New List(Of KeyValuePair(Of String, String))
postData.Add(New KeyValuePair(Of String, String)("auth_digest ", auth))
Dim content As New FormUrlEncodedContent(postData)
content.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/x-runtime-guid")
Dim response As HttpResponseMessage = client.PostAsync(New Uri(_host + "/api/cookieLogin"), content).Result
If response.IsSuccessStatusCode Then
MsgBox("POST CookieLogin Successfully")
Else
MsgBox(response)
End If
Catch ex As Exception
MessageBox.Show("Invalid response from the server due to connection limitation or firewall blocking your request")
Return ex.ToString()
End Try
'CREATE DOWNLOAD URL
Dim download_url As String = _host + "/media/" + cameraID + ".mkv"
Dim download_param As String = "?pos=" + videoDT + "&duration=" + duration + "&resolution=" + resolution
Dim downloadFile As String = download_url + download_param
'GET REQUEST AND DOWNLOAD
Dim file_response = Await httpClient.GetAsync(downloadFile)
Dim file_header = file_response.Content.Headers.GetValues("Content-Disposition")
Dim temp_string() As String = file_header.ToArray()
temp_string = temp_string(0).Split("=")
downloadFileName = temp_string(1).Replace("""", "")
Try
Using fs As New FileStream(path & downloadFileName, FileMode.Create)
Await file_response.Content.CopyToAsync(fs)
End Using
Catch ex As Exception
MessageBox.Show("Directory does not exists, please manually change the folder target")
Return ex.ToString()
End Try
Return "Download successfully"
End Function
DigestAuthFixer.vb class
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Security.Cryptography
Imports System.Text.RegularExpressions
Imports System.Net
Imports System.IO
Imports System.Net.Http
Namespace NUI
Public Class DigestAuthFixer
Private Shared _host As String
Private Shared _user As String
Private Shared _password As String
Private Shared _realm As String
Private Shared _nonce As String
Private Shared _qop As String
Private Shared _cnonce As String
Private Shared _cnonceDate As DateTime
Private Shared _nc As Integer
Public Sub New(ByVal host As String, ByVal user As String, ByVal password As String)
_host = host
_user = user
_password = password
End Sub
Private Function CalculateMd5Hash(ByVal input As String) As String
Dim inputBytes As Byte() = Encoding.GetEncoding("ISO-8859-1").GetBytes(input)
Dim hash = MD5.Create().ComputeHash(inputBytes)
Dim sb As New System.Text.StringBuilder()
For Each b In hash
sb.Append(b.ToString("x2"))
Next b
Return sb.ToString()
End Function
Private Function GrabHeaderVar(ByVal varName As String, ByVal header As String) As String
Dim regHeader = New Regex(String.Format("{0}=""([^""]*)""", varName))
Dim matchHeader = regHeader.Match(header)
If matchHeader.Success Then Return matchHeader.Groups(1).Value
Throw New ApplicationException(String.Format("Header {0} not found", varName))
End Function
Private Function GetDigestHeader(ByVal dir As String) As String
Dim digest = CalculateMd5Hash(_user.ToLower + ":" + _realm + ":" + _password)
Dim partial_ha2 = CalculateMd5Hash("GET" + ":")
Dim simplified_ha2 = CalculateMd5Hash(digest + ":" + _nonce + ":" + partial_ha2)
Dim auth_digest = (_user.ToLower + ":" + _nonce + ":" + simplified_ha2)
Return auth_digest
End Function
Public Function GrabResponse(ByVal dir As String) As String
Dim url = _host & dir
Dim uri = New Uri(url)
Dim request = CType(WebRequest.Create(uri), HttpWebRequest)
If Not String.IsNullOrEmpty(_cnonce) AndAlso DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0 Then
request.Headers.Add("Authorization", GetDigestHeader(dir))
End If
Dim response As HttpWebResponse
Try
response = CType(request.GetResponse(), HttpWebResponse)
Catch ex As WebException
If ex.Response Is Nothing OrElse (CType(ex.Response, HttpWebResponse)).StatusCode <> HttpStatusCode.Unauthorized Then Throw
Dim wwwAuthenticateHeader = ex.Response.Headers("WWW-Authenticate")
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader)
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader)
_qop = "auth"
_nc = 0
_cnonce = New Random().[Next](123400, 9999999).ToString()
_cnonceDate = DateTime.Now
Dim request2 = CType(WebRequest.Create(uri), HttpWebRequest)
request2.Headers.Add("Authorization", GetDigestHeader(dir))
response = CType(request2.GetResponse(), HttpWebResponse)
End Try
Dim reader = New StreamReader(response.GetResponseStream())
Return reader.ReadToEnd()
End Function
End Class
End Namespace

upload files to Google drive in VB.NET - searching for working code

I want to upload txt files to my google drive using vb.net , I was searching for about a 2 hours and found this Upload and download to Google Drive using VB.NET Form
Imports Google.Apis.Auth
Imports Google.Apis.Download
'Dev Console:
'https://console.developers.google.com/
'Nuget command:
'Install-Package Google.Apis.Drive.v2
Private Service As DriveService = New DriveService
Private Sub CreateService()
If Not BeGreen Then
Dim ClientId = "your client ID"
Dim ClientSecret = "your client secret"
Dim MyUserCredential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientId, .ClientSecret = ClientSecret}, {DriveService.Scope.Drive}, "user", CancellationToken.None).Result
Service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = MyUserCredential, .ApplicationName = "Google Drive VB Dot Net"})
End If
End Sub
Private Sub UploadFile(FilePath As String)
Me.Cursor = Cursors.WaitCursor
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim TheFile As New File()
TheFile.Title = "My document"
TheFile.Description = "A test document"
TheFile.MimeType = "text/plain"
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)
Me.Cursor = Cursors.Default
MsgBox("Upload Finished")
End Sub
Can't get this code to work .. can someone help me fix this code or post here other working vb.net code?
Here is the code step by step:
1. Create a Console VB.NET app.
2. Install the NuGet package.
Open View > Other Windows > Package Manager Console and type:
Install-Package Google.Apis.Drive.v2
The output should look like:
PM> Install-Package Google.Apis.Drive.v2
...
Adding 'Google.Apis 1.9.2' to YourApp.
Successfully added 'Google.Apis 1.9.2' to YourApp.
Adding 'Google.Apis.Auth 1.9.2' to YourApp.
Successfully added 'Google.Apis.Auth 1.9.2' to YourApp.
Adding 'Google.Apis.Drive.v2 1.9.2.1940' to YourApp.
Successfully added 'Google.Apis.Drive.v2 1.9.2.1940' to YourApp.
PM>
3. Copy and paste the following code in Module1.vb:
Imports Google.Apis.Auth
Imports Google.Apis.Download
' Your original code was missing the following "Imports":
Imports Google.Apis.Drive.v2
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports System.Threading
Imports Google.Apis.Drive.v2.Data
Module Module1
' Call UploadFile(...) from your programs Main():
Sub Main()
UploadFile("C:\file_to_upload.txt")
End Sub
Private Service As DriveService = New DriveService
Private Sub CreateService()
Dim ClientId = "your client ID"
Dim ClientSecret = "your client secret"
Dim MyUserCredential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientId, .ClientSecret = ClientSecret}, {DriveService.Scope.Drive}, "user", CancellationToken.None).Result
Service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = MyUserCredential, .ApplicationName = "Google Drive VB Dot Net"})
End Sub
Private Sub UploadFile(FilePath As String)
'Not needed from a Console app:
'Me.Cursor = Cursors.WaitCursor
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim TheFile As New File()
TheFile.Title = "My document"
TheFile.Description = "A test document"
TheFile.MimeType = "text/plain"
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)
'' You were mmissing the Upload part!
UploadRequest.Upload()
Dim file As File = UploadRequest.ResponseBody
' Not needed from a Console app:
'Me.Cursor = Cursors.Default
MsgBox("Upload Finished")
End Sub
End Module
Do not forget to replace:
Path of file to upload.
Your client ID.
Your client secret.
Get your client ID and client secret here: https://console.developers.google.com/apis/credentials/oauthclient/
And that's it! Your file should appear on https://drive.google.com/drive/my-drive
It works!
TheFile.Title = "My document.txt"'I added extension.
TheFile.Description = "A test document"
TheFile.MimeType = ""'I left it blank,because type has been added before
I don't understand "client ID" but somehow I finished it after 30minutes of trying.

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

Importing Google Drive Quickstart Code to Visual Basic

I am trying to get the Quickstart code for .Net imported to Visual Basic (VB .NET) and I had some errors. I am a newbie to this kind of programming. Would appreciate some pointers, or someone pointing out something that is fundamentally wrong with the code.
Appreciate the help!
The errors that I get when I try to compile the Console App are:
Error 2 Argument not specified for parameter 'arg' of 'Private Shared Function GetAuthorization(arg As Google.Apis.Authentication.OAuth2.DotNetOpenAuth.NativeApplicationClient) As DotNetOpenAuth.OAuth2.IAuthorizationState'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 22 86 Nipod Drive Console
Error 3 'BaseClientService' is ambiguous in the namespace 'Google.Apis.Services'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 23 48 Nipod Drive Console
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports Google.Apis.Services
Namespace GoogleDriveSamples
Class DriveCommandLineSample
Shared Sub Main(ByVal args As String)
Dim CLIENT_ID As [String] = "YOUR_CLIENT_ID"
Dim CLIENT_SECRET As [String] = "YOUR_CLIENT_SECRET"
'' Register the authenticator and create the service
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthorization)
Dim service = New DriveService(New BaseClientService.Initializer() With { _
.Authenticator = auth _
})
Dim body As New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("document.txt")
Dim stream As New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
Console.WriteLine("File id: " + file.Id)
Console.WriteLine("Press Enter to end this process.")
Console.ReadLine()
End Sub
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState( New () {DriveService.Scopes.Drive.GetStringValue()})
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Console.Write(" Authorization Code: ")
Dim authCode As String = Console.ReadLine()
Console.WriteLine()
' Retrieve the access token by using the authorization code:
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
End Namespace
I reliase this is an old subject, but this may help someone in future, make sure you compile in framework 3.5
Sorry cant seem to edit or delete my previous answer, for anyone in future, this should help:
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports System.Security
Imports Google.Apis.Services
Public Class GoogleDrive
Public Function UploadFile() As Boolean
Const CLIENT_ID As String = "xxxxxxxxxxxxx.apps.googleusercontent.com"
Const CLIENT_SECRET As String = "-yyyyyyyyyyyyyyyyyyyyyyy"
'Register the authenticator and create the service
Dim provider As NativeApplicationClient = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim getAuth As Func(Of NativeApplicationClient, IAuthorizationState) = AddressOf GetAuthorization
Dim auth As OAuth2Authenticator(Of NativeApplicationClient) = New OAuth2Authenticator(Of NativeApplicationClient)(provider, getAuth)
Dim service = New DriveService(New BaseClientService.Initializer() With {.Authenticator = auth})
Dim body As File = New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("D:\document.txt")
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
MessageBox.Show("File : " & file.Id)
End Function
Private Function GetAuthorization(ByVal Client As NativeApplicationClient) As IAuthorizationState
Dim RetVal As IAuthorizationState
Dim state As IAuthorizationState = New AuthorizationState(New String() {DriveService.Scopes.Drive.GetStringValue()})
'Check to see if we have a saved refresh token
If My.Settings.SavedAuth.ToString <> "" Then
state.RefreshToken = My.Settings.SavedAuth
If (Client.RefreshToken(state)) Then
Return state
End If
End If
'Get the auth URL:
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = Client.RequestUserAuthorization(state)
'Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
'wait until user has entered the code
Dim authCode As String = InputBox("Authorisation code", "Authorisation Code", "")
'Retrieve the access token by using the authorization code:
RetVal = Client.ProcessUserAuthorization(authCode, state)
'store the refresh token
Call StoreRefreshToken(state.RefreshToken)
Return RetVal
End Function
Private Function LoadRefreshToken() As String
Return My.Settings.SavedAuth
End Function
Private Sub StoreRefreshToken(ByVal Token As String)
My.Settings("SavedAuth") = Token
My.Settings.Save()
End Sub
End Class

Upload and download to Google Drive using VB.NET Form [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to figure out the codes for visual basic .net 2008 of a program (WinForms) that could upload and download some files to and from my google drive account.
Someone can help me?
It took a long time to find some code that worked and I never did find anything written in vb.net. Everything I found was written for C#. Well after doing a bunch of conversion I was able to get some things working. However it was very little and I had to figure out the rest. So to make other people's life so much easier here is working vb.net code for Drive v2 & OAuth 2.0:
Imports System.Threading
Imports System.Threading.Tasks
Imports Google
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth
Imports Google.Apis.Download
'Dev Console:
'https://console.developers.google.com/
'Nuget command:
'Install-Package Google.Apis.Drive.v2
Private Service As DriveService = New DriveService
Private Sub CreateService()
If Not BeGreen Then
Dim ClientId = "your client ID"
Dim ClientSecret = "your client secret"
Dim MyUserCredential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientId, .ClientSecret = ClientSecret}, {DriveService.Scope.Drive}, "user", CancellationToken.None).Result
Service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = MyUserCredential, .ApplicationName = "Google Drive VB Dot Net"})
End If
End Sub
Private Sub UploadFile(FilePath As String)
Me.Cursor = Cursors.WaitCursor
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim TheFile As New File()
TheFile.Title = "My document"
TheFile.Description = "A test document"
TheFile.MimeType = "text/plain"
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)
Me.Cursor = Cursors.Default
MsgBox("Upload Finished")
End Sub
Private Sub DownloadFile(url As String, DownloadDir As String)
Me.Cursor = Cursors.WaitCursor
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim Downloader = New MediaDownloader(Service)
Downloader.ChunkSize = 256 * 1024 '256 KB
' figure out the right file type base on UploadFileName extension
Dim Filename = DownloadDir & "NewDoc.txt"
Using FileStream = New System.IO.FileStream(Filename, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim Progress = Downloader.DownloadAsync(url, FileStream)
Threading.Thread.Sleep(1000)
Do While Progress.Status = TaskStatus.Running
Loop
If Progress.Status = TaskStatus.RanToCompletion Then
MsgBox("Downloaded!")
Else
MsgBox("Not Downloaded :(")
End If
End Using
Me.Cursor = Cursors.Default
End Sub
If you don't know the URL to download the file, then you can use this code to get one:
Dim Request = Service.Files.List()
Request.Q = "mimeType != 'application/vnd.google-apps.folder' and trashed = false"
Request.MaxResults = 2
Dim Results = Request.Execute
For Each Result In Results.Items
MsgBox(Result.DownloadUrl & vbCrLf & Result.Title & vbCrLf & Result.OriginalFilename)
Next
Please look at the .NET samples found on the Google Drive SDK website found below.
Google Drive SDK Documentation
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DriveQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-dotnet-quickstart.json
static string[] Scopes = { DriveService.Scope.DriveReadonly };
static string ApplicationName = "Drive API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine("Files:");
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
}
}
}
Hope this helps you.