Skip to content

Instantly share code, notes, and snippets.

@xeekworx
Created August 20, 2019 14:49
Show Gist options
  • Save xeekworx/fa7f232d3726683d8b7b87cebcbecf59 to your computer and use it in GitHub Desktop.
Save xeekworx/fa7f232d3726683d8b7b87cebcbecf59 to your computer and use it in GitHub Desktop.
Imports System
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Net.Http
Imports System.Runtime.InteropServices
Imports System.Threading.Tasks
Imports Dropbox.Api
Imports Dropbox.Api.Common
Imports Dropbox.Api.Files
Imports Dropbox.Api.Team
Namespace SimpleTest
Partial Class Program
Private Const LoopbackHost As String = "http://127.0.0.1:52475/"
Private ReadOnly RedirectUri As Uri = New Uri(LoopbackHost & "authorize")
Private ReadOnly JSRedirectUri As Uri = New Uri(LoopbackHost & "token")
<DllImport("kernel32.dll", ExactSpelling:=True)>
Private Shared Function GetConsoleWindow() As IntPtr
<DllImport("user32.dll")>
<MarshalAs(UnmanagedType.Bool)>
Private Shared Function SetForegroundWindow(ByVal hWnd As IntPtr) As Boolean
<STAThread>
Private Shared Function Main(ByVal args As String()) As Integer
Dim instance = New Program()
Dim task = Task.Run(CType(AddressOf instance.Run, Func(Of Task(Of Integer))))
task.Wait()
Return task.Result
End Function
Private Async Function Run() As Task(Of Integer)
DropboxCertHelper.InitializeCertPinning()
Dim accessToken = Await Me.GetAccessToken()
If String.IsNullOrEmpty(accessToken) Then
Return 1
End If
Dim httpClient = New HttpClient(New WebRequestHandler With {
.ReadWriteTimeout = 10 * 1000
}) With {
.Timeout = TimeSpan.FromMinutes(20)
}
Try
Dim config = New DropboxClientConfig("SimpleTestApp") With {
.HttpClient = httpClient
}
Dim client = New DropboxClient(accessToken, config)
Await RunUserTests(client)
Catch e As HttpException
Console.WriteLine("Exception reported from RPC layer")
Console.WriteLine(" Status code: {0}", e.StatusCode)
Console.WriteLine(" Message : {0}", e.Message)
If e.RequestUri IsNot Nothing Then
Console.WriteLine(" Request uri: {0}", e.RequestUri)
End If
End Try
Return 0
End Function
Private Async Function RunUserTests(ByVal client As DropboxClient) As Task
Await GetCurrentAccount(client)
Dim path = "/DotNetApi/Help"
Dim folder = Await CreateFolder(client, path)
Dim list = Await ListFolder(client, path)
Dim firstFile = list.Entries.FirstOrDefault(Function(i) i.IsFile)
If firstFile IsNot Nothing Then
Await Download(client, path, firstFile.AsFile)
End If
Dim pathInTeamSpace = "/Test"
Await ListFolderInTeamSpace(client, pathInTeamSpace)
Await Upload(client, path, "Test.txt", "This is a text file")
Await ChunkUpload(client, path, "Binary")
End Function
Private Async Function RunTeamTests(ByVal client As DropboxTeamClient) As Task
Dim members = Await client.Team.MembersListAsync()
Dim member = members.Members.FirstOrDefault()
If member IsNot Nothing Then
Dim userClient = client.AsMember(member.Profile.TeamMemberId)
Await RunUserTests(userClient)
End If
End Function
Private Async Function HandleOAuth2Redirect(ByVal http As HttpListener) As Task
Dim context = Await http.GetContextAsync()
While context.Request.Url.AbsolutePath <> RedirectUri.AbsolutePath
context = Await http.GetContextAsync()
End While
context.Response.ContentType = "text/html"
Using file = File.OpenRead("index.html")
file.CopyTo(context.Response.OutputStream)
End Using
context.Response.OutputStream.Close()
End Function
Private Async Function HandleJSRedirect(ByVal http As HttpListener) As Task(Of OAuth2Response)
Dim context = Await http.GetContextAsync()
While context.Request.Url.AbsolutePath <> JSRedirectUri.AbsolutePath
context = Await http.GetContextAsync()
End While
Dim redirectUri = New Uri(context.Request.QueryString("url_with_fragment"))
Dim result = DropboxOAuth2Helper.ParseTokenFragment(redirectUri)
Return result
End Function
Private Async Function GetAccessToken() As Task(Of String)
Console.Write("Reset settings (Y/N) ")
If Console.ReadKey().Key = ConsoleKey.Y Then
Settings.[Default].Reset()
End If
Console.WriteLine()
Dim accessToken = Settings.[Default].AccessToken
If String.IsNullOrEmpty(accessToken) Then
Try
Console.WriteLine("Waiting for credentials.")
Dim state = Guid.NewGuid().ToString("N")
Dim authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, ApiKey, RedirectUri, state:=state)
Dim http = New HttpListener()
http.Prefixes.Add(LoopbackHost)
http.Start()
System.Diagnostics.Process.Start(authorizeUri.ToString())
Await HandleOAuth2Redirect(http)
Dim result = Await HandleJSRedirect(http)
If result.State <> state Then
Return Nothing
End If
Console.WriteLine("and back...")
SetForegroundWindow(GetConsoleWindow())
accessToken = result.AccessToken
Dim uid = result.Uid
Console.WriteLine("Uid: {0}", uid)
Settings.[Default].AccessToken = accessToken
Settings.[Default].Uid = uid
Settings.[Default].Save()
Catch e As Exception
Console.WriteLine("Error: {0}", e.Message)
Return Nothing
End Try
End If
Return accessToken
End Function
Private Async Function GetCurrentAccount(ByVal client As DropboxClient) As Task
Dim full = Await client.Users.GetCurrentAccountAsync()
Console.WriteLine("Account id : {0}", full.AccountId)
Console.WriteLine("Country : {0}", full.Country)
Console.WriteLine("Email : {0}", full.Email)
Console.WriteLine("Is paired : {0}", If(full.IsPaired, "Yes", "No"))
Console.WriteLine("Locale : {0}", full.Locale)
Console.WriteLine("Name")
Console.WriteLine(" Display : {0}", full.Name.DisplayName)
Console.WriteLine(" Familiar : {0}", full.Name.FamiliarName)
Console.WriteLine(" Given : {0}", full.Name.GivenName)
Console.WriteLine(" Surname : {0}", full.Name.Surname)
Console.WriteLine("Referral link : {0}", full.ReferralLink)
If full.Team IsNot Nothing Then
Console.WriteLine("Team")
Console.WriteLine(" Id : {0}", full.Team.Id)
Console.WriteLine(" Name : {0}", full.Team.Name)
Else
Console.WriteLine("Team - None")
End If
End Function
Private Async Function CreateFolder(ByVal client As DropboxClient, ByVal path As String) As Task(Of FolderMetadata)
Console.WriteLine("--- Creating Folder ---")
Dim folderArg = New CreateFolderArg(path)
Dim folder = Await client.Files.CreateFolderV2Async(folderArg)
Console.WriteLine("Folder: " & path & " created!")
Return folder.Metadata
End Function
Private Async Function ListFolderInTeamSpace(ByVal client As DropboxClient, ByVal path As String) As Task
Dim account = Await client.Users.GetCurrentAccountAsync()
If Not account.RootInfo.IsTeam Then
Console.WriteLine("This user doesn't belong to a team with shared space.")
Else
Try
client = client.WithPathRoot(New PathRoot.Root(account.RootInfo.RootNamespaceId))
Await ListFolder(client, path)
Catch ex As PathRootException
Console.WriteLine("The user's root namespace ID has changed to {0}", ex.ErrorResponse.AsInvalidRoot.Value)
End Try
End If
End Function
Private Async Function ListFolder(ByVal client As DropboxClient, ByVal path As String) As Task(Of ListFolderResult)
Console.WriteLine("--- Files ---")
Dim list = Await client.Files.ListFolderAsync(path)
For Each item In list.Entries.Where(Function(i) i.IsFolder)
Console.WriteLine("D {0}/", item.Name)
Next
For Each item In list.Entries.Where(Function(i) i.IsFile)
Dim file = item.AsFile
Console.WriteLine("F{0,8} {1}", file.Size, item.Name)
Next
If list.HasMore Then
Console.WriteLine(" ...")
End If
Return list
End Function
Private Async Function Download(ByVal client As DropboxClient, ByVal folder As String, ByVal file As FileMetadata) As Task
Console.WriteLine("Download file...")
Using response = Await client.Files.DownloadAsync(folder & "/" & file.Name)
Console.WriteLine("Downloaded {0} Rev {1}", response.Response.Name, response.Response.Rev)
Console.WriteLine("------------------------------")
Console.WriteLine(Await response.GetContentAsStringAsync())
Console.WriteLine("------------------------------")
End Using
End Function
Private Async Function Upload(ByVal client As DropboxClient, ByVal folder As String, ByVal fileName As String, ByVal fileContent As String) As Task
Console.WriteLine("Upload file...")
Using stream = New MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(fileContent))
Dim response = Await client.Files.UploadAsync(folder & "/" & fileName, WriteMode.Overwrite.Instance, body:=stream)
Console.WriteLine("Uploaded Id {0} Rev {1}", response.Id, response.Rev)
End Using
End Function
Private Async Function ChunkUpload(ByVal client As DropboxClient, ByVal folder As String, ByVal fileName As String) As Task
Console.WriteLine("Chunk upload file...")
Const chunkSize As Integer = 128 * 1024
Dim fileContent = New Byte(1048575) {}
New Random().NextBytes(fileContent)
Using stream = New MemoryStream(fileContent)
Dim numChunks As Integer = CInt(Math.Ceiling(CDbl(stream.Length) / chunkSize))
Dim buffer As Byte() = New Byte(131071) {}
Dim sessionId As String = Nothing
For idx = 0 To numChunks - 1
Console.WriteLine("Start uploading chunk {0}", idx)
Dim byteRead = stream.Read(buffer, 0, chunkSize)
Using memStream As MemoryStream = New MemoryStream(buffer, 0, byteRead)
If idx = 0 Then
Dim result = Await client.Files.UploadSessionStartAsync(body:=memStream)
sessionId = result.SessionId
Else
Dim cursor As UploadSessionCursor = New UploadSessionCursor(sessionId, CULng((chunkSize * idx)))
If idx = numChunks - 1 Then
Await client.Files.UploadSessionFinishAsync(cursor, New CommitInfo(folder & "/" & fileName), memStream)
Else
Await client.Files.UploadSessionAppendV2Async(cursor, body:=memStream)
End If
End If
End Using
Next
End Using
End Function
Private Async Function ListTeamMembers(ByVal client As DropboxTeamClient) As Task(Of MembersListResult)
Dim members = Await client.Team.MembersListAsync()
For Each member In members.Members
Console.WriteLine("Member id : {0}", member.Profile.TeamMemberId)
Console.WriteLine("Name : {0}", member.Profile.Name)
Console.WriteLine("Email : {0}", member.Profile.Email)
Next
Return members
End Function
End Class
End Namespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment