Пример #1
0
        /// <summary>Uploads file in existing folder in Dropbox.</summary>
        /// <param name="folder">
        /// Path to the folder. Always begin with "/" - the root Dropbox folder. Example: "/Contests/Active"
        /// </param>
        /// <param name="file">Name of the file with the filename extension. Example: "Abstract5567.jpg"</param>
        /// <param name="content">A generic view of a sequence of bytes. (Stream)</param>
        /// <returns>On success returns shared link of the file, otherwise null.</returns>
        public static async Task<string> Upload(string folder, string file, Stream content)
        {
            string sharedLink = null;

            using (var dbx = new DropboxClient(DropboxAppAccessToken))
            {
                using (var mem = new MemoryStream())
                {
                    content.Position = 0;
                    content.CopyTo(mem);

                    mem.Position = 0;

                    try
                    {
                        var uploaded = await dbx.Files.UploadAsync(
                        folder + "/" + file,
                        WriteMode.Overwrite.Instance,
                        body: mem);

                        var sharedLinkArg = new Dropbox.Api.Sharing.CreateSharedLinkArg(folder + "/" + file);
                        var link = await dbx.Sharing.CreateSharedLinkAsync(sharedLinkArg);

                        sharedLink = link.Url;
                    }
                    catch (Exception)
                    { }
                }
            }

            return sharedLink;
        }
 public async Task<DocumentMetadata> Upload(string folder, string file, Stream content)
 {
     using (DropboxClient dropboxClient = new DropboxClient(this.accessToken))
     {
         try
         {
             folder = folder.TrimEnd('/', '\\').Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
             file = file.TrimStart('/', '\\');
             
             var updated =
                 await
                 dropboxClient.Files.UploadAsync(
                     folder + "/" + file,
                     WriteMode.Overwrite.Instance,
                     false,
                     null,
                     false,
                     content);
             return new DocumentMetadata
                        {
                            Id = updated.Id,
                            RevisionId = updated.Rev,
                            ServerModified = updated.ServerModified,
                            Size = updated.Size
                        };
         }
         catch (ApiException<UploadError> ex)
         {
             throw new UploadFailedException(
                 string.Format("Upload failed for the next file: {0}", Path.Combine(folder, file)),
                 ex);
         }
         
     }
 }
Пример #3
0
        public DropboxClientWrapper()
        {
            dropboxClient = new DropboxClient(Config.DropBoxAuthKey);

            dropboxHttpClient = new HttpClient();
            dropboxHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Config.DropBoxAuthKey);
        }
 public async Task GetAccount()
 {
     using (var client = new DropboxClient(AccessToken))
     {
         Account = await client.Users.GetCurrentAccountAsync();
     }
 }
 public async Task Connetti(string token)
 {
     Connection = new DropboxClient(token);
     await Credenziali();
     await RefreshFolderList();
     await RefreshFileList();
 }
Пример #6
0
 public async Task<byte[]> DownloadContentAsByteArray(DropboxClient client, DownloadArg arg)
 {
     using (var response = await client.Files.DownloadAsync(arg))
     {
         return await response.GetContentAsByteArrayAsync();
     }
 }
Пример #7
0
        public DropBox(string loginAccessToken)
        {
            DropboxClientConfig config;
            HttpClient          httpClient;

            Dropbox.Api.Users.FullAccount userDropoBox;

            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)
            };


            config = new DropboxClientConfig()
            {
                HttpClient = httpClient
            };
            AccessToken  = loginAccessToken;
            client       = new Dropbox.Api.DropboxClient(AccessToken, config);
            userDropoBox = client.Users.GetCurrentAccountAsync().Result;


            User = new User(userDropoBox.Name.DisplayName, userDropoBox.Locale, userDropoBox.Email, userDropoBox.ProfilePhotoUrl, userDropoBox.EmailVerified);
        }
Пример #8
0
        public static async Task<Dictionary<string, List<Tuple<string, string>>>> GetAllSharedLinks()
        {
            var linkList = new Dictionary<string, List<Tuple<string, string>>>();

            using (var dbx = new DropboxClient(DropboxAppAccessToken))
            {
                //var arg = new Dropbox.Api.Sharing.GetSharedLinksArg("folder");
                var list = await dbx.Sharing.GetSharedLinksAsync();

                foreach(var link in list.Links)
                {
                    var imgName = link.AsPath.Path.Substring(link.AsPath.Path.LastIndexOf('/') + 1);
                    string path = link.AsPath.Path.Replace("/" + imgName, "");

                    string rawUrl = link.Url.Substring(0, link.Url.Length - DropboxURLSuffix.Length) + RawURLSuffix;

                    if (path != string.Empty && imgName != "www.dropbox.com.url")
                    {
                        if (!linkList.ContainsKey(path))
                        {
                            linkList.Add(path, new List<Tuple<string, string>>());
                        }

                        linkList[path].Add(new Tuple<string, string>(rawUrl, imgName));
                    }
                }
            }

            return linkList;
        }
 public async Task<ActionResult> GetFiles(string folder)
 {
     using (var dropboxClient = new DropboxClient(Common.Constants.ServerConstants.DropboxClient))
     {
         var files = await ListUserFiles(dropboxClient, folder);
         return Json(files, JsonRequestBehavior.AllowGet);
     }
 }
Пример #10
0
 public async Task LoadFileList()
 {
     using (var client = new DropboxClient(AccessToken))
     {
         ListFolderResult list = await client.Files.ListFolderAsync(string.Empty);
         Files = list.Entries;
     }
 }
Пример #11
0
 public async Task Download(string folder, string file)
 {
     using (var client = new DropboxClient(AccessToken))
     {
         using (IDownloadResponse<FileMetadata> response = await client.Files.DownloadAsync(folder + "/" + file))
         {
             LastDownloadedFile = await response.GetContentAsByteArrayAsync();
         }
     }
 }
Пример #12
0
 private static async Task Upload(DropboxClient dbx, string folder, string file, byte[] content)
 {
     using (var mem = new MemoryStream(content)) 
     {
         FileMetadata updated = await dbx.Files.UploadAsync(
             folder + "/" + file,
             WriteMode.Overwrite.Instance,
             body: mem);
         Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev);
     }
 }
Пример #13
0
        public static DropboxClient GetApi(string accessToken)
        {
            var config = new DropboxClientConfig
            {
                HttpClient = ProxyTools.CreateHttpClient()
            };

            var api = new DropboxClient(accessToken, config);

            return api;
        }
Пример #14
0
 public async Task Upload(DropboxClient dbx, string folder, string file, string content)
 {
     using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(content)))
     {
         var updated = await dbx.Files.UploadAsync(
             folder + "/" + file,
             Dropbox.Api.Files.WriteMode.Overwrite.Instance,
             body: mem);
         Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev);
     }
 }
Пример #15
0
 public async Task<UserInfo> GetUserInfoAsync()
 {
     UserInfo user = new UserInfo();
     var config = new DropboxClientConfig() { HttpClient = client };
     using (var dbx = new DropboxClient(AccessToken, config))
     {
         var full = await dbx.Users.GetCurrentAccountAsync();
         user.Email = full.Email;
         user.Name = full.Name.DisplayName;
     }
     return user;
 }
Пример #16
0
        /*
         * ============================================
         * Public
         * ============================================
         */

        /// <summary>
        /// Initialize the DropboxClient by login using an access token.
        /// </summary>
        public bool Login()
        {
            // No access token, we need a new one
            if (!this.HasAccessToken && !this.OAuth())
            {
                return(false);
            }

            this.dbx = new DropboxApi.DropboxClient(Properties.Settings.Default.DropboxAccessToken);

            return(true);
        }
Пример #17
0
        private async Task<int> Run()
        {
            InitializeCertPinning();

            var accessToken = await this.GetAccessToken();
            if (string.IsNullOrEmpty(accessToken))
            {
                return 1;
            }

            // Specify socket level timeout which decides maximum waiting time when on bytes are
            // received by the socket.
            var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 })
            {
                // Specify request level timeout which decides maximum time taht can be spent on
                // download/upload files.
                Timeout = TimeSpan.FromMinutes(20)
            };

            this.client = new DropboxClient(accessToken, userAgent: "SimpleTestApp", httpClient: httpClient);

            try
            {
                await GetCurrentAccount();

                var path = "/DotNetApi/Help";
                var list = await ListFolder(path);

                var firstFile = list.Entries.FirstOrDefault(i => i.IsFile);
                if (firstFile != null)
                {
                    await Download(path, firstFile.AsFile);
                }

                await Upload(path, "Test.txt", "This is a text file");

                await ChunkUpload(path, "Binary");
            }
            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;
        }
Пример #18
0
        public static async Task<int> UploadFile(string token, byte[] contentFile, IFileProvider fileProvider,
            string filename, int moduleId = -1, int hwId = -1)
        {

            string username = TokenHelper.GetFromToken(token, "username");
            string role = TokenHelper.GetFromToken(token, "role");

            string path = "/" + role + "/" + username + "/" + filename;

            var key = WebConfigurationManager.AppSettings["DropboxToken"];
            var dbx = new DropboxClient(key);

            FileType fileType;
            var lastOrDefault = filename.Split('.').LastOrDefault();
            if (lastOrDefault != null)
                if (Enum.TryParse(lastOrDefault, out fileType))
                {
                    using (var memoryStream = new MemoryStream(contentFile))
                    {
                        try
                        {
                            await dbx.Files.UploadAsync(
                                path,
                                WriteMode.Add.Instance.AsAdd,
                                body: memoryStream);
                            Logger.Logger.Instance.LogAction(LoggerHelper.GetActionString(username, "Upload File"));
                        }
                        catch (Exception ex)
                        {
                            Logger.Logger.Instance.LogError(ex);
                            throw;
                        }
                        var input = new FileDTO
                        {
                            Path = path,
                            FileType = fileType,
                            FileName = filename
                        };
                        var fileId = fileProvider.SaveUploadedFilePath(input, moduleId, hwId);
                        if (fileId < 0)
                            throw new Exception("Cannot save file path");
                        else
                            return fileId;
                    }
                }
                else
                    throw new Exception("File tye not supported");
            else
                throw new Exception("Not a file type");
        }
Пример #19
0
        public async Task ListRootFolder(DropboxClient dbx)
        {
            var list = await dbx.Files.ListFolderAsync(string.Empty);

            // show folders, then files
            foreach (var item in list.Entries.Where(i => i.IsFolder))
            {
                Console.WriteLine("D  {0}/", item.Name);
            }

            foreach (var item in list.Entries.Where(i => i.IsFile))
            {
                Console.WriteLine("F{0,8} {1}", item.AsFile.Size, item.Name);
            }
        }
Пример #20
0
        public async Task Upload(string folder, string file, byte[] content, Action onSuccess)
        {
            using (var client = new DropboxClient(AccessToken))
            {
                using (var mem = new MemoryStream(content))
                {
                    await client.Files.UploadAsync(
                        folder + "/" + file,
                        WriteMode.Overwrite.Instance,
                        body: mem);

                    onSuccess();
                }
            }
        }
Пример #21
0
        public async Task<FileMetadata> Upload(string file, string content)
        {
            using (var dbx = new DropboxClient(_accessToken))
            {
                using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(content)))
                {
                    var updated = await dbx.Files.UploadAsync(
                        "/" + file,
                       WriteMode.Overwrite.Instance,
                       body: mem);

                    return updated;
                }
            }
        }
Пример #22
0
		public async Task<bool> SendAsync (string csv, string participantId)
		{
			var fileName = string.Format (Resources.Export.FileNameFormat, participantId, DateTime.Now);
			var filePath = string.Format ("/{0}", fileName);
			try {
				using (var dbx = new DropboxClient (Resources.Export.Dropbox.AccessToken)) {
					using (var mem = new MemoryStream (Encoding.UTF8.GetBytes (csv))) {
						await dbx.Files.UploadAsync (filePath, WriteMode.Overwrite.Instance, body: mem);
					}
					return true;
				}
			} catch {
				return false;
			}
		}
Пример #23
0
        public async Task<string> UploadAsync(byte[] content, string extension)
        {
            string guid = Guid.NewGuid().ToString();
            string imageUrl = string.Format("/{0}.{1}", guid, extension);
            
            using (var mem = new MemoryStream(content))
            using (var dbx = new DropboxClient(Token))
            {
                var image = await dbx.Files.UploadAsync(new CommitInfo(imageUrl), body: mem);
                var shareLink = await dbx.Sharing.CreateSharedLinkAsync(image.PathLower);
                var rawLink = ProcessImageLink(shareLink.Url);

                return rawLink;
            }
        }
Пример #24
0
        private static async Task Run()
        {
            using (var dropboxAccount = new DropboxClient(GlobalConstatns.AccessTokenDropBox))
            {
                FullAccount full = await dropboxAccount.Users.GetCurrentAccountAsync();
                Console.WriteLine("Hello {0} !", full.Name.DisplayName);

                string[] catPictures = Directory.GetFiles(Directory.GetCurrentDirectory() + "..\\..\\..\\Album");
                foreach (var cat in catPictures)
                {
                    byte[] bytes = ReadBinaryFile(cat);
                    
                    await Upload(dropboxAccount, "/Cats", cat.Substring(cat.LastIndexOf("\\") + 1), bytes);
                }
            }
        }
        private async Task<UserFilesViewModel> ListUserFiles(DropboxClient dropboxClient, string folder)
        {
            if (string.IsNullOrEmpty(folder))
            {
                folder = this.User.Identity.Name;
            }
            var list = await dropboxClient.Files.ListFolderAsync("/" + folder);
            
            var userFiles = new UserFilesViewModel();

            userFiles.Folders = list.Entries.Where(i => i.IsFolder).Select(i => i.Name).ToList();

            userFiles.Files = list.Entries.Where(i => i.IsFile).Select(i => i.Name).ToList();

            return userFiles;
        }
Пример #26
0
        /// <summary>
        /// Run tests for user-level operations.
        /// </summary>
        /// <param name="client">The Dropbox client.</param>
        /// <returns>An asynchronous task.</returns>
        private async Task RunUserTests(DropboxClient client)
        {
            await GetCurrentAccount(client);

            var path = "/DotNetApi/Help";
            var list = await ListFolder(client, path);

            var firstFile = list.Entries.FirstOrDefault(i => i.IsFile);
            if (firstFile != null)
            {
                await Download(client, path, firstFile.AsFile);
            }

            await Upload(client, path, "Test.txt", "This is a text file");

            await ChunkUpload(client, path, "Binary");
        }
Пример #27
0
        private async Task<int> Run()
        {
            InitializeCertPinning();

            var accessToken = await this.GetAccessToken();
            if (string.IsNullOrEmpty(accessToken))
            {
                return 1;
            }

            // Specify socket level timeout which decides maximum waiting time when on bytes are
            // received by the socket.
            var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 })
            {
                // Specify request level timeout which decides maximum time taht can be spent on
                // download/upload files.
                Timeout = TimeSpan.FromMinutes(20)
            };

            try
            {
                var client = new DropboxClient(accessToken, userAgent: "SimpleTestApp", httpClient: httpClient);
                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;
        }
Пример #28
0
        /// <summary>
        /// Deletes file or entire folder(with or without content). 
        /// </summary>
        /// <param name="path">If the target is a folder - path to the folder. Example: "/Contests/Active".
        /// If the target is file - the path includes the filename and extension. Example: "/Contests/Active/Abstract5567.jpg"
        /// The path is relevant to the root Dropbox folder - i.e. the path always starts with "/" 
        /// </param>
        /// <returns>On success returns true, otherwise false.</returns>
        public static async Task<bool> Delete(string path)
        {
            using (var dbx = new DropboxClient(DropboxAppAccessToken))
            {
                var folderArg = new Dropbox.Api.Files.DeleteArg(path);
                bool success = true;
                try
                {
                    var folder = await dbx.Files.DeleteAsync(folderArg);
                }
                catch (Exception)
                {
                    success = false;
                }

                return success;
            }
        }
        public async Task<AccountConfiguration> CreateAccount()
        {
            var isOk = OAuth2Flow.TryAuthenticate(this);

            if (!isOk) return null;

            var api = new DropboxClient(_oauthResponse.AccessToken);

            var owner = await api.Users.GetCurrentAccountAsync();

            var account = new AccountConfiguration()
            {
                Id = owner.AccountId,
                Name = owner.Name.DisplayName,
                Type = StorageType.Dropbox,
                Secret = _oauthResponse.AccessToken,
            };

            return account;
        }
Пример #30
0
 public DropboxFolder(string authorisationCode)
 {
     base.AuthorisationCode = authorisationCode;
     dropboxClient          = DropboxClientAccess();
 }
Пример #31
0
        public static async Task<Blog> FromUserAsync(UserProfile user)
        {
            if (string.IsNullOrWhiteSpace(user.BlogName) ||
                string.IsNullOrWhiteSpace(user.DropboxAccessToken))
            {
                return null;
            }

            using (var client = new DropboxClient(user.DropboxAccessToken, userAgent: "SimpleBlogDemo"))
            {
                return new Blog
                {
                    BlogName = user.BlogName,
                    BlogArticles = new List<ArticleMetadata>(await client.GetArticleList()).AsReadOnly()
                };
            }
        }
        public async Task<ActionResult> CreateFile()
        {
            if (Request.Files.Count == 0)
            {
                return this.RedirectToAction("Index", "MyFiles");
            }
            using (var dropboxClient = new DropboxClient(Common.Constants.ServerConstants.DropboxClient))
            {
                string path = "/" + User.Identity.Name;
                string filename = Path.GetFileName(Request.Files[0].FileName);

                int contentLength = Request.Files[0].ContentLength;
                byte[] contentBuffer = new byte[contentLength];

                Request.Files[0].InputStream.Read(contentBuffer, 0, contentLength);

                BinaryReader contentBinaryReader = new BinaryReader(Request.Files[0].InputStream);
                byte[] binaryData = contentBinaryReader.ReadBytes(contentLength);

                string result = System.Text.Encoding.UTF8.GetString(binaryData);


                using (var fileContentReader = new MemoryStream(Encoding.UTF8.GetBytes(result)))
                {
                    var updated = await dropboxClient.Files.UploadAsync(
                        "/" + User.Identity.Name + "/" + Request.Files[0].FileName,
                        WriteMode.Overwrite.Instance,
                        body: fileContentReader);

                    return this.RedirectToAction("Index", "MyFiles");
                }
            }
        }
Пример #33
-9
        public async Task<IHttpActionResult> DownloadLink(int moduleId)
        {
            var key = WebConfigurationManager.AppSettings["DropboxToken"];
            var dbx = new DropboxClient(key);

            var files = _fileProvider.GetByModule(moduleId);

            var model = new List<FileViewModel>();

            foreach (var file in files)
            {
                try
                {
                    var downloadLink = await dbx.Sharing.CreateSharedLinkAsync(file.Path, false);

                    var viewModel = new FileViewModel
                    {
                        Filename = file.FileName,
                        Path = downloadLink.Url.Remove(downloadLink.Url.Length - 1) + "1"
                    };
                    model.Add(viewModel);
                }
                catch (Exception ex)
                {
                    Logger.Logger.Instance.LogError(ex);
                    return InternalServerError(ex);
                }
            }
            return Ok(model);
        }