Exemplo n.º 1
0
        private async Task ExecuteMainAsync()
        {
            Console.WriteLine("Access token: ");
            var accessToken = Console.ReadLine();

            Console.WriteLine("Remote file name: ");
            var fileName = Console.ReadLine();

            Console.WriteLine("Local file path: ");
            var localFilePath = Console.ReadLine();

            Console.WriteLine("Parent folder Id: ");
            var parentFolderId = Console.ReadLine();

            var timer = Stopwatch.StartNew();

            var auth = new OAuthSession(accessToken, "YOUR_REFRESH_TOKEN", 3600, "bearer");

            var config = new BoxConfig("YOUR_CLIENT_ID", "YOUR_CLIENT_ID", new Uri("http://boxsdk"));
            var client = new BoxClient(config, auth);

            var file = File.OpenRead(localFilePath);
            var fileRequest = new BoxFileRequest
            {
                Name = fileName,
                Parent = new BoxFolderRequest { Id = parentFolderId }
            };

            var bFile = await client.FilesManager.UploadAsync(fileRequest, file);

            Console.WriteLine("{0} uploaded to folder: {1} as file: {2}",localFilePath, parentFolderId, bFile.Id);
            Console.WriteLine("Time spend : {0} ms", timer.ElapsedMilliseconds);
        }
        /// <summary>
        /// Uploads a provided file to the target parent folder
        /// If the file already exists, an error will be thrown
        /// </summary>
        /// <param name="fileRequest"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public async Task<BoxFile> UploadAsync(BoxFileRequest fileRequest, Stream stream, List<string> fields = null)
        {
            stream.ThrowIfNull("stream");
            fileRequest.ThrowIfNull("fileRequest")
                .Name.ThrowIfNullOrWhiteSpace("filedRequest.Name");
            fileRequest.Parent.ThrowIfNull("fileRequest.Parent")
                .Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id");

            BoxMultiPartRequest request = new BoxMultiPartRequest(_config.FilesUploadEndpointUri)
                .Param(ParamFields, fields)
                .FormPart(new BoxStringFormPart()
                {
                    Name = "metadata",
                    Value = _converter.Serialize(fileRequest)
                })
                .FormPart(new BoxFileFormPart()
                {
                    Name = "file",
                    Value = stream,
                    FileName = fileRequest.Name
                });

            IBoxResponse<BoxCollection<BoxFile>> response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false);

            // We can only upload one file at a time, so return the first entry
            return response.ResponseObject.Entries.FirstOrDefault();
        }
        public async Task UploadFile_ValidResponse_ValidFile()
        {
            /*** Arrange ***/
            string responseString = "{ \"total_count\": 1, \"entries\": [ { \"type\": \"file\", \"id\": \"5000948880\", \"sequence_id\": \"3\", \"etag\": \"3\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\", \"name\": \"tigers.jpeg\", \"description\": \"a picture of tigers\", \"size\": 629644, \"path_collection\": { \"total_count\": 2, \"entries\": [ { \"type\": \"folder\", \"id\": \"0\", \"sequence_id\": null, \"etag\": null, \"name\": \"All Files\" }, { \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\" } ] }, \"created_at\": \"2012-12-12T10:55:30-08:00\", \"modified_at\": \"2012-12-12T11:04:26-08:00\", \"trashed_at\": null, \"purged_at\": null, \"content_created_at\": \"2013-02-04T16:57:52-08:00\", \"content_modified_at\": \"2013-02-04T16:57:52-08:00\", \"created_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"modified_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"owned_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"shared_link\": null, \"parent\": { \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\" }, \"item_status\": \"active\" } ] }";
            _handler.Setup(h => h.ExecuteAsync<BoxCollection<BoxFile>>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxCollection<BoxFile>>>(new BoxResponse<BoxCollection<BoxFile>>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }));

            var fakeFileRequest = new BoxFileRequest()
            {
                Name = "test.txt",
                Parent = new BoxRequestEntity() { Id = "0" }
            };

            var fakeStream = new Mock<System.IO.Stream>();

            /*** Act ***/
            BoxFile f = await _filesManager.UploadAsync(fakeFileRequest, fakeStream.Object);

            /*** Assert ***/
            Assert.AreEqual("5000948880", f.Id);
            Assert.AreEqual("3", f.SequenceId);
            Assert.AreEqual("tigers.jpeg", f.Name);
            Assert.AreEqual("134b65991ed521fcfe4724b7d814ab8ded5185dc", f.Sha1);
            Assert.AreEqual(629644, f.Size);
        }
Exemplo n.º 4
0
        public async Task<bool> Save(Stream stream, string path)
        {
            var api = await GetApi();
            BoxFile item;

            var file = await api.GetFileByPath(path);
            if (file != null)
            {
                item = await api.FilesManager.UploadNewVersionAsync(file.Name, file.Id, stream, file.ETag);
            }
            else // not found: creating new
            {

                var folderName = CloudPath.GetDirectoryName(path);
                var fileName = CloudPath.GetFileName(path);

                var folder = await api.GetFileByPath(folderName);
                if (folder == null)
                    throw new InvalidOperationException(string.Format("Folder does not exist: {0}", folderName));

                var request = new BoxFileRequest()
                {
                    Name = fileName,
                    Parent = new BoxRequestEntity { Id = folder.Id },
                };

                item = await api.FilesManager.UploadAsync(request, stream);

            }

            return item != null;
        }
 public static async Task SetFileDescription(UserTokenHandler tokenHandler, string fileID, string description)
 {
     var client      = GetNewBoxClient(tokenHandler);
     var fileRequest = new Box.V2.Models.BoxFileRequest {
         Id = fileID, Description = description
     };
     await client.FilesManager.UpdateInformationAsync(fileRequest).ConfigureAwait(false);
 }
Exemplo n.º 6
0
        public async Task UploadFile_ValidResponse_ValidFile()
        {
            /*** Arrange ***/
            string responseString = "{ \"total_count\": 1, \"entries\": [ { \"type\": \"file\", \"id\": \"5000948880\", \"sequence_id\": \"3\", \"etag\": \"3\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\", \"name\": \"tigers.jpeg\", \"description\": \"a picture of tigers\", \"size\": 629644, \"path_collection\": { \"total_count\": 2, \"entries\": [ { \"type\": \"folder\", \"id\": \"0\", \"sequence_id\": null, \"etag\": null, \"name\": \"All Files\" }, { \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\" } ] }, \"created_at\": \"2012-12-12T10:55:30-08:00\", \"modified_at\": \"2012-12-12T11:04:26-08:00\", \"trashed_at\": null, \"purged_at\": null, \"content_created_at\": \"2013-02-04T16:57:52-08:00\", \"content_modified_at\": \"2013-02-04T16:57:52-08:00\", \"created_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"modified_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"owned_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"shared_link\": null, \"parent\": { \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\" }, \"item_status\": \"active\", \"tags\": [ \"important\", \"needs review\" ] } ] }";
            BoxMultiPartRequest boxRequest = null;
            _handler.Setup(h => h.ExecuteAsync<BoxCollection<BoxFile>>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxCollection<BoxFile>>>(new BoxResponse<BoxCollection<BoxFile>>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }))
                .Callback<IBoxRequest>(r => boxRequest = r as BoxMultiPartRequest);

            var createdAt = new DateTime(2016, 8, 27);
            var modifiedAt = new DateTime(2016, 8, 28);

            var fakeFileRequest = new BoxFileRequest()
            {
                Name = "test.txt",
                ContentCreatedAt = createdAt,
                ContentModifiedAt = modifiedAt,
                Parent = new BoxRequestEntity() { Id = "0" }
            };

            var createdAtString = createdAt.ToString("yyyy-MM-ddTHH:mm:sszzz");
            var modifiedAtString = modifiedAt.ToString("yyyy-MM-ddTHH:mm:sszzz");

            var fakeStream = new Mock<System.IO.Stream>();

            /*** Act ***/
            BoxFile f = await _filesManager.UploadAsync(fakeFileRequest, fakeStream.Object, null, null, new byte[] { 0, 1, 2, 3, 4 });

            /*** Assert ***/
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(_FilesUploadUri, boxRequest.AbsoluteUri.AbsoluteUri);
            Assert.AreEqual(2, boxRequest.Parts.Count);
            Assert.AreEqual("attributes", boxRequest.Parts[0].Name);
            Assert.IsNotNull(boxRequest.Parts[0] as BoxStringFormPart);
            Assert.IsTrue(AreJsonStringsEqual(
                "{\"content_created_at\":\"" + createdAtString + "\",\"content_modified_at\":\"" + modifiedAtString + "\",\"parent\":{\"id\":\"0\"},\"name\":\"test.txt\"}",
                (boxRequest.Parts[0] as BoxStringFormPart).Value));
            Assert.AreEqual("file", boxRequest.Parts[1].Name);
            Assert.IsNotNull(boxRequest.Parts[1] as BoxFileFormPart);
            Assert.AreEqual("test.txt", (boxRequest.Parts[1] as BoxFileFormPart).FileName);
            Assert.IsTrue(object.ReferenceEquals(fakeStream.Object, (boxRequest.Parts[1] as BoxFileFormPart).Value));
            Assert.IsTrue(boxRequest.HttpHeaders.ContainsKey("Content-MD5"));
            Assert.AreEqual(HexStringFromBytes(new byte[] { 0, 1, 2, 3, 4 }), boxRequest.HttpHeaders["Content-MD5"]);

            Assert.AreEqual("5000948880", f.Id);
            Assert.AreEqual("3", f.SequenceId);
            Assert.AreEqual("tigers.jpeg", f.Name);
            Assert.AreEqual("134b65991ed521fcfe4724b7d814ab8ded5185dc", f.Sha1);
            Assert.AreEqual(629644, f.Size);
            Assert.AreEqual("important", f.Tags[0]);
            Assert.AreEqual("needs review", f.Tags[1]);
        }
Exemplo n.º 7
0
 private static Task<BoxFile> UploadFile(BoxFolder newFolder, BoxClient userClient, Stream file)
 {
     var fileRequest = new BoxFileRequest
     {
         Name = "logo.png",
         Parent = new BoxFolderRequest { Id = newFolder.Id }
     };
     return userClient.FilesManager.UploadAsync(fileRequest, file);
 }
        public static async Task <FileFolderInfo> UploadFile(UserTokenHandler tokenHandler, string parentFolderID, string fileName, byte[] data)
        {
            var client      = GetNewBoxClient(tokenHandler);
            var fileRequest = new Box.V2.Models.BoxFileRequest {
                Name = fileName, Parent = new BoxRequestEntity {
                    Id = parentFolderID
                }
            };

            Box.V2.Models.BoxFile file = await client.FilesManager.UploadAsync(fileRequest, new MemoryStream(data)).ConfigureAwait(false);

            return(new FileFolderInfo
            {
                ID = file.Id,
                Name = file.Name,
                ParentFolderID = parentFolderID
            });
        }
        public async Task FileWorkflow_ValidRequest_ValidResponse()
        {
            //file Ids of the two files to download
            string imageFileId1 = "16894947279";
            string imageFileId2 = "16894946307";
            
            // paths to store the two downloaded files
            var dlPath1 = string.Format(GetSaveFolderPath(), "thumbnail1.png");
            var dlPath2 = string.Format(GetSaveFolderPath(), "thumbnail2.png");

            //download 2 files
            using (FileStream fs = new FileStream(dlPath1, FileMode.OpenOrCreate))
            {
                Stream stream = await _client.FilesManager.DownloadStreamAsync(imageFileId1);
                await stream.CopyToAsync(fs);
            }

            using (FileStream fs = new FileStream(dlPath2, FileMode.OpenOrCreate))
            {
                Stream stream = await _client.FilesManager.DownloadStreamAsync(imageFileId2);
                await stream.CopyToAsync(fs);
            }

            // File name to use to upload files
            string uploadFileName = "testUpload.png";

            // Upload file at dlPath1
            BoxFile file;
            using (FileStream fs = new FileStream(dlPath1, FileMode.Open))
            {
                BoxFileRequest req = new BoxFileRequest()
                {
                    Name = uploadFileName,
                    Parent = new BoxRequestEntity() { Id = "0" }
                };

                file = await _client.FilesManager.UploadAsync(req, fs);
            }

            Assert.AreEqual(uploadFileName, file.Name, "Incorrect file name");
            Assert.AreEqual("0", file.Parent.Id, "Incorrect destination folder");

            // Upload file at dlPath2 as new version of 'file'
            BoxFile newFileVersion;
            using (FileStream fs = new FileStream(dlPath2, FileMode.Open))
            {
                newFileVersion = await _client.FilesManager.UploadNewVersionAsync(uploadFileName, file.Id, fs, file.ETag);
            }

            Assert.AreEqual(newFileVersion.Name, uploadFileName);
            Assert.AreEqual(newFileVersion.Parent.Id, "0");

            //View file versions (Requires upgraded acct)
            BoxCollection<BoxFileVersion> fileVersions = await _client.FilesManager.ViewVersionsAsync(newFileVersion.Id);

            Assert.AreEqual(fileVersions.TotalCount, 1, "Incorrect number of versions");

            foreach (var f in fileVersions.Entries)
            {
                Assert.AreEqual(uploadFileName, f.Name);
            }

            // Update the file name of a file
            string updateName = GetUniqueName();

            BoxFileRequest updateReq = new BoxFileRequest()
            {
                Id = file.Id,
                Name = updateName
            };
            BoxFile fileUpdate = await _client.FilesManager.UpdateInformationAsync(updateReq);

            Assert.AreEqual(file.Id, fileUpdate.Id, "File Ids are not the same");
            Assert.AreEqual(updateName, fileUpdate.Name, "File Names are not the same");

            // Test create shared link
            BoxSharedLinkRequest linkReq = new BoxSharedLinkRequest()
            {
                Access = BoxSharedLinkAccessType.open
            };
            BoxFile fileWithLink = await _client.FilesManager.CreateSharedLinkAsync(newFileVersion.Id, linkReq);

            Assert.AreEqual(BoxSharedLinkAccessType.open, fileWithLink.SharedLink.Access, "Incorrect access for shared link");

            // Copy file in same folder
            string copyName = GetUniqueName();
            BoxFileRequest copyReq = new BoxFileRequest()
            {
                Id = fileWithLink.Id,
                Name = copyName,
                Parent = new BoxRequestEntity() { Id = "0" }
            };
            BoxFile fileCopy = await _client.FilesManager.CopyAsync(copyReq);

            Assert.AreEqual(fileCopy.Name, copyName, "Incorrect Name for copied file");
            Assert.AreEqual(fileCopy.Parent.Id, "0", "Incorrect parent folder for copied file");

            // Test get file information
            BoxFile fileInfo = await _client.FilesManager.GetInformationAsync(fileWithLink.Id);

            Assert.AreEqual(updateName, fileWithLink.Name, "File name is incorrect");
            Assert.AreEqual("0", fileWithLink.Parent.Id, "Parent folder is incorrect");

            // Delete both files
            await _client.FilesManager.DeleteAsync(fileCopy.Id, fileCopy.ETag);
            await _client.FilesManager.DeleteAsync(fileWithLink.Id, fileWithLink.ETag);
        }
        public async Task FileWorkflow_ValidRequest_ValidResponse()
        {
            string fileName = "reimages.zip";
            string saveName = "reimages2.zip";


            string filePath = string.Format(savePath, fileName);
            string dlPath = string.Format(savePath, saveName);

            // Test upload a file
            BoxFile file;
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                BoxFileRequest req = new BoxFileRequest(){
                    Name = "reimages.zip",
                    Parent = new BoxRequestEntity() { Id = "0" }
                };

                file = await _client.FilesManager.UploadAsync(req, fs);
            }

            Assert.AreEqual(fileName, file.Name);
            Assert.AreEqual("0", file.Parent.Id);

            // Test upload a new version
            BoxFile newFile;
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                newFile = await _client.FilesManager.UploadNewVersionAsync(fileName, file.Id, fs, file.ETag);
            }

            Assert.AreEqual(newFile.Name, fileName);
            Assert.AreEqual(newFile.Parent.Id, "0");

            // Test view file versions (Requires upgraded acct)
            //BoxCollection<BoxFile> versions = await _client.FilesManager.ViewVersionsAsync(newFile.Id);

            //Assert.AreEqual(versions.TotalCount, 2);
            //foreach (var f in versions.Entries)
            //{
            //    Assert.AreEqual(fileName, f.Name);
            //    Assert.AreEqual("0", f.Parent.Id);
            //}

            // Test update a file
            string updateName = GetUniqueName();
            BoxFileRequest updateReq = new BoxFileRequest()
            {
                Id = file.Id,
                Name = updateName,
                Description = updateName
            };
            BoxFile fileUpdate = await _client.FilesManager.UpdateInformationAsync(updateReq);

            Assert.AreEqual(file.Id, fileUpdate.Id);
            Assert.AreEqual(updateName, fileUpdate.Name );
            Assert.AreEqual(updateName, fileUpdate.Description);

            // Test create shared link
            //BoxSharedLinkRequest linkReq = new BoxSharedLinkRequest()
            //{
            //    Access = BoxSharedLinkAccessType.open
            //};
            //BoxFile fileLink = await _client.FilesManager.CreateSharedLinkAsync(newFile.Id, linkReq);

            //Assert.AreEqual(BoxSharedLinkAccessType.open, fileLink.SharedLink.Access);

            // Test copy a file
            string copyName = GetUniqueName();
            BoxFileRequest copyReq = new BoxFileRequest()
            {
                Id = newFile.Id,
                Name = copyName,
                Parent = new BoxRequestEntity() { Id = "0" }
            };
            BoxFile fileCopy = await _client.FilesManager.CopyAsync(copyReq);

            Assert.AreEqual(fileCopy.Name, copyName);
            Assert.AreEqual(fileCopy.Parent.Id, "0");

            // Test download a file
            using (FileStream fs = new FileStream(dlPath, FileMode.OpenOrCreate))
            {
                Stream stream = await _client.FilesManager.DownloadStreamAsync(file.Id);
                await stream.CopyToAsync(fs);
            }

            // Test get file information
            BoxFile fileInfo = await _client.FilesManager.GetInformationAsync(file.Id);

            Assert.AreEqual(updateName, fileInfo.Name);
            Assert.AreEqual("0", file.Parent.Id);

            BoxFile newFileInfo = await _client.FilesManager.GetInformationAsync(newFile.Id);

            Assert.AreEqual(updateName, newFileInfo.Name);
            Assert.AreEqual("0", newFileInfo.Parent.Id);

            // Test delete a file
            await _client.FilesManager.DeleteAsync(fileCopy.Id, fileCopy.ETag);
            await _client.FilesManager.DeleteAsync(newFile.Id, newFileInfo.ETag);


        }
        public async Task RestoreTrashedFile_ValidResponse_ValidFile()
        {
            /*** Arrange ***/
            string responseString = "{ \"type\": \"file\", \"id\": \"5859258256\", \"sequence_id\": \"3\", \"etag\": \"3\", \"sha1\": \"4bd9e98652799fc57cf9423e13629c151152ce6c\", \"name\": \"Screenshot_1_30_13_6_37_PM.png\", \"description\": \"\", \"size\": 163265, \"path_collection\": { \"total_count\": 1, \"entries\": [ { \"type\": \"folder\", \"id\": \"0\", \"sequence_id\": null, \"etag\": null, \"name\": \"All Files\" } ] }, \"created_at\": \"2013-01-30T18:43:56-08:00\", \"modified_at\": \"2013-02-07T10:56:58-08:00\", \"trashed_at\": null, \"purged_at\": null, \"content_created_at\": \"2013-01-30T18:43:56-08:00\", \"content_modified_at\": \"2013-02-07T10:56:58-08:00\", \"created_by\": { \"type\": \"user\", \"id\": \"181757341\", \"name\": \"sean test\", \"login\": \"[email protected]\" }, \"modified_by\": { \"type\": \"user\", \"id\": \"181757341\", \"name\": \"sean test\", \"login\": \"[email protected]\" }, \"owned_by\": { \"type\": \"user\", \"id\": \"181757341\", \"name\": \"sean test\", \"login\": \"[email protected]\" }, \"shared_link\": { \"url\": \"https://seanrose.box.com/s/ebgti08mtmhbpb4vlp55\", \"download_url\": \"https://seanrose.box.com/shared/static/ebgti08mtmhbpb4vlp55.png\", \"vanity_url\": null, \"is_password_enabled\": false, \"unshared_at\": null, \"download_count\": 0, \"preview_count\": 4, \"access\": \"open\", \"permissions\": { \"can_download\": true, \"can_preview\": true } }, \"parent\": { \"type\": \"folder\", \"id\": \"0\", \"sequence_id\": null, \"etag\": null, \"name\": \"All Files\" }, \"item_status\": \"active\" }";
            _handler.Setup(h => h.ExecuteAsync<BoxFile>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxFile>>(new BoxResponse<BoxFile>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }));

            BoxFileRequest fileReq = new BoxFileRequest()
            {
                Id = "0",
                Name = "test"
            };

            /*** Act ***/
            BoxFile f = await _filesManager.RestoreTrashedAsync(fileReq);

            /*** Assert ***/
            Assert.AreEqual("5859258256", f.Id);
            Assert.AreEqual("3", f.SequenceId);
            Assert.AreEqual("3", f.ETag);
            Assert.AreEqual("4bd9e98652799fc57cf9423e13629c151152ce6c", f.Sha1);
            Assert.AreEqual("file", f.Type);


        }
        public async Task CopyFile_ValidResponse_ValidFile()
        {
            /*** Arrange ***/
            string responseString = "{ \"type\": \"file\", \"id\": \"5000948880\", \"sequence_id\": \"3\", \"etag\": \"3\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\", \"name\": \"tigers.jpeg\", \"description\": \"a picture of tigers\", \"size\": 629644, \"path_collection\": { \"total_count\": 2, \"entries\": [ { \"type\": \"folder\", \"id\": \"0\", \"sequence_id\": null, \"etag\": null, \"name\": \"All Files\" }, { \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\" } ] }, \"created_at\": \"2012-12-12T10:55:30-08:00\", \"modified_at\": \"2012-12-12T11:04:26-08:00\", \"created_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"modified_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"owned_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"shared_link\": { \"url\": \"https://www.box.com/s/rh935iit6ewrmw0unyul\", \"download_url\": \"https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg\", \"vanity_url\": null, \"is_password_enabled\": false, \"unshared_at\": null, \"download_count\": 0, \"preview_count\": 0, \"access\": \"open\", \"permissions\": { \"can_download\": true, \"can_preview\": true } }, \"parent\": { \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\" }, \"item_status\": \"active\" }";
            _handler.Setup(h => h.ExecuteAsync<BoxFile>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxFile>>(new BoxResponse<BoxFile>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }));


            BoxFileRequest request = new BoxFileRequest()
            {
                Name = "test",
                Parent = new BoxRequestEntity() { Id = "0" }
            };

            /*** Act ***/
            BoxFile f = await _filesManager.CopyAsync(request);

            /*** Assert ***/
            Assert.AreEqual("5000948880", f.Id);
            Assert.AreEqual("3", f.SequenceId);
            Assert.AreEqual("3", f.ETag);
            Assert.AreEqual("134b65991ed521fcfe4724b7d814ab8ded5185dc", f.Sha1);
            Assert.AreEqual("file", f.Type);
            Assert.AreEqual("sean rose", f.CreatedBy.Name);
            Assert.AreEqual("*****@*****.**", f.CreatedBy.Login);
            Assert.AreEqual("user", f.CreatedBy.Type);
            Assert.AreEqual("17738362", f.CreatedBy.Id);

        }
Exemplo n.º 13
0
        /// <summary>
        /// Used to create a copy of a file in another folder. The original version of the file will not be altered.
        /// </summary>
        /// <param name="fileRequest">BoxFileRequest object.</param>
        /// <param name="fields">Attribute(s) to include in the response.</param>
        /// <returns>
        /// A full file object is returned if the ID is valid and if the update is successful. 
        /// Errors can be thrown if the destination folder is invalid or if a file-name collision occurs. 
        /// </returns>
        public async Task<BoxFile> CopyAsync(BoxFileRequest fileRequest, List<string> fields = null)
        {
            fileRequest.ThrowIfNull("fileRequest");
            fileRequest.Id.ThrowIfNullOrWhiteSpace("fileRequest.Id");
            fileRequest.Parent.ThrowIfNull("fileRequest.Parent")
                .Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.CopyPathString, fileRequest.Id))
                .Method(RequestMethod.Post)
                .Param(ParamFields, fields);

            fileRequest.Id = null; //file Id was used as a query parameter in this case
            request.Payload(_converter.Serialize(fileRequest));

            IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        public async Task<FileSystemInfoContract> MoveItemAsync(RootName root, FileSystemId source, string moveName, DirectoryId destination, Func<FileSystemInfoLocator> locatorResolver)
        {
            var context = await RequireContext(root);

            if (source is DirectoryId) {
                var request = new BoxFolderRequest() { Id = source.Value, Parent = new BoxRequestEntity() { Id = destination.Value, Type = BoxType.folder }, Name = moveName };
                var item = await AsyncFunc.Retry<BoxFolder, BoxException>(async () => await context.Client.FoldersManager.UpdateInformationAsync(request, fields: boxFolderFields), RETRIES);

                return new DirectoryInfoContract(item.Id, item.Name, item.CreatedAt.Value, item.ModifiedAt.Value);
            }
            else {
                var request = new BoxFileRequest() { Id = source.Value, Parent = new BoxRequestEntity() { Id = destination.Value, Type = BoxType.file }, Name = moveName };
                var item = await AsyncFunc.Retry<BoxFile, BoxException>(async () => await context.Client.FilesManager.UpdateInformationAsync(request, fields: boxFileFields), RETRIES);

                return new FileInfoContract(item.Id, item.Name, item.CreatedAt.Value, item.ModifiedAt.Value, item.Size.Value, item.Sha1.ToLowerInvariant());
            }
        }
        /// <summary>
        /// Restores an item that has been moved to the trash. Default behavior is to restore the item to the folder it was in before 
        /// it was moved to the trash. If that parent folder no longer exists or if there is now an item with the same name in that 
        /// parent folder, the new parent folder and/or new name will need to be included in the request.
        /// </summary>
        /// <returns>The full item will be returned with a 201 Created status. By default it is restored to the parent folder it was in before it was trashed.</returns>
        public async Task<BoxFile> RestoreTrashedAsync(BoxFileRequest fileRequest, List<string> fields = null)
        {
            fileRequest.ThrowIfNull("fileRequest")
                .Id.ThrowIfNullOrWhiteSpace("fileRequest.Id");
            fileRequest.Name.ThrowIfNullOrWhiteSpace("fileRequest.Name");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, fileRequest.Id)
                .Method(RequestMethod.Post)
                .Param(ParamFields, fields)
                .Payload(_converter.Serialize(fileRequest));

            IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
Exemplo n.º 16
0
        /// <summary>
        /// Used to create a copy of a file in another folder. The original version of the file will not be altered.
        /// </summary>
        /// <param name="fileRequest"></param>
        /// <returns></returns>
        public async Task<BoxFile> CopyAsync(BoxFileRequest fileRequest, List<string> fields = null)
        {
            fileRequest.ThrowIfNull("fileRequest")
                .Name.ThrowIfNullOrWhiteSpace("fileRequest.Name");
            fileRequest.Parent.ThrowIfNull("fileRequest.Parent")
                .Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.CopyPathString, fileRequest.Id))
                .Method(RequestMethod.Post)
                .Param(ParamFields, fields)
                .Payload(_converter.Serialize(fileRequest))
                .Authorize(_auth.Session.AccessToken);

            IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request);

            return response.ResponseObject;
        }
        public async Task<FileSystemInfoContract> RenameItemAsync(RootName root, FileSystemId target, string newName, Func<FileSystemInfoLocator> locatorResolver)
        {
            var context = await RequireContext(root);

            if (target is DirectoryId) {
                var request = new BoxFolderRequest() { Id = target.Value, Name = newName };
                var item = await AsyncFunc.Retry<BoxFolder, BoxException>(async () => await context.Client.FoldersManager.UpdateInformationAsync(request, fields: boxFolderFields), RETRIES);

                return new DirectoryInfoContract(item.Id, item.Name, item.CreatedAt.Value, item.ModifiedAt.Value);
            }
            else {
                var request = new BoxFileRequest() { Id = target.Value, Name = newName };
                var item = await AsyncFunc.Retry<BoxFile, BoxException>(async () => await context.Client.FilesManager.UpdateInformationAsync(request, fields: boxFileFields), RETRIES);

                return new FileInfoContract(item.Id, item.Name, item.CreatedAt.Value, item.ModifiedAt.Value, item.Size.Value, item.Sha1.ToLowerInvariant());
            }
        }
        public async Task<FileInfoContract> NewFileItemAsync(RootName root, DirectoryId parent, string name, Stream content, IProgress<ProgressValue> progress)
        {
            var context = await RequireContext(root);

            var request = new BoxFileRequest() { Name = name, Parent = new BoxRequestEntity() { Id = parent.Value } };
            var item = await AsyncFunc.Retry<BoxFile, BoxException>(async () => await context.Client.FilesManager.UploadAsync(request, new ProgressStream(content, progress), boxFileFields), RETRIES);

            return new FileInfoContract(item.Id, item.Name, item.CreatedAt.Value, item.ModifiedAt.Value, item.Size.Value, item.Sha1.ToLowerInvariant());
        }
        /// <summary>
        /// Used to update individual or multiple fields in the file object, including renaming the file, changing it’s description, 
        /// and creating a shared link for the file. To move a file, change the ID of its parent folder. An optional etag
        /// can be included to ensure that client only updates the file if it knows about the latest version.
        /// </summary>
        /// <param name="fileRequest"></param>
        /// <returns></returns>
        public async Task<BoxFile> UpdateInformationAsync(BoxFileRequest fileRequest, string etag = null, List<string> fields = null)
        {
            fileRequest.ThrowIfNull("fileRequest")
                .Id.ThrowIfNullOrWhiteSpace("fileRequest.Id");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, fileRequest.Id)
                .Method(RequestMethod.Put)
                .Header("If-Match", etag)
                .Param(ParamFields, fields);

            request.Payload = _converter.Serialize(fileRequest);

            IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
Exemplo n.º 20
0
        internal async Task Upload()
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker();
            fileOpenPicker.FileTypeFilter.Add("*");
            StorageFile openFile = await fileOpenPicker.PickSingleFileAsync();
            if (openFile == null)
                return;

            var stream = await openFile.OpenStreamForReadAsync();

            BoxFileRequest fileReq = new BoxFileRequest()
            {
                Name = openFile.Name,
                Parent = new BoxRequestEntity() { Id = FolderId }
            };
            BoxFile file = await Client.FilesManager.UploadAsync(fileReq, stream);
            Items.Add(file);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Uploads a provided file to the target parent folder.
        /// If the file already exists, an error will be thrown.
        /// A proper timeout should be provided for large uploads.
        /// </summary>
        /// <param name="fileRequest">BoxFileRequest object.</param>
        /// <param name="stream">Stream of uploading file.</param>
        /// <param name="fields">Fields which shall be returned in result.</param>
        /// <param name="timeout">Timeout for response.</param>
        /// <param name="contentMD5">The SHA1 hash of the file.</param>
        /// <param name="setStreamPositionToZero">Set position for input stream to 0.</param>
        /// <param name="uploadUri">Uri to use for upload. Default upload endpoint URI is used if not specified.</param>
        /// <returns>A full file object is returned inside of a collection if the ID is valid and if the update is successful.</returns>
        public async Task<BoxFile> UploadAsync(BoxFileRequest fileRequest, Stream stream, List<string> fields = null,
                                                TimeSpan? timeout = null, byte[] contentMD5 = null,
                                                bool setStreamPositionToZero = true,
                                                Uri uploadUri = null)
        {
            stream.ThrowIfNull("stream");
            fileRequest.ThrowIfNull("fileRequest")
                .Name.ThrowIfNullOrWhiteSpace("filedRequest.Name");
            fileRequest.Parent.ThrowIfNull("fileRequest.Parent")
                .Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id");

            if (setStreamPositionToZero)
                stream.Position = 0;

            uploadUri = uploadUri == null ? _config.FilesUploadEndpointUri : uploadUri;

            BoxMultiPartRequest request = new BoxMultiPartRequest(uploadUri) { Timeout = timeout }
                .Param(ParamFields, fields)
                .FormPart(new BoxStringFormPart()
                {
                    Name = "attributes",
                    Value = _converter.Serialize(fileRequest)
                })
                .FormPart(new BoxFileFormPart()
                {
                    Name = "file",
                    Value = stream,
                    FileName = fileRequest.Name
                });

            if (contentMD5 != null)
                request.Header(Constants.RequestParameters.ContentMD5, HexStringFromBytes(contentMD5));

            IBoxResponse<BoxCollection<BoxFile>> response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false);

            // We can only upload one file at a time, so return the first entry
            return response.ResponseObject.Entries.FirstOrDefault();
        }
        public async Task<FileSystemInfoContract> CopyItemAsync(RootName root, FileSystemId source, string copyName, DirectoryId destination, bool recurse)
        {
            var context = await RequireContext(root);

            if (source is DirectoryId) {
                var request = new BoxFolderRequest() { Id = source.Value, Name = copyName, Parent = new BoxRequestEntity() { Id = destination.Value } };
                var item = await AsyncFunc.Retry<BoxFolder, BoxException>(async () => await context.Client.FoldersManager.CopyAsync(request, boxFolderFields), RETRIES);

                return new DirectoryInfoContract(item.Id, item.Name, item.CreatedAt.Value, item.ModifiedAt.Value);
            }
            else {
                var request = new BoxFileRequest() { Id = source.Value, Name = copyName, Parent = new BoxRequestEntity() { Id = destination.Value } };
                var item = await AsyncFunc.Retry<BoxFile, BoxException>(async () => await context.Client.FilesManager.CopyAsync(request, boxFileFields), RETRIES);

                return new FileInfoContract(item.Id, item.Name, item.CreatedAt.Value, item.ModifiedAt.Value, item.Size.Value, item.Sha1.ToLowerInvariant());
            }
        }