public void Test1() { FileManager newSys = new FileManager(); DateTime date1 = new DateTime(2019, 7, 20, 18, 30, 25); AbstractFile file1 = new AbstractFile("Test1", 100, date1); AbstractFile file2 = new AbstractFile("Test2", 100, date1); newSys.AddFile(file1); newSys.AddFile(file2); List <AbstractFile> list = newSys.EndEditing(); StorageAlgorithms algorithm = new StorageAlgorithms(); var pointInfo1 = algorithm.SeparateBackup(list, Type.Full); var pointInfo2 = algorithm.SeparateBackup(list, Type.Full); RestoreSystem newChain = new RestoreSystem(); newChain.AddPoint(pointInfo1); newChain.AddPoint(pointInfo2); ICleaningPoints Clean = new CleanByPoints(1); Clean.Clean(newChain.Points); Assert.AreEqual(1, newChain.ShowRestorePoints().Count); Assert.AreEqual(1, newChain.ShowRestorePoints().Count); }
public void Test2() { FileManager newSys = new FileManager(); DateTime date1 = new DateTime(2019, 7, 20, 18, 30, 25); AbstractFile file1 = new AbstractFile("Test1", 100, date1); AbstractFile file2 = new AbstractFile("Test2", 100, date1); newSys.AddFile(file1); newSys.AddFile(file2); List <AbstractFile> list = newSys.EndEditing(); StorageAlgorithms algorithm = new StorageAlgorithms(); var pointInfo1 = algorithm.SeparateBackup(list, Type.Full); var pointInfo2 = algorithm.SeparateBackup(list, Type.Full); RestoreSystem newChain = new RestoreSystem(); newChain.AddPoint(pointInfo1); newChain.AddPoint(pointInfo2); ICleaningPoints Clean = new CleanBySize(250); Clean.StartClean(newChain.Points); //Не совсем понимаю почему должен остаться один бекап если мы закидываем два FULL Backup(каждый по 200мб), то теоретически мы их можем удалять без последствий и удалим каждый с весом >150 Assert.AreEqual(1, newChain.ShowRestorePoints().Count); }
private async void simpleFileToolStripMenuItem_Click(object sender, EventArgs e) { var di = new SimpleFile(); if (di.ShowDialog() == DialogResult.OK) { Task[] ts = new Task[di.FileNames.Length]; for (int i = 0; i < ts.Length; i++) { ts[i] = filesSystem.AddFile(di.FileNames[i], Category.GetCategory(di.Category)); } await Task.WhenAll(ts); } }
public int UploadFile(int groupId) { int groupFileId = 155; var groupFolderPath = "Groups/" + groupId; var f = new FileInfo(); var fc = new FileManager(); if (groupId > 0 && FileUploadControl.HasFile) { var role = RoleController.Instance.GetRoleById(PortalId, groupId); var fo = FolderManager.Instance.GetFolder(PortalId, groupFolderPath); if (fo != null) { groupFileId = fc.AddFile(fo, FileUploadControl.PostedFile.FileName, FileUploadControl.PostedFile.InputStream, false, true, FileUploadControl.PostedFile.ContentType).FileId; } else { var pc = new PermissionController(); var browsePermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "BROWSE").Cast <PermissionInfo>().FirstOrDefault(); var readPermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "READ").Cast <PermissionInfo>().FirstOrDefault(); var writePermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "WRITE").Cast <PermissionInfo>().FirstOrDefault(); var groupFolder = FolderManager.Instance.AddFolder(PortalId, groupFolderPath); groupFolder.FolderPermissions.Add(new FolderPermissionInfo(browsePermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); groupFolder.FolderPermissions.Add(new FolderPermissionInfo(readPermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); groupFolder.FolderPermissions.Add(new FolderPermissionInfo(writePermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); groupFolder.IsProtected = true; FolderManager.Instance.UpdateFolder(groupFolder); groupFileId = fc.AddFile(groupFolder, FileUploadControl.PostedFile.FileName, FileUploadControl.PostedFile.InputStream, false, true, FileUploadControl.PostedFile.ContentType).FileId; } } return(groupFileId); }
public void AddDocFilePathReturnsDocFile() { var actual = FileManager.AddFile(TestDocFilePath); Check.That(actual).IsInstanceOf <DocFile>() .And.Satisfies(() => actual.FileName == "Test paragraph about house fires.doc"); }
public void AddDocFileTest() { var result = FileManager.AddFile(TestDocFilePath); Check.That(Info(FileManager.DocFilesDirectory + @"\Test paragraph about house fires.doc")).Exists(); Check.That(result).IsInstanceOf <DocFile>(); }
private NodeInfoViewModel CreateFile(string name, string owner = "John Doe") { fileManager.AddFile(name, owner); var folder = fileManager.GetNodeInfo(name); return(folder); }
public void AddPdfFilePathReturnsPdfFile() { var path = @"..\..\MockUserFiles\Test paragraph about house fires.pdf"; var actual = FileManager.AddFile(path); Check.That(actual.FileName).IsEqualTo("Test paragraph about house fires.pdf"); Check.That(actual).IsInstanceOf <PdfFile>(); }
public void AddDocXFilePathReturnsDocXFile() { var path = TestDocXFilePath; var actual = FileManager.AddFile(path); Check.That(actual.FileName).IsEqualTo("Test paragraph about house fires.docx"); Check.That(actual).IsInstanceOf <DocXFile>(); }
public void AddDocXFileTest() { var sourcePath = TestDocXFilePath; var result = FileManager.AddFile(sourcePath); Check.That(result).IsInstanceOf <DocXFile>() .And.Satisfies(result.Exists); }
public void AddPdfFileTest() { var sourcePath = @"..\..\MockUserFiles\Test paragraph about house fires.pdf"; var result = FileManager.AddFile(sourcePath); Check.That(FileManager.PdfFilesDirectory + @"\Test paragraph about house fires.pdf") .Satisfies(File.Exists); Check.That(result).IsInstanceOf <PdfFile>(); }
private void btnAddFiles_Click(object sender, EventArgs e) { if (filesToAdd == null || filesToAdd.Count == 0) { return; } int nAdded = 0; List <TrackedFile> newFiles = new List <TrackedFile>(); foreach (var file in filesToAdd) { FileInfo fi = new FileInfo(file); if (!fi.Exists) { continue; } bool alreadyInSystem = FileManager.Exists(file); if (!alreadyInSystem) { TrackedFile newFile = FileManager.AddFile( Path.GetFileNameWithoutExtension(fi.Name), fi.Extension.Substring(1), fi.DirectoryName, (int)fi.Length, fi.CreationTime, fi.LastWriteTime); if (newFile != null) { LogFileAdded(newFile); newFiles.Add(newFile); nAdded++; } } } bool wantsLink = chkLinkFiles.Checked; string linkResult = null; if (wantsLink && nAdded > 1 && newFiles.Count > 1) { string memo = txtMemo.Text.Trim(); var fileIDs = from file in newFiles select file.FileID; FileLink newLink = LinkManager.AddLink(fileIDs.ToList(), memo); if (newLink != null) { // Log link creation and each file joined LogLinkCreation(newLink.LinkMemoID, nAdded, memo); LogLinkJoined(newLink, newLink.GetFiles()); linkResult = $"\n\nLinked {nAdded} files" + (string.IsNullOrEmpty(memo) ? "." : $" as '{memo}'."); } } string resultPrompt = $"Added {nAdded} file(s)." + linkResult; Messenger.Show(resultPrompt, caption); DialogResult = DialogResult.OK; Close(); }
public void AddTxtFileTest() { var sourcePath = @"..\..\MockUserFiles\Test paragraph about house fires.txt"; var result = FileManager.AddFile(sourcePath); var txtFileInfo = new FileInfo(FileManager.TxtFilesDirectory + @"\Test paragraph about house fires.txt"); Check.That(txtFileInfo).Exists(); Check.That(result).IsInstanceOf <TxtFile>(); }
public void HasSimilarFileTest() { foreach (var file in AllTestFiles) { FileManager.AddFile(file.FullPath); } foreach (var file in AllTestFiles) { Check.That(file.NameSansExt).Satisfies(FileManager.HasSimilarFile); Check.That(file).Satisfies(FileManager.HasSimilarFile); } }
public void GetFilesTest() { // Add 2 test files FileManager.AddFile("Test File 1", "test", "test", 1000, DateTime.Now, DateTime.Now); FileManager.AddFile("Test File 2", "test", "test", 1000, DateTime.Now, DateTime.Now); // Get all files List <TrackedFile> trackedFiles = FileManager.GetFiles(); // Verify there are least two files Assert.IsTrue(trackedFiles.Count >= 2); }
public void RemoveFileTest() { var file = AllTestFiles.ElementAt(new Random().Next(0, AllTestFiles.Count())); FileManager.AddFile(file.FullPath); Check.That(file).Satisfies(FileManager.HasSimilarFile); FileManager.RemoveFile(file); Check.That(file).DoesNotSatisfy(FileManager.HasSimilarFile); }
public void Test3() //Тест на раздельное хранение. Узнаём что все файлы дошли до конца. { FileManager newSys = new FileManager(); DateTime date1 = new DateTime(2019, 7, 20, 18, 30, 25); AbstractFile file1 = new AbstractFile("Test1", 100, date1); AbstractFile file2 = new AbstractFile("Test2", 100, date1); newSys.AddFile(file1); newSys.AddFile(file2); List <AbstractFile> list = newSys.EndEditing(); StorageAlgorithms algorithm = new StorageAlgorithms(); var pointInfo1 = algorithm.SeparateBackup(list, Type.Full); RestoreSystem newChain = new RestoreSystem(); newChain.AddPoint(pointInfo1); List <FileRestoreCopyInfo> restoredFiles = newChain.ShowRestoreFiles(1); Assert.AreEqual(2, restoredFiles.Count); }
public void FileWriteAndReadTest1() { FileManager manager = new FileManager(); foreach (var item in Directory.GetFiles("D:\\Work\\go", "*.*", SearchOption.AllDirectories)) { FileInfo info = new FileInfo(item); using (var stream = info.OpenRead()) { var path = string.Join('/', info.DirectoryName.Split('\\', '/').Skip(1)); manager.AddFile(info.Name, info.Extension, stream, stream.Length, path); } } }
public void Test4() { FileManager newSys = new FileManager(); DateTime date1 = new DateTime(2019, 7, 20, 18, 30, 25); AbstractFile file1 = new AbstractFile("Test1", 100, date1); AbstractFile file2 = new AbstractFile("Test2", 100, date1); newSys.AddFile(file1); newSys.AddFile(file2); List <AbstractFile> list = newSys.EndEditing(); StorageAlgorithms algorithm = new StorageAlgorithms(); var pointInfo1 = algorithm.SeparateBackup(list, Type.Full); RestoreSystem newChain = new RestoreSystem(); newChain.AddPoint(pointInfo1); List <RestorePoint> restoredFiles = newChain.ShowRestorePoints(); Assert.AreEqual(200, restoredFiles[0].BackupSize); }
public void ApproveFile() { var fileKey = _packet.Args[0].ToString(); var destPath = _packet.Args[1].ToString(); var password = _packet.Args[2].ToString(); FileManager.AddFile(password, destPath, fileKey); var approved = new { fileApproved = true, message = "File added to whitelist" }; _serializator.Serialize(_client, _packet.Endpoint, _packet.SyncKey, approved); }
public void ApproveFile() { var fileKey = _packet.Args[0].ToString(); var destPath = _packet.Args[1].ToString(); var password = _packet.Args[2].ToString().ToSecureString(); FileManager.AddFile(password, destPath, fileKey); var approved = new { fileApproved = true, message = "File added to whitelist" }; _builder.WriteMessage(approved); }
public async Task ConvertAsNeededAsyncTest() { foreach (var fileName in AllTestFiles.Select(file => file.Name)) { FileManager.AddFile(fileName); } await FileManager.ConvertAsNeededAsync(); var filesUnconverted = FileManager.AllFiles .Except(FileManager.TxtFiles) .Except(FileManager.TaggedFiles) .Where(file => FileManager.TxtFiles.All(tf => tf.NameSansExt != file.NameSansExt)); Check.That(filesUnconverted).IsEmpty(); }
public int UploadFile() { //int documentFileId = 155; //FileID for dental-mirror.PNG int documentFileId = 155; var f = new FileInfo(); var fc = new FileManager(); if (FileUploadControl.HasFile) { var fo = FolderManager.Instance.GetFolder(PortalId, "Documents/"); documentFileId = fc.AddFile(fo, FileUploadControl.PostedFile.FileName, FileUploadControl.PostedFile.InputStream, false, true, FileUploadControl.PostedFile.ContentType).FileId; } return(documentFileId); }
public ActionResult AddWork(HttpPostedFileBase uploadFile, WorkOnTask workOnTask) { if (ModelState.IsValid) { if (uploadFile == null) { ModelState.AddModelError("", "Выберите файл"); return(PartialView("_AddWork", workOnTask)); } workOnTask.UserId = int.Parse(User.Identity.Name); string path = Server.MapPath("~/Content/Assets/Tasks/" + workOnTask.TaskId); string result = fileManager.AddFile(uploadFile, path, workOnTask); var task = unitOfWork.Tasks.GetTaskByIdWithJoin(workOnTask.TaskId, false, false, true, true); unitOfWork.Dispose(); unitOfWork = new UnitOfWork(); if (result == null) { if (task == null) { ModelState.AddModelError("", "Задача не найдена"); return(PartialView("_AddWork", workOnTask)); } workOnTask.File = workOnTask.TaskId + "/" + Path.GetFileName(uploadFile.FileName); unitOfWork.WorkOnTask.AddNewItem(workOnTask); task.Status = "В проверке"; unitOfWork.Tasks.UpdateItem(task); unitOfWork.Save(); MailTools mail = new MailTools(); mail.SendMailToUser(task.Users.Email, "Исполнитель загрузил решение", $"<p>Исполнитель загрузил решение. Проверьте, верное ли оно.</p>"); } else { ModelState.AddModelError("", result); return(PartialView("_AddWork", workOnTask)); } return(RedirectToLocal($"~/Tasks/TaskDetails/{workOnTask.TaskId}")); } return(PartialView("_AddWork", workOnTask)); }
/// <summary> /// Asynchronously adds a new document by the specified file path. /// </summary> /// <param name="docPath">The file path specifying where to find the document.</param> /// <returns>A System.Threading.Tasks.Task representing the ongoing asynchronous operation.</returns> private async Task DisplayAddNewDocumentDialogImplementation(string docPath) { var chosenFile = FileManager.AddFile(docPath); try { await FileManager.ConvertAsNeededAsync(); } catch (FileConversionFailureException e) { this.ShowMessage($".doc file conversion failed\n{e.Message}"); } var textfile = FileManager.TxtFiles.Where(f => f.NameSansExt == chosenFile.NameSansExt).First(); await LoadTextandTabAsync(textfile); CheckIfAddingAllowed(); startProcessingButton.IsEnabled = true; StartProcessMenuItem.IsEnabled = true; }
public void AddFilesTest() { int fileCount = 0; // Add default file and get file count FileManager.AddFile("Test add file", "test", "test", 1000, DateTime.Now, DateTime.Now); List <TrackedFile> fileList = FileManager.GetFiles(); fileCount = fileList.Count; // Add file without memo FileManager.AddFile("Test add file without memo", "test", "test", 1000, DateTime.Now, DateTime.Now); // Verify the file was added fileList = FileManager.GetFiles(); Assert.AreEqual(fileCount + 1, fileList.Count); //Add file with memo FileManager.AddFile("Test add file with memo", "test", "test", 1000, DateTime.Now, DateTime.Now, "Description for added file"); fileList = FileManager.GetFiles(); Assert.AreEqual(fileCount + 2, fileList.Count); }
private async Task InitializeFileManager() { var initPath = Path.Combine(LocationTextBox.Text, ProjectNameTextBox.Text); var availablePath = initPath; for (var i = 0; i < int.MaxValue; ++i) { if (Directory.Exists(availablePath)) { availablePath = initPath + i; } else { break; } } FileManager.Initialize(availablePath); foreach (var file in DocumentsAddedListBox.Items) { try { FileManager.AddFile((file as ListViewItem).Tag.ToString()); } catch (FileNotFoundException e) { this.ShowMessage(e.Message); } } try { await FileManager.ConvertAsNeededAsync(); } catch (FileConversionFailureException e) { this.ShowMessage($".doc file conversion failed\n{e.Message}"); } }
public void GetFileTest() { // Add a test file so at least one trakced file exists FileManager.AddFile("Test File", "test", "test", 1000, DateTime.Now, DateTime.Now); // Get all files List <TrackedFile> trackedFiles = FileManager.GetFiles(); // Verify there is at least one file Assert.IsNotNull(trackedFiles); // Store some data for one of the files int fileId = trackedFiles[0].FileID; string fileName = trackedFiles[0].Filename; string fileMemo = trackedFiles[0].FileMemo; // Get a file by the file id TrackedFile file = FileManager.GetFile(fileId); // Verify the expected file was returned Assert.IsNotNull(file); Assert.AreEqual(fileName, file.Filename); Assert.AreEqual(fileMemo, file.FileMemo); }
public async Task <IActionResult> UploadFile([FromRoute] string screeningId, [FromForm] IFormFile file) { if (string.IsNullOrEmpty(screeningId)) { _logger.LogWarning("Cannot upload file without a screeningId"); return(BadRequest()); } try { bool documentLibraryExists = await _sharePointFileManager.DocumentLibraryExists(ScreeningDocumentListTitle); if (!documentLibraryExists) { await _sharePointFileManager.CreateDocumentLibrary(ScreeningDocumentListTitle, ScreeningDocumentUrlTitle); _logger.LogInformation("Successfully created document library {ScreeningDocumentListTitle} on SharePoint", ScreeningDocumentListTitle); } else { _logger.LogInformation("Successfully retrieved document library {ScreeningDocumentListTitle} on SharePoint", ScreeningDocumentListTitle); } // update screening modification time to current time await UpdateScreeningModifiedOnDate(screeningId); _logger.LogInformation("Successfully updated last modification date for screening {ScreeningId}", screeningId); // retrieve folder name var screening = await _dynamicsClient.GetScreeningById(Guid.Parse(screeningId)); string folderName = GetScreeningFolderName(screening); _logger.LogInformation("Successfully retrieved SharePoint folder name {FolderName} for screening {ScreeningId}", folderName, screeningId); // format file name string fileName = SanitizeFileName(file.FileName); fileName = FileUtility.CombineNameDocumentType(fileName, "WebUpload"); // upload to SharePoint await _sharePointFileManager.AddFile(ScreeningDocumentUrlTitle, folderName, fileName, file.OpenReadStream(), file.ContentType); _logger.LogInformation("Successfully uploaded file {FileName} to folder {FolderName} on SharePoint", fileName, folderName); return(new JsonResult(fileName)); } catch (SharePointRestException ex) { _logger.LogError(ex, string.Join(Environment.NewLine, "Failed to upload file {FileName} for screening {ScreeningId}", "Request: {@Request}", "Response: {@Response}"), file.Name, screeningId, ex.Request, ex.Response); return(StatusCode(StatusCodes.Status500InternalServerError)); } catch (OdataerrorException ex) { _logger.LogError(ex, string.Join(Environment.NewLine, "Failed to upload file {FileName} for screening {ScreeningId}", "{@ErrorBody}"), file.Name, screeningId, ex.Body); return(StatusCode(StatusCodes.Status500InternalServerError)); } catch (Exception ex) { _logger.LogError(ex, "Failed to upload file {FileName} for screening {ScreeningId}", file.Name, screeningId); return(StatusCode(StatusCodes.Status500InternalServerError)); } }
void Save() { try { bool isProcessSuccessed = false; if (_fileId == -1) { if (isFileGet) { personFile.CreatedBy = AppVariables.UserId; personFile.CreationDate = DateTime.Now; personFile.IsActive = true; isProcessSuccessed = fileMan.AddFile(personFile); if (isProcessSuccessed) { if (SaveEvent != null) { SaveEvent(new FileModel() { Id = personFile.Id, FileName = personFile.FileName, CreationDate = personFile.CreationDate, CreatedUser = AppVariables.UserName, CreatedBy = AppVariables.UserId }, true); } MessageBox.Show("Dosya Ekleme tamamlandı."); btnSave.Enabled = false; btnCancel.Text = "Kapat"; return; } else { MessageBox.Show("Dosya Ekleme tamamlanamadı."); return; } } else { MessageBox.Show("Lütfen Dosya Seçin."); return; } } else { if (isFileGet) { isProcessSuccessed = fileMan.UpdateFile(personFile); if (isProcessSuccessed) { if (SaveEvent != null) { SaveEvent(new FileModel() { Id = personFile.Id, FileName = personFile.FileName, CreationDate = personFile.CreationDate, CreatedUser = AppVariables.UserName, CreatedBy = AppVariables.UserId }, false); } MessageBox.Show("Dosya Güncelleme tamamlandı."); btnSave.Enabled = false; btnCancel.Text = "Kapat"; return; } else { MessageBox.Show("Dosya Güncelleme tamamlanamadı."); return; } } else { MessageBox.Show("Güncelleme tamamlandı."); return; } } } catch (Exception ex) { LogManager.LogException(ex, AppVariables.UserId, "FrmFile", "Save"); } }