private async Task <int> Run() { DropboxCertHelper.InitializeCertPinning(); var accessToken = await this.GetAccessToken(); if (string.IsNullOrEmpty(accessToken)) { return(1); } using (var client = new DropboxClient(accessToken)) { var list = await client.Files.ListFolderAsync(String.Empty); foreach (var item in list.Entries) { Console.WriteLine($"Item: {item} - IsFile: {item.IsFile} - IsFolder: {item.IsFolder}"); } try { var folderArg = new CreateFolderArg("/temp"); var folder = await client.Files.CreateFolderV2Async(folderArg); Console.WriteLine($"Folder created: {folder.Metadata.Name}"); } catch (Exception e) { Console.WriteLine(e); } } return(0); }
private async Task <int> Run() { DropboxCertHelper.InitializeCertPinning(); var accessToken = await this.GetAccessToken(); if (string.IsNullOrEmpty(accessToken)) { return(1); } // Specify socket level timeout which decides maximum waiting time when no bytes are // received by the socket. var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { // Specify request level timeout which decides maximum time that can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; try { var config = new DropboxClientConfig("SimpleTestApp") { HttpClient = httpClient }; var client = new DropboxClient(accessToken, config); await RunUserTests(client); // Tests below are for Dropbox Business endpoints. To run these tests, make sure the ApiKey is for // a Dropbox Business app and you have an admin account to log in. /* * var client = new DropboxTeamClient(accessToken, userAgent: "SimpleTeamTestApp", httpClient: httpClient); * await RunTeamTests(client); */ } catch (HttpException e) { Console.WriteLine("Exception reported from RPC layer"); Console.WriteLine(" Status code: {0}", e.StatusCode); Console.WriteLine(" Message : {0}", e.Message); if (e.RequestUri != null) { Console.WriteLine(" Request uri: {0}", e.RequestUri); } } return(0); }
public async Task <Stream> Download(int userId, string path) { DropboxCertHelper.InitializeCertPinning(); var accessToken = preferenceRepository.FirstOrDefault(x => x.UserId.Equals(userId) && x.Key.Equals(Constants.DropboxAccessToken)); using (var dropboxClient = new DropboxClient(accessToken.Value)) { var result = await dropboxClient.Files.DownloadAsync(path); return(await result.GetContentAsStreamAsync()); } }
private async Task <int> Run() { DropboxCertHelper.InitializeCertPinning(); var uid = await this.AcquireAccessToken(null, IncludeGrantedScopes.None); if (string.IsNullOrEmpty(uid)) { return(1); } // Specify socket level timeout which decides maximum waiting time when no bytes are // received by the socket. var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { // Specify request level timeout which decides maximum time that can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; try { var config = new DropboxClientConfig("SimplePKCEOAuthApp") { HttpClient = httpClient }; var client = new DropboxClient(Settings.Default.RefreshToken, ApiKey, config); // This call should succeed since the correct scope has been acquired await GetCurrentAccount(client); Console.WriteLine("Oauth PKCE Test Complete!"); Console.WriteLine("Exit with any key"); Console.ReadKey(); } catch (HttpException e) { Console.WriteLine("Exception reported from RPC layer"); Console.WriteLine(" Status code: {0}", e.StatusCode); Console.WriteLine(" Message : {0}", e.Message); if (e.RequestUri != null) { Console.WriteLine(" Request uri: {0}", e.RequestUri); } } return(0); }
public static async Task Main() { DropboxCertHelper.InitializeCertPinning(); var sourceFilePath = "Example.txt"; var targetDirectory = "/DotNetApi/Help"; var accessToken = GetAccessToken(); using (var client = GetClient(accessToken)) { await EnsureDirectoryExists(client, targetDirectory); await UploadFile(client, sourceFilePath, targetDirectory); } }
private async Task LoginToDropBoxAsync() { DropboxCertHelper.InitializeCertPinning(); //String accessToken = await GetAccessToken(); String accessToken = await GetAccessToken(); if (accessToken == null || accessToken.Length == 0) { return; } var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { Timeout = TimeSpan.FromMinutes(1) }; var config = new DropboxClientConfig("SampleApp") { HttpClient = httpClient }; var client = new DropboxClient(accessToken, config); //var full = Task.Run( async ()=> await client.Users.GetCurrentAccountAsync(), token).Result; var 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}", 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(" Photo : {0}", full.ProfilePhotoUrl); //invoke Update main UI in Block 2 Dispatcher.Invoke(new Action <Dropbox.Api.Users.FullAccount>(UpdateAccountInfoBlockHandler), full); }
public async Task <IEnumerable <StorageItem> > Get(int userId) { DropboxCertHelper.InitializeCertPinning(); var accessToken = preferenceRepository.FirstOrDefault(x => x.UserId.Equals(userId) && x.Key.Equals(Constants.DropboxAccessToken)); List <StorageItem> list = new List <StorageItem>(); using (var dropboxClient = new DropboxClient(accessToken.Value)) { var result = await dropboxClient.Files.ListFolderAsync("/Homemanagement"); foreach (var item in result.Entries.OrderBy(x => x.IsFile).ThenBy(x => x.Name)) { list.Add(ParseStorageItem(item)); } } return(list); }
public async Task <StorageItem> Upload(int userId, string filename, string accountName, string chargeName, Stream stream) { DropboxCertHelper.InitializeCertPinning(); var accessToken = preferenceRepository.FirstOrDefault(x => x.UserId.Equals(userId) && x.Key.Equals(Constants.DropboxAccessToken)); using (var dropboxClient = new DropboxClient(accessToken.Value)) { var result = await dropboxClient.Files.UploadAsync(new CommitInfo($"/Homemanagement/{accountName}/{chargeName}/{filename}"), stream); return(ParseStorageItem(result)); //var file = result.AsFile; //return new StorageItem //{ // ExternalId = file.Id, // IsFolder = false, // Name = file.Name, // Path = file.PathDisplay, // Size = file.Size //}; } }
public async Task <bool> DownloadBackup() { DropboxCertHelper.InitializeCertPinning(); var accessToken = await GetToken(); try { using (var client = new DropboxClient(accessToken)) { try { var response = await client.Files.DownloadAsync($"/{_filename}"); if (response != null && response.Response.Size > 0) { using (var fileStream = File.Create(_fullFileName)) { (await response.GetContentAsStreamAsync()).CopyTo(fileStream); return(true); } } } catch (Exception e) { WorkspaceLogger.Log.Error(e); return(false); } } } catch (Exception e) { WorkspaceLogger.Log.Error(e); } return(false); }
public async Task <bool> UploadBackup() { DropboxCertHelper.InitializeCertPinning(); var accessToken = await GetToken(); using (var client = new DropboxClient(accessToken)) { try { using (var mem = new MemoryStream(File.ReadAllBytes(_fullFileName))) { var updated = await client.Files.UploadAsync($"/{_filename}", WriteMode.Overwrite.Instance, body : mem); return(updated.Size != 0); } } catch (Exception e) { WorkspaceLogger.Log.Error(e); } return(false); } }
internal ProviderDropbox(Configurations.DataTarget config, LoggerBase logger) : base(config, logger) { // parse config // we assume the target is the token var token = _config.Target; // check for optional path var args = token.Split(';'); foreach (var arg in args) { var keyValue = arg.Split('='); if (keyValue.Length == 2) { switch (keyValue[0].Trim().ToLower()) { case "token": token = keyValue[1].Trim(); break; case "path": _path = keyValue[1].Trim(); break; } } } if (string.IsNullOrEmpty(token)) { _logger.Log(_config.Name, LoggerPriorities.Error, "Token is missing."); return; } // format path if (_path == null) { _path = string.Empty; } if (!_path.StartsWith("/")) { _path = "/" + _path; } if (!_path.EndsWith("/")) { _path += "/"; } // init client DropboxCertHelper.InitializeCertPinning(); _requestHandler = new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }; // Specify socket level timeout which decides maximum waiting time when no bytes are // received by the socket. _httpClient = new HttpClient(_requestHandler) { // Specify request level timeout which decides maximum time that can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; var clientConfig = new DropboxClientConfig(_config.Name) { HttpClient = _httpClient }; _client = new DropboxClient(token, clientConfig); }
private async Task <int> Run() { DropboxCertHelper.InitializeCertPinning(); string[] scopeList = new string[3] { "files.metadata.read", "files.content.read", "account_info.read" }; var uid = await this.AcquireAccessToken(scopeList, IncludeGrantedScopes.None); if (string.IsNullOrEmpty(uid)) { return(1); } // Specify socket level timeout which decides maximum waiting time when no bytes are // received by the socket. var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { // Specify request level timeout which decides maximum time that can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; try { var config = new DropboxClientConfig("SimpleOAuthApp") { HttpClient = httpClient }; var client = new DropboxClient(Settings.Default.AccessToken, Settings.Default.RefreshToken, ApiKey, ApiSecret, config); // This call should succeed since the correct scope has been acquired await GetCurrentAccount(client); Console.WriteLine("Refreshing without scope account_info.read"); var newScopes = new string[] { "files.metadata.read", "files.content.read" }; await client.RefreshAccessToken(newScopes); try { // This should fail since token does not have "account_info.read" scope await GetCurrentAccount(client); } catch (Exception) { Console.WriteLine("Correctly failed with invalid scope"); } Console.WriteLine("Attempting to try again with include_granted_scopes"); await this.AcquireAccessToken(newScopes, IncludeGrantedScopes.User); var clientNew = new DropboxClient(Settings.Default.AccessToken, Settings.Default.RefreshToken, ApiKey, ApiSecret, config); await GetCurrentAccount(clientNew); Console.WriteLine("Oauth Test Complete!"); Console.WriteLine("Exit with any key"); Console.ReadKey(); } catch (HttpException e) { Console.WriteLine("Exception reported from RPC layer"); Console.WriteLine(" Status code: {0}", e.StatusCode); Console.WriteLine(" Message : {0}", e.Message); if (e.RequestUri != null) { Console.WriteLine(" Request uri: {0}", e.RequestUri); } } return(0); }
public async Task <Uri> AddDocument(Meeting meeting, Document document, string path = "") { DropboxCertHelper.InitializeCertPinning(); if (string.IsNullOrEmpty(accessToken)) { throw new ArgumentException("accessToken"); } // Specify socket level timeout which decides maximum waiting time when no bytes are // received by the socket. var httpClient = new HttpClient() { // Specify request level timeout which decides maximum time that can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; var config = new DropboxClientConfig("OpenGovAlerts") { HttpClient = httpClient }; var client = new DropboxClient(accessToken, config); if (string.IsNullOrEmpty(path)) { path = Path.Combine(baseFolder, meeting.Source.Name, meeting.Title, meeting.Date.ToString("yyyy-MM-dd") + "-" + meeting.BoardName); } var filename = new string(document.Title.Select(ch => invalidFileNameChars.Contains(ch) ? '_' : ch).ToArray()); try { CreateFolderResult result = await client.Files.CreateFolderV2Async(path, false); } catch (ApiException <CreateFolderError> ex) { if (ex.ErrorResponse.AsPath.Value.IsConflict) { // The folder already exists. Fine. I feel like I need to shower now. } else { // F**k it, I'm not looking at any of those other properties. throw new ApplicationException(string.Format("Could not create/verify Dropbox folder {1} for document {0} because of error {2}", document.Url, path, ex.Message)); } } catch (Exception e) { throw new ApplicationException(string.Format("Could not create/verify Dropbox folder {1} for document {0} because of error {2}", document.Url, path, e.Message)); } string filePath = Path.Combine(path, filename); try { Stream input = await httpClient.GetStreamAsync(document.Url); FileMetadata file = await client.Files.UploadAsync(filePath, body : input); SharedLinkMetadata link = await client.Sharing.CreateSharedLinkWithSettingsAsync(new CreateSharedLinkWithSettingsArg(file.PathLower)); return(new Uri(link.Url)); } catch (ApiException <UploadError> ex) { throw new ApplicationException(string.Format("Could not upload document {0} to path {1} because of error {2}", document.Url, filePath, ex.Message)); } catch (Exception e) { throw new ApplicationException(string.Format("Could not upload document {0} to path {1} because of error {2}", document.Url, filePath, e.Message)); } }
private async Task <int> Run() { DropboxCertHelper.InitializeCertPinning(); string[] scopeList = new string[] { "files.metadata.read", "files.content.read", "account_info.read", "sharing.read" }; var uid = await AcquireAccessToken(scopeList, IncludeGrantedScopes.None); if (string.IsNullOrEmpty(uid)) { return(1); } // Specify socket level timeout which decides maximum waiting time when no bytes are received by the socket. var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { // Specify request level timeout which decides maximum time that can be spent on download/upload files. Timeout = TimeSpan.FromMinutes(20) }; try { var config = new DropboxClientConfig("SimpleOAuthApp") { HttpClient = httpClient }; var client = new DropboxClient(Settings.Default.AccessToken, Settings.Default.RefreshToken, Settings.Default.ApiKey, Settings.Default.ApiSecret, config); var scopes = new string[] { "files.metadata.read", "files.content.read", "sharing.read" }; await client.RefreshAccessToken(scopes); if (Settings.Default.SharedLinks == null || Settings.Default.SharedLinks.Count == 0) { Settings.Default.SharedLinks = new System.Collections.Specialized.StringCollection(); Console.Write("Shared link URL: "); var line = Console.ReadLine(); while (line.Length > 0) { Settings.Default.SharedLinks.Add(line); Console.Write("Additional shared link URL (leave blank to finish): "); line = Console.ReadLine(); } Settings.Default.Save(); } var sharedLinks = Settings.Default.SharedLinks; foreach (var sharedLinkUrl in sharedLinks) { GetSharedLinkMetadataArg arg = new GetSharedLinkMetadataArg(sharedLinkUrl); var sharedLinkMetaData = await client.Sharing.GetSharedLinkMetadataAsync(arg); var localDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), sharedLinkMetaData.Name); Directory.CreateDirectory(localDir); Console.WriteLine($"Processing shared link name: {sharedLinkMetaData.Name}"); if (Verbose) { Console.WriteLine($"Shared link local folder: {localDir}"); } SharedLink sharedLink = new SharedLink(sharedLinkUrl); ListFolderArg listFolderArg = new ListFolderArg(path: "", sharedLink: sharedLink); var listFiles = await client.Files.ListFolderAsync(listFolderArg); foreach (var listFile in listFiles.Entries) { try { if (Verbose) { Console.WriteLine($"Processing: {listFile.Name}"); } // Get the remote object details var remoteFile = listFile.AsFile; // Construct a reference to the local equivalent var localFile = Path.Combine(localDir, listFile.Name); if (Verbose) { Console.WriteLine($" Local filename: {localFile}"); } // Do we have a file already if (File.Exists(localFile)) { if (Verbose) { Console.WriteLine($" Local file exists. Comparing timestamp"); } var localTimestamp = File.GetLastWriteTimeUtc(localFile); if (Verbose) { Console.WriteLine($" Checking {remoteFile.ServerModified} with {localTimestamp}"); } if (DateTime.Compare(remoteFile.ServerModified, localTimestamp) == 0) { if (Verbose) { Console.WriteLine($" Skipping unchanged file: {listFile.Name}"); } continue; } } GetSharedLinkMetadataArg downloadArg = new GetSharedLinkMetadataArg(sharedLinkUrl, $"/{listFile.Name}"); if (Verbose) { Console.WriteLine($"SharedLinkUrl: {sharedLinkUrl}"); Console.WriteLine($" File Name: {listFile.Name}"); } var download = await client.Sharing.GetSharedLinkFileAsync(downloadArg); Console.WriteLine($" Downloading: {remoteFile.Name}"); using (var ms = new MemoryStream()) { var bytes = await download.GetContentAsByteArrayAsync(); if (bytes.Length > 0) { File.WriteAllBytes(localFile, bytes.ToArray()); File.SetCreationTimeUtc(localFile, remoteFile.ServerModified); File.SetLastWriteTimeUtc(localFile, remoteFile.ServerModified); } else { Console.Error.WriteLine($"No bytes downloaded"); } } } catch (Exception ex) { Console.Error.WriteLine($"Failed during download: ${ex.Message}"); } } if (Verbose) { Console.WriteLine("Download complete!"); } } if (Verbose) { Console.WriteLine("All downloads complete!"); } if (PromptToExit) { Console.WriteLine("Exit with any key"); Console.ReadKey(); } } catch (HttpException e) { Console.WriteLine("Exception reported from RPC layer"); Console.WriteLine(" Status code: {0}", e.StatusCode); Console.WriteLine(" Message : {0}", e.Message); if (e.RequestUri != null) { Console.WriteLine(" Request uri: {0}", e.RequestUri); } } return(0); }