示例#1
0
文件: Program.cs 项目: omrs2006/Ash
        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);
            }
        }
示例#2
0
        public File SaveFile(File file, Stream fileStream)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (fileStream == null)
            {
                throw new ArgumentNullException("fileStream");
            }

            BoxFile newBoxFile = null;

            if (file.ID != null)
            {
                newBoxFile = BoxProviderInfo.Storage.SaveStream(MakeBoxId(file.ID), fileStream, file.Title);
            }
            else if (file.FolderID != null)
            {
                var folderId = MakeBoxId(file.FolderID);
                file.Title = GetAvailableTitle(file.Title, folderId, IsExist);
                newBoxFile = BoxProviderInfo.Storage.CreateFile(fileStream, file.Title, folderId);
            }

            CacheInsert(newBoxFile);
            var parentId = GetParentFolderId(newBoxFile);

            if (parentId != null)
            {
                CacheReset(parentId);
            }

            return(ToFile(newBoxFile));
        }
示例#3
0
 private void txtInput_KeyUp(object sender, KeyEventArgs e)
 {
     //回车提交
     if (e.KeyCode == Keys.Enter)
     {
         string input = this.txtInput.Text.Trim();
         if (!string.IsNullOrEmpty(input))
         {
             BoxFile selectBoxFile = this.boxFiles.Where(o => o.Name == input).FirstOrDefault();
             if (selectBoxFile != null)
             {
                 bool canStart = Utils.StartFile(selectBoxFile.Path);
                 if (canStart)
                 {
                     this.Close();
                 }
                 else
                 {
                     this.lbInfo.Text = input + "=>[无法启动]";
                 }
                 selectBoxFile = null;
             }
             else
             {
                 this.lbInfo.Text = input + "=>[未找到]";
             }
         }
         else
         {
             this.lbInfo.Text = "=>[请输入]";
         }
         input = null;
     }
 }
        public async Task ViewVersions_ValidResponse_ValidFileVersions()
        {
            /*** Arrange ***/
            string responseString = "{ \"total_count\": 1, \"entries\": [ { \"type\": \"file_version\", \"id\": \"672259576\", \"sha1\": \"359c6c1ed98081b9a69eb3513b9deced59c957f9\", \"name\": \"Dragons.js\", \"size\": 92556, \"created_at\": \"2012-08-20T10:20:30-07:00\", \"modified_at\": \"2012-11-28T13:14:58-08:00\", \"modified_by\": { \"type\": \"user\", \"id\": \"183732129\", \"name\": \"sean rose\", \"login\": \"[email protected]\" } } ] }";

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

            /*** Act ***/
            BoxCollection <BoxFile> c = await _filesManager.ViewVersionsAsync("0");

            /*** Assert ***/
            Assert.AreEqual(c.TotalCount, 1);

            BoxFile f = c.Entries.First();

            Assert.AreEqual("672259576", f.Id);
            Assert.AreEqual("file_version", f.Type);
            Assert.AreEqual("359c6c1ed98081b9a69eb3513b9deced59c957f9", f.Sha1);
            Assert.AreEqual("Dragons.js", f.Name);
        }
示例#5
0
        private void CopyTiffBoxPairs(ref BackgroundWorker Slave, ref string ProcessStatus, List <App_Code.Font> SelectedFonts)
        {
            int expNum = 0;

            int Progress = 0;

            ProcessStatus = "Copying box/tif pairs...";
            Slave.ReportProgress(Progress);

            foreach (App_Code.Font F in SelectedFonts)
            {
                if (Slave.CancellationPending)
                {
                    break;
                }

                ProcessStatus = "Copying box/tif pairs for " + F.Name + "...";
                Progress++; if (Progress > 100)
                {
                    Progress = 100;
                }
                Slave.ReportProgress(Progress);

                if (Directory.Exists(TiffBoxPairsDir + "\\" + F.ID))
                {
                    string[] BoxFiles = Directory.GetFiles(TiffBoxPairsDir + "\\" + F.ID, "*.box", SearchOption.AllDirectories);

                    foreach (string BoxFile in BoxFiles)
                    {
                        if (File.Exists(BoxFile.Replace(".box", ".tif")))
                        {
                            string[] FileParts    = BoxFile.Split(new char[] { '\\' });
                            string   JustFileName = "";

                            if (FileParts.Length > 0)
                            {
                                JustFileName = FileParts[FileParts.Length - 1];
                            }

                            if (JustFileName != "")
                            {
                                string   FixedFileName = "";
                                string[] fileNameParts = JustFileName.Split(new char[] { '.' });
                                if (fileNameParts.Length == 4)
                                {
                                    FixedFileName = fileNameParts[0] + "." + fileNameParts[1] + ".exp" + expNum + "." + fileNameParts[3];
                                    expNum++;
                                }

                                if (FixedFileName != "")
                                {
                                    File.Copy(BoxFile, TrainingDir + "\\" + FixedFileName, true);
                                    File.Copy(BoxFile.Replace(".box", ".tif"), TrainingDir + "\\" + FixedFileName.Replace(".box", ".tif"), true);
                                }
                            }
                        }
                    }
                }
            }
        }
示例#6
0
        public Stream DownloadStream(BoxFile file, int offset = 0)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            if (offset > 0 && file.Size.HasValue)
            {
                return(_boxClient.FilesManager.DownloadAsync(file.Id, startOffsetInBytes: offset, endOffsetInBytes: (int)file.Size - 1).Result);
            }

            var str = _boxClient.FilesManager.DownloadAsync(file.Id).Result;

            if (offset == 0)
            {
                return(str);
            }

            var tempBuffer = TempStream.Create();

            if (str != null)
            {
                str.CopyTo(tempBuffer);
                tempBuffer.Flush();
                tempBuffer.Seek(offset, SeekOrigin.Begin);

                str.Dispose();
            }

            return(tempBuffer);
        }
        public Stream DownloadStream(BoxFile file, int offset = 0)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            if (offset > 0 && file.Size.HasValue)
            {
                return(_boxClient.FilesManager.DownloadStreamAsync(file.Id, startOffsetInBytes: offset, endOffsetInBytes: (int)file.Size - 1).Result);
            }

            var str = _boxClient.FilesManager.DownloadStreamAsync(file.Id).Result;

            if (offset == 0)
            {
                return(str);
            }

            var tempBuffer = new FileStream(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 8096, FileOptions.DeleteOnClose);

            if (str != null)
            {
                str.CopyTo(tempBuffer);
                tempBuffer.Flush();
                tempBuffer.Seek(offset, SeekOrigin.Begin);

                str.Dispose();
            }

            return(tempBuffer);
        }
示例#8
0
        public async Task <IActionResult> Rename(string newName, string uid, string currentFolderID, string type)
        {
            try
            {
                var client = Initialise();
                if (type == "file")
                {
                    BoxFile fileAfterRename = await client.FilesManager.UpdateInformationAsync(new BoxFileRequest()
                    {
                        Id = uid, Name = newName
                    });
                }
                else if (type == "folder")
                {
                    BoxFolder boxFolder = await client.FoldersManager.UpdateInformationAsync(new BoxFolderRequest()
                    {
                        Id = uid, Name = newName
                    });
                }

                Task.Run(() => { RecordFileAction(client, uid, "Rename"); });
                return(await GetBoxFolderItems(client, currentFolderID));
            }
            catch (BoxException exp)
            {
                return(StatusCode(Convert.ToInt32(exp.StatusCode)));
            }
        }
        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 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);
        }
示例#11
0
        /// <summary>
        /// 托盘的右键菜单单击事件
        /// </summary>
        private void toolStripSubMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;

            if (toolStripMenuItem.Name == MenuName_Exit)
            {
                //取消注册热键
                HotKey.UnregisterHotKey(this.Handle, _winQKey);
                HotKey.GlobalDeleteAtom(_winQKey);

                //退出
                this.Close();

                //(Exit)
                Application.Exit();
            }
            else
            {
                //打开文件
                BoxFile selectBoxFileItem = toolStripMenuItem.Tag as BoxFile;
                bool    state             = Utils.StartFile(selectBoxFileItem.Path);
                if (!state)
                {
                    MessageUtil.ShowTips(string.Format("文件“{0}”不存在。", selectBoxFileItem.Name));
                }
                selectBoxFileItem = null;
            }
            toolStripMenuItem = null;
        }
示例#12
0
        public File <string> ToFile(BoxFile boxFile)
        {
            if (boxFile == null)
            {
                return(null);
            }

            if (boxFile is ErrorFile)
            {
                //Return error entry
                return(ToErrorFile(boxFile as ErrorFile));
            }

            var file = GetFile();

            file.ID             = MakeId(boxFile.Id);
            file.ContentLength  = boxFile.Size.HasValue ? (long)boxFile.Size : 0;
            file.CreateOn       = boxFile.CreatedAt.HasValue ? TenantUtil.DateTimeFromUtc(boxFile.CreatedAt.Value) : default;
            file.FolderID       = MakeId(GetParentFolderId(boxFile));
            file.ModifiedOn     = boxFile.ModifiedAt.HasValue ? TenantUtil.DateTimeFromUtc(boxFile.ModifiedAt.Value) : default;
            file.NativeAccessor = boxFile;
            file.Title          = MakeFileTitle(boxFile);

            return(file);
        }
示例#13
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);
        }
示例#14
0
        public static void addShortcut(BoxFile _boxFile, string _groupName)
        {
            _boxFile.Key = BoxFileData.getUniqueKey(_boxFile.Name);
            if (existShortcut(_boxFile.Key, _groupName))
            {
                return;
            }

            var data     = BoxFileData.STATIC_Shortcuts.Where(o => o.Key.Key == BoxFileData.getUniqueKey(_groupName)).FirstOrDefault();
            var boxGroup = data.Key;
            var boxFiles = data.Value;

            if (boxFiles == null)
            {
                BoxFileData.STATIC_Shortcuts.Remove(boxGroup);

                boxFiles = new List <BoxFile>();
                boxFiles.Add(_boxFile);

                BoxFileData.STATIC_Shortcuts.Add(boxGroup, boxFiles);
            }
            else
            {
                boxFiles.Add(_boxFile);
            }

            BoxFileData.SaveShortcut();
        }
        public async Task CreateFileSharedLink_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
            }));

            BoxSharedLinkRequest sharedLink = new BoxSharedLinkRequest()
            {
                Access = BoxSharedLinkAccessType.collaborators
            };

            /*** Act ***/
            BoxFile f = await _filesManager.CreateSharedLinkAsync("0", sharedLink);

            /*** 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);
        }
示例#16
0
        public File ToFile(BoxFile boxFile)
        {
            if (boxFile == null)
            {
                return(null);
            }

            if (boxFile is ErrorFile)
            {
                //Return error entry
                return(ToErrorFile(boxFile as ErrorFile));
            }

            return(new File
            {
                ID = MakeId(boxFile.Id),
                Access = FileShare.None,
                ContentLength = boxFile.Size.HasValue ? (long)boxFile.Size : 0,
                CreateBy = BoxProviderInfo.Owner,
                CreateOn = boxFile.CreatedAt.HasValue ? TenantUtil.DateTimeFromUtc(boxFile.CreatedAt.Value) : default(DateTime),
                FileStatus = FileStatus.None,
                FolderID = MakeId(GetParentFolderId(boxFile)),
                ModifiedBy = BoxProviderInfo.Owner,
                ModifiedOn = boxFile.ModifiedAt.HasValue ? TenantUtil.DateTimeFromUtc(boxFile.ModifiedAt.Value) : default(DateTime),
                NativeAccessor = boxFile,
                ProviderId = BoxProviderInfo.ID,
                ProviderKey = BoxProviderInfo.ProviderKey,
                Title = MakeFileTitle(boxFile),
                RootFolderId = MakeId(),
                RootFolderType = BoxProviderInfo.RootFolderType,
                RootFolderCreator = BoxProviderInfo.Owner,
                Shared = false,
                Version = 1
            });
        }
示例#17
0
        public async Task UploadNewVersion_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\": { \"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\", \"tags\": [ \"important\", \"needs review\" ] } ] }";

            _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 fakeStream = new Mock <System.IO.Stream>();

            /*** Act ***/
            BoxFile f = await _filesManager.UploadNewVersionAsync("fakeFile", "0", fakeStream.Object, "1");

            /*** 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);
            Assert.AreEqual("important", f.Tags[0]);
            Assert.AreEqual("needs review", f.Tags[1]);
        }
示例#18
0
        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));
        }
示例#19
0
        public Stream DownloadStream(BoxFile file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            return(_boxClient.FilesManager.DownloadStreamAsync(file.Id).Result);
        }
        public async Task ExecuteMetadataQueryWithFields_ValidResponse()
        {
            /*** Arrange ***/
            string      responseString = "{\"entries\":[{\"type\":\"file\",\"id\":\"1244738582\",\"etag\":\"1\",\"sha1\":\"012b5jdunwkfu438991344044\",\"name\":\"Very Important.docx\",\"metadata\":{\"enterprise_67890\":{\"catalogImages\":{\"$parent\":\"file_50347290\",\"$version\":2,\"$template\":\"catalogImages\",\"$scope\":\"enterprise_67890\",\"photographer\":\"Bob Dylan\"}}}},{\"type\":\"folder\",\"id\":\"124242482\",\"etag\":\"1\",\"sha1\":\"012b5ir8391344044\",\"name\":\"Also Important.docx\",\"metadata\":{\"enterprise_67890\":{\"catalogImages\":{\"$parent\":\"file_50427290\",\"$version\":2,\"$template\":\"catalogImages\",\"$scope\":\"enterprise_67890\",\"photographer\":\"Bob Dylan\"}}}}],\"limit\":2,\"next_marker\":\"0!WkeoDQ3mm5cI_RzSN--UOG1ICuw0gz3729kfhwuoagt54nbvqmgfhsygreh98nfu94344PpctrcgVa8AMIe7gRwSNBNloVR-XuGmfqTw\"}";
            IBoxRequest boxRequest     = null;

            Handler.Setup(h => h.ExecuteAsync <BoxCollectionMarkerBased <BoxItem> >(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxCollectionMarkerBased <BoxItem> > >(new BoxResponse <BoxCollectionMarkerBased <BoxItem> >()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var queryParams = new Dictionary <string, object>();

            queryParams.Add("arg", "Bob Dylan");
            List <string> fields = new List <string>();

            fields.Add("id");
            fields.Add("name");
            fields.Add("sha1");
            fields.Add("metadata.enterprise_240748.catalogImages.photographer");
            string marker = "q3f87oqf3qygou5t478g9gwrbul";
            BoxCollectionMarkerBased <BoxItem> items = await _metadataManager.ExecuteMetadataQueryAsync(from : "enterprise_67890.catalogImages", query : "photographer = :arg", fields : fields, queryParameters : queryParams, ancestorFolderId : "0", marker : marker, autoPaginate : false);

            /*** Assert ***/

            // Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(MetadataQueryUri, boxRequest.AbsoluteUri.AbsoluteUri);
            JObject payload = JObject.Parse(boxRequest.Payload);

            Assert.AreEqual("enterprise_67890.catalogImages", payload["from"]);
            Assert.AreEqual("photographer = :arg", payload["query"]);
            Assert.AreEqual("0", payload["ancestor_folder_id"]);
            JArray payloadFields = JArray.Parse(payload["fields"].ToString());

            Assert.AreEqual("id", payloadFields[0]);
            Assert.AreEqual("name", payloadFields[1]);
            Assert.AreEqual("sha1", payloadFields[2]);
            Assert.AreEqual("metadata.enterprise_240748.catalogImages.photographer", payloadFields[3]);
            Assert.AreEqual(marker, payload["marker"]);

            // Response check
            Assert.AreEqual(items.Entries[0].Type, "file");
            Assert.AreEqual(items.Entries[0].Id, "1244738582");
            Assert.AreEqual(items.Entries[0].Name, "Very Important.docx");
            Assert.AreEqual(items.Entries[1].Type, "folder");
            Assert.AreEqual(items.Entries[1].Id, "124242482");
            Assert.AreEqual(items.Entries[1].Name, "Also Important.docx");
            BoxFile file = (BoxFile)items.Entries[0];

            Assert.AreEqual(file.Metadata["enterprise_67890"]["catalogImages"]["photographer"].Value, "Bob Dylan");
        }
示例#21
0
        protected String MakeFileTitle(BoxFile boxFile)
        {
            if (boxFile == null || string.IsNullOrEmpty(boxFile.Name))
            {
                return(BoxProviderInfo.ProviderKey);
            }

            return(Global.ReplaceInvalidCharsAndTruncate(boxFile.Name));
        }
示例#22
0
        private async Task <Content> GetBoxItem(BoxClient client, string ID)
        {
            _logger.LogInformation("Retrieving data needed to record the file action");
            //String[] fields = new String[1] { BoxFile.FieldSha1 };
            BoxFile boxFile = await client.FilesManager.GetInformationAsync(ID);

            Content content = GetCustomFileObject(boxFile);

            return(content);
        }
示例#23
0
        public static void deleteLikeShortcut(BoxFile _boxFile)
        {
            if (!existLikeShortcut(_boxFile.Key))
            {
                return;
            }

            BoxFileData.STATIC_LikeShortcuts.Remove(_boxFile);

            BoxFileData.SaveLikeShortcut();
        }
示例#24
0
        public async Task GetSharedLink_ValidRequest_ValidSharedLink()
        {
            BoxSharedLinkRequest linkReq = new BoxSharedLinkRequest()
            {
                Access = BoxSharedLinkAccessType.open
            };

            BoxFile fileLink = await _client.FilesManager.CreateSharedLinkAsync("11999421592", linkReq);

            Assert.AreEqual(BoxSharedLinkAccessType.open, fileLink.SharedLink.Access);
        }
示例#25
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);
        }
示例#26
0
        public async Task UploadNewVersionAsync_ForNewFileVersion_ShouldReturnDifferentFile()
        {
            var uploadedFile = await CreateSmallFile(FolderId);

            using (var fileStream = new FileStream(GetSmallFileV2Path(), FileMode.OpenOrCreate))
            {
                BoxFile newVersionFile = await UserClient.FilesManager.UploadNewVersionAsync(GetUniqueName("file"), uploadedFile.Id, fileStream);

                Assert.AreNotEqual(uploadedFile.FileVersion.Id, newVersionFile.FileVersion.Id);
            }
        }
示例#27
0
 protected void PrintFile(BoxFile file, bool json = false)
 {
     if (json)
     {
         base.OutputJson(file);
         return;
     }
     else
     {
         this.PrintFile(file);
     }
 }
示例#28
0
        public static void addLikeShortcut(BoxFile _boxFile)
        {
            _boxFile.Key = BoxFileData.getUniqueKey(_boxFile.Name);

            if (existLikeShortcut(_boxFile.Key))
            {
                return;
            }

            BoxFileData.STATIC_LikeShortcuts.Add(_boxFile);

            BoxFileData.SaveLikeShortcut();
        }
示例#29
0
        public async Task GetSharedLink_ValidRequest_ValidSharedLink()
        {
            string imageFileId1 = "16894947279";

            BoxSharedLinkRequest linkReq = new BoxSharedLinkRequest()
            {
                Access = BoxSharedLinkAccessType.open
            };

            BoxFile fileLink = await _client.FilesManager.CreateSharedLinkAsync(imageFileId1, linkReq);

            Assert.AreEqual(BoxSharedLinkAccessType.open, fileLink.SharedLink.Access);
        }
示例#30
0
        /// <summary>
        /// GetCustomFileObject returns custom content from BoxFile Object.
        /// </summary>
        /// <param name="boxFile"></param>
        /// <returns></returns>
        private Content GetCustomFileObject(BoxFile boxFile)
        {
            Content cont = new Content();

            cont.Type         = boxFile.Type;
            cont.Id           = boxFile.Id;
            cont.FileName     = boxFile.Name;
            cont.Size         = boxFile.Size.ToString();
            cont.Hash         = boxFile.Sha1;
            cont.LastModified = boxFile.ModifiedAt.ToString();
            cont.Secure       = "false";
            return(cont);
        }
示例#31
0
        //Function to allow the user to select the directory they'd like to find files in
        void DirectoryClick(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();	//Create a new FolderBrowser
             			DialogResult result = fbd.ShowDialog();					//Open FolderBrowser

             			string[] filepaths = {};								//Create an array that will hold the file paths

             			try
             			{
             				filepaths = Directory.GetFiles(fbd.SelectedPath,"*.pgn", SearchOption.TopDirectoryOnly);
             				//Convert all the file names in the directory with the .pgn file extension to the array of filepaths
             				Array.Sort(filepaths); //Make sure they're sorted for the user
             				f.addFilePaths(filepaths);	//Make sure functions knows what files we're operating on
             			}
             			catch(Exception exception)
             			{
             				Debug.WriteLine(exception.ToString());
             				return;
             			}

             			SelectAllButton.Visible = true;	//Make select all button visible
             			DeselectAllButton.Visible = true; //Make deselect all button visible

             			for(int i = 0; i < filepaths.Length; i++)
             			{
             				string[] split = filepaths[i].Split('\\');	//Split the file path by the \\ to get file name
             				BoxFile temp = new BoxFile(filepaths[i],split[split.Length-1]);	//Create a new BoxFile object with file path and file name
             				FileCheckedBox.Items.Add(temp, true);	//Add it to the checkedFileBox with the value true
             			}
        }
示例#32
0
        //Button used to parse all the selected games
        void DisplayButtonClick(object sender, System.EventArgs e)
        {
            int king_val = 0;
            int queen_val = 0;
            int rook_val = 0;
            int bishop_val = 0;
            int knight_val = 0;
            int pawn_val = 0;
            int ELO_val = 0;

            try //Try and parse the values of the textboxes for piece values from user
            {
                king_val = int.Parse(kingBox.Text);
                queen_val = int.Parse(queenBox.Text);
                rook_val = int.Parse(rookBox.Text);
                bishop_val = int.Parse(bishopBox.Text);
                knight_val = int.Parse(knightBox.Text);
                pawn_val = int.Parse(pawnBox.Text);
                ELO_val = int.Parse(ELObox.Text);
            }
            catch(Exception ex) //If there's an issue with that
            {
                MessageBox.Show("There was an error with your piece values or ELO. Using default values." +ex.ToString());
                //Tell the user about the error
                king_val = 0;	//And set the values to their standard values
                queen_val = 8;
                rook_val = 5;
                bishop_val = 3;
                knight_val = 3;
                pawn_val = 1;
                ELO_val = 0;
            }
            finally //Then actually parse each file
            {
                foreach(object itemChecked in FileCheckedBox.CheckedItems) //For each item in the checked file box that is checked
                {
                    BoxFile tempBoxFile = new BoxFile();	//Create a new temporary BoxFile
                    tempBoxFile = (BoxFile)itemChecked;		//Cast it from the object passed by the loop
                    FileInfo tempFileInfo = new FileInfo(tempBoxFile.fullpath); //Create a fileInfo from its full path
                    f.parsePGN(tempFileInfo, king_val, queen_val, rook_val, bishop_val, knight_val, pawn_val, ELO_val);
                    //Parse the file with the piece values and elo value
                }
                f.print(); //After each file has been parsed, print the file to csv
            }
        }