Example #1
0
        static async Task MainAsync()
        {
            //first we need to refresh the tokens and persist them in a file
            var newSession = await client.Auth.RefreshAccessTokenAsync(access_token);

            //store the tokens on disk
            File.WriteAllText(TOKEN_FILENAME, newSession.AccessToken + TOKEN_SPLIT_CHAR + newSession.RefreshToken);

            //look up the folder id based on the path
            var boxFolderId = await FindBoxFolderId(BOX_FOLDER_PATH);

            using (FileStream fs = File.Open(PATH_TO_FILE + FILENAME, FileMode.Open, FileAccess.Read))
            {
                Console.WriteLine("Uploading file...");

                // Create request object with name and parent folder the file should be uploaded to
                BoxFileRequest request = new BoxFileRequest()
                {
                    Name   = DateTime.Now.ToFileTime() + "-" + FILENAME, //for this demo, don't collide with any other files
                    Parent = new BoxRequestEntity()
                    {
                        Id = boxFolderId
                    }
                };
                BoxFile f = await client.FilesManager.UploadAsync(request, fs);
            }
        }
Example #2
0
        public async Task UpdateFileInformation_ForNewDispositionDate_ShouldBeAbleToUpdateIt()
        {
            var adminFolder = await CreateFolderAsAdmin("0");

            var uploadedFile = await CreateSmallFileAsAdmin(adminFolder.Id);

            await CreateRetentionPolicy(adminFolder.Id);

            var newDispositionDate = DateTimeOffset.Now.AddDays(1);
            var boxFileRequest     = new BoxFileRequest
            {
                Id            = uploadedFile.Id,
                DispositionAt = newDispositionDate
            };

            await Retry(async() =>
            {
                await AdminClient.FilesManager.UpdateInformationAsync(boxFileRequest);

                var response = await AdminClient.FilesManager.GetInformationAsync(uploadedFile.Id, new List <string>()
                {
                    "disposition_at"
                });

                Assert.IsTrue(newDispositionDate.IsEqualUpToSeconds(response.DispositionAt.Value));
            }, 5, 5000);
        }
        public static async Task Setup(BoxClient boxClient)
        {
            var folderRequest = new BoxFolderRequest()
            {
                Name = "Test Folder", Parent = new BoxRequestEntity()
                {
                    Id = "0"
                }
            };
            var newFolder = await boxClient.FoldersManager.CreateAsync(folderRequest);

            var pathToFile = HttpContext.Current.Server.MapPath("~/");
            var fileName   = "text.txt";

            using (FileStream fs = File.Open(pathToFile + fileName, FileMode.Open))
            {
                // Create request object with name and parent folder the file should be uploaded to
                BoxFileRequest request = new BoxFileRequest()
                {
                    Name   = fileName,
                    Parent = new BoxRequestEntity()
                    {
                        Id = "0"
                    }
                };
                var boxFile = await boxClient.FilesManager.UploadAsync(request, fs);
            }
        }
        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()));
            }
        }
Example #5
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());
        }
Example #7
0
        private async Task ExecuteMainAsync()
        {
            var devToken       = "E3myQeNXgY2PA5q2AQaSqLbEUIVabPeU";
            var fileName       = "test.txt";
            var localFilePath  = @"C:\Users\Public\test.txt";
            var parentFolderId = "1";

            var timer = Stopwatch.StartNew();



            var config = new BoxConfig(CLIENT_ID, CLIENT_SECRET, new Uri("http://boxsdk"));
            //DevToken
            var auth   = new OAuthSession(devToken, "NOT_NEEDED", 3600, "bearer");
            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);
            Console.ReadKey();
        }
        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()));
            }
        }
        public async Task UpdateFileInformation_ValidResponse_ValidFile()
        {
            string responseString = "{ \"type\": \"file\", \"id\": \"5000948880\", \"sequence_id\": \"3\", \"etag\": \"3\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\", \"name\": \"new name.jpg\", \"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
            }));

            /*** Act ***/
            BoxFileRequest request = new BoxFileRequest()
            {
                Id = "fakeId"
            };

            BoxFile f = await _filesManager.UpdateInformationAsync(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);
        }
        public async Task <ActionResult> Upload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                var fileName = file.FileName;
                using (var fs = file.InputStream)
                {
                    // Create request object with name and parent folder the file should be uploaded to
                    BoxFileRequest request = new BoxFileRequest()
                    {
                        Name   = fileName,
                        Parent = new BoxRequestEntity()
                        {
                            Id = "0"
                        }
                    };
                    string email   = this.GetCurrentUserEmail();
                    var    boxUser = await BoxHelper.GetOrCreateBoxUser(email);

                    var boxFile = await BoxHelper.UserClient(boxUser.Id).FilesManager.UploadAsync(request, fs);
                }
            }

            return(RedirectToAction("Index"));
        }
        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()));
            }
        }
Example #12
0
        public async Task Get(int id)
        {
            var client = BuildConfig().Item2;

            var code = Request.Query["code"];
            await client.Auth.AuthenticateAsync(code);

            BoxFile newFile;

            // Create request object with name and parent folder the file should be uploaded to
            using (FileStream stream = new FileStream("taxdoc.txt", FileMode.Open))
            {
                BoxFileRequest req = new BoxFileRequest()
                {
                    Name   = "taxdoc.txt",
                    Parent = new BoxRequestEntity()
                    {
                        Id = "0"
                    }
                };
                newFile = await client.FilesManager.UploadAsync(req, stream);

                Console.Out.Write(newFile.Id);
            }
        }
        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);
        }
Example #14
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);
        }
        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",
                ContentCreatedAt  = DateTime.Now,
                ContentModifiedAt = DateTime.Now,
                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);
        }
Example #16
0
        public bool UploadCloudFile(FileBlock file, string destinationPath = null)
        {
            bool status = false;

            try
            {
                using (var stream = new FileStream(file.path, FileMode.OpenOrCreate))
                {
                    BoxFileRequest request = new BoxFileRequest()
                    {
                        Name   = file.id,
                        Parent = new BoxRequestEntity()
                        {
                            Id = file.Parent[0]
                        }
                    };
                    Task task = Task.Run(() => client.FilesManager.UploadAsync(request, stream));
                    task.Wait();
                    status = true;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(status);
        }
        public async Task <ICustomActivityResult> Execute()
        {
            var Message = string.Empty;

            var boxConfig   = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT      = new BoxJWTAuth(boxConfig);
            var adminToken  = boxJWT.UserToken(USER_ID);
            var adminClient = boxJWT.AdminClient(adminToken);

            using (FileStream fileStream = new FileStream(FilePath, FileMode.Open))
            {
                BoxFileRequest requestParams = new BoxFileRequest()
                {
                    Name   = NameFile,
                    Parent = new BoxRequestEntity()
                    {
                        Id = FolderID
                    }
                };
                BoxFile file = await adminClient.FilesManager.UploadAsync(requestParams, fileStream);

                Message = file.Id;
            }
            return(this.GenerateActivityResult(Message));
        }
        public BoxFile RenameFile(string boxFileId, string newName)
        {
            var boxFileRequest = new BoxFileRequest {
                Id = boxFileId, Name = newName
            };

            return(_boxClient.FilesManager.UpdateInformationAsync(boxFileRequest, null, _boxFields).Result);
        }
        public async Task <bool> BoxUpLoadFileAsunc(BoxClient client, string filePath, string parentID)
        {
            bool _isSuccessUpload = false;

            if (client == null)
            {
                return(_isSuccessUpload);
            }
            if (!System.IO.File.Exists(filePath))
            {
                return(_isSuccessUpload);
            }

            FileInfo     info               = new System.IO.FileInfo(filePath);
            long         fileSize           = info.Length;
            MemoryStream fileInMemoryStream = GetBigFileInMemoryStream(fileSize);
            string       loadfileName       = System.IO.Path.GetFileName(filePath);
            string       fileName           = info.Name;
            bool         progressReported   = false;
            long         minSize            = 20 * 1024 * 1024;

            try
            {
                if (fileSize >= minSize)
                {
                    var progress = new Progress <BoxProgress>(val =>
                    {
                        Debug.WriteLine("{0}%", val.progress);
                        progressReported = true;
                    });
                    await client.FilesManager.UploadUsingSessionAsync(fileInMemoryStream, loadfileName, parentID, null, progress);

                    fileInMemoryStream.Close();
                }
                else
                {
                    using (FileStream fs = new FileStream(loadfileName, FileMode.Open))
                    {
                        BoxFileRequest req = new BoxFileRequest
                        {
                            Name   = fileName,
                            Parent = new BoxRequestEntity {
                                Id = parentID
                            }
                        };
                        await client.FilesManager.UploadAsync(req, fs);
                    }
                }
            }
            catch (Exception ex)
            {
                //throw;
                return(false);
            }
            return(true);
        }
Example #20
0
        public async Task RestoreFile_Valid_Response()
        {
            const string   fileId      = "238288183114";
            BoxFileRequest fileRequest = new BoxFileRequest()
            {
                Id = fileId
            };

            var restoredFile = await _client.FilesManager.RestoreTrashedAsync(fileRequest);
        }
Example #21
0
        public override async void Copy(FileItem from, FileItem to)
        {
            BoxFileRequest req = new BoxFileRequest();

            req.Name   = Path.GetFileName(to.Path);
            req.Parent = new BoxRequestEntity()
            {
                Id = Path.GetPathRoot(to.Path)
            };
            BoxFile request = await client.FilesManager.CopyAsync(req);
        }
Example #22
0
        public override async void Upload(FileItem from, FileItem to)
        {
            BoxFileRequest req = new BoxFileRequest();

            req.Name   = Path.GetFileName(to.Path);
            req.Parent = new BoxRequestEntity()
            {
                Id = Path.GetPathRoot(to.Path)
            };
            var newFile = await client.FilesManager.UploadAsync(req, DataUtils.GetStreamFromPath(from.Path));
        }
        public static BoxFileRequest FileItemToBoxFileRequest(FileItem to)
        {
            BoxFileRequest req = new BoxFileRequest();

            req.Name   = Path.GetFileName(to.Path);
            req.Parent = new BoxRequestEntity()
            {
                Id = Path.GetPathRoot(to.Path)
            };
            return(req);
        }
Example #24
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));
        }
Example #25
0
        public static async Task PrepareBoxAppUser(ClaimsIdentity externalIdentity)
        {
            var auth0UserId = externalIdentity.Claims.FirstOrDefault(c => c.Type == "user_id").Value;
            var boxId       = GetBoxIdFromAuth0(auth0UserId);

            if (boxId == null)
            {
                //create a new app user in Box
                string email       = externalIdentity.Claims.FirstOrDefault(c => c.Type == "email").Value;
                var    userRequest = new BoxUserRequest()
                {
                    Name = email, IsPlatformAccessOnly = true
                };
                var appUser = await AdminClient().UsersManager.CreateEnterpriseUserAsync(userRequest);

                boxId = appUser.Id;

                //store the boxId in the user's Auth0 metadata
                var meta = new Dictionary <string, object>();
                meta.Add(BOX_USER_ID_KEY, boxId);
                AUTH0_CLIENT.UpdateUserMetadata(auth0UserId, meta);

                //now do the initial box account setup
                var boxClient     = UserClient((string)boxId);
                var folderRequest = new BoxFolderRequest()
                {
                    Name = "Test Folder", Parent = new BoxRequestEntity()
                    {
                        Id = "0"
                    }
                };
                var newFolder = await boxClient.FoldersManager.CreateAsync(folderRequest);

                var pathToFile = HttpContext.Current.Server.MapPath("~/Assets/");
                var fileName   = "test.txt";
                using (FileStream fs = File.Open(pathToFile + fileName, FileMode.Open))
                {
                    // Create request object with name and parent folder the file should be uploaded to
                    BoxFileRequest request = new BoxFileRequest()
                    {
                        Name   = fileName,
                        Parent = new BoxRequestEntity()
                        {
                            Id = "0"
                        }
                    };
                    var boxFile = await boxClient.FilesManager.UploadAsync(request, fs);
                }
            }

            HttpContext.Current.Session[BOX_USER_ID_KEY] = (string)boxId;
        }
Example #26
0
 public static void UploadFileToBox(BoxClient client, string fileName, string path, string parentFolderId)
 {
     var fileRequest = new BoxFileRequest()
     {
         Name   = fileName,
         Parent = new BoxRequestEntity()
         {
             Id = parentFolderId
         }
     };
     StreamReader fileReader = new StreamReader(path);
     var          file       = client.FilesManager.UploadAsync(fileRequest, fileReader.BaseStream).Result;
 }
        public Task UploadStream(Stream stream, string filename, MemoryStream data)
        {
            var req = new BoxFileRequest
            {
                Name   = filename,
                Parent = new BoxRequestEntity {
                    Id = "0"
                },
                Description = "ripped_music"
            };

            return(_boxClient.FilesManager.UploadAsync(req, data));
        }
Example #28
0
        public BoxFile MoveFile(string boxFileId, string toFolderId)
        {
            var boxFileRequest = new BoxFileRequest
            {
                Id     = boxFileId,
                Parent = new BoxRequestEntity
                {
                    Id = toFolderId
                }
            };

            return(_boxClient.FilesManager.UpdateInformationAsync(boxFileRequest, null, _boxFields).Result);
        }
        public BoxFile CreateFile(Stream fileStream, string title, string parentId)
        {
            var boxFileRequest = new BoxFileRequest
            {
                Name   = title,
                Parent = new BoxRequestEntity
                {
                    Id = parentId
                }
            };

            return(_boxClient.FilesManager.UploadAsync(boxFileRequest, fileStream, _boxFields, setStreamPositionToZero: false).Result);
        }
        public BoxFile CopyFile(string boxFileId, string newFileName, string toFolderId)
        {
            var boxFileRequest = new BoxFileRequest
            {
                Id     = boxFileId,
                Name   = newFileName,
                Parent = new BoxRequestEntity
                {
                    Id = toFolderId
                }
            };

            return(_boxClient.FilesManager.CopyAsync(boxFileRequest, _boxFields).Result);
        }