public async Task ShouldCreateFile(string name, string contentType, byte[] content) { // Arrange var fileMock = new Mock <IFile>(); fileMock.SetupGet(x => x.Name).Returns(name); fileMock.SetupGet(x => x.ContentType).Returns(contentType); fileMock.Setup(x => x.OpenReadStream()).Returns(() => new MemoryStream(content)); var request = new UploadFileCommand() { File = fileMock.Object }; // Act await LoginAsDefaultUserAsync(); Guid fileId = await SendAsync(request); File file = await FindAsync <File>(x => x.Id == fileId); // Assert file.Should().NotBeNull(); file.Id.Should().Be(fileId); file.Name.Should().Be(name); file.ContentType.Should().Be(contentType); file.Content.Should().Equal(content); }
public void Test1() { ShowdirCommand commandOne = new ShowdirCommand(); ShowdiskCommand commandTwo = new ShowdiskCommand(); DirectoryCommand commandThree = new DirectoryCommand(); StartAppCommand commandFour = new StartAppCommand(); DeleteFileCommand commandFive = new DeleteFileCommand(); UploadFileCommand commandSix = new UploadFileCommand(); ChangeDirCommand commandSeven = new ChangeDirCommand(); DownloadFileCommand commandEight = new DownloadFileCommand(); List <ICommand> container = new List <ICommand>(); container.Add(commandOne); container.Add(commandTwo); container.Add(commandThree); container.Add(commandFour); container.Add(commandFive); container.Add(commandSix); container.Add(commandSeven); container.Add(commandEight); foreach (var value in container) { bool finders = false; foreach (var value2 in _macroCommand._commands) { if (value2.GetType() == value.GetType()) { finders = true; } } Assert.True(finders); } }
public void Visit(UploadFileCommand command) { Visit((ICommand)command); if (Root.TryFindNode(command.DirectoryId, out var parent) && parent is Directory parentDirectory) { var existingFile = parentDirectory.Children.FirstOrDefault(c => c.Name == command.Name); if (existingFile == null) { var file = _factory.CreateFile(command.Name, command.Data.Length); parentDirectory.Children.Add(file); _timestamp.Increment(); Message = $"ID={file.Id}"; } else { OnNodeAlreadyExists(command.Name, command.DirectoryId); } } else { OnDirectoryDoesNotExist(command.DirectoryId); } }
public async Task Handle_AllConditionsMet_Success() { // Arrange var content = new MemoryStream(); var reader = new Mock <IFileReader>(); var writer = new Mock <IFileWriter>(); var command = new UploadFileCommand { SourceFileName = "File", Content = content }; _fileStorage .Setup(x => x.CreateFile(It.IsAny <string>())) .Returns(writer.Object); // Act var response = await _handler.Handle(command, CancellationToken.None); // Assert Assert.That(response.TargetFileName, Is.Not.Null); _fileStorage.Verify(x => x.CreateFile(It.IsAny <string>()), Times.Once); _eventService.Verify(x => x.PublishAsync <TemporaryFileUploadedEvent>(It.IsAny <TemporaryFileUploadedEvent>()), Times.Once); writer.Verify(x => x.WriteAsync(It.IsAny <Stream>()), Times.Once); }
public ActionResult Upload(Guid uploadKey, HttpPostedFileBase fileData) { var command = new UploadFileCommand(uploadKey, fileData, ControllerContext.HttpContext.User.Identity.Name); var results = _commandProcessor.Process(command); return(Json(new { Status = results.Success ? "OK" : "Error" })); }
public async Task <IActionResult> Upload(IFormFile file) { var command = new UploadFileCommand { File = file }; return(Ok(await _mediator.Send(command))); }
public async Task ShouldThrowErrorForInvalidInput(string fileName, string mimeType) { var command = new UploadFileCommand { Name = fileName, MimeType = mimeType }; await Assert.ThrowsAsync <ValidationException>(() => SendAsync(command)); }
public async Task <IActionResult> Post() { var form = await Request.ReadFormAsync(); var file = form.Files.First(); var result = await UploadFileCommand.ExecuteAsync(new UploadTeabagImageCommand(file.OpenReadStream(), file.FileName)); return(Translator.Translate(result)); }
public async Task <IActionResult> Upload([FromForm] UploadFileCommand request) { var form = Request.Form; request.Title = form["title"]; request.CategoryId = form["categoryId"]; request.Files = form.Files.ToList(); return(Ok(await _fileService.Upload(request))); }
public async Task <IActionResult> UploadFile([FromForm] UploadFileCommand command) { command.UserId = _accountService.UserId; command.File = new MemoryStream(); await Request.Form.Files[0].CopyToAsync(command.File); await _mediator.Send(command); return(Ok()); }
public async Task <IActionResult> Post(IFormFile file) { var command = new UploadFileCommand() { File = file, UserId = User.Identity.UserId() }; var fileId = await mediator.Send(command); return(Ok(fileId)); }
public async Task <IActionResult> UploadFileAsync() { var file = HttpContext.Request.Form.Files[0]; var command = new UploadFileCommand() { File = file }; UploadFileCommandValidator.FileIsValid(file); var result = await _mediator.Send(command); return(Ok(result)); }
public async void ContinueFileOpenPicker(IReadOnlyList <StorageFile> files) { try { if (files != null && files.Count > 0) { SelectedFile = files[0]; } else { SelectedFile = null; SelectedFileImage = null; return; } try { var properties = await SelectedFile.GetBasicPropertiesAsync(); SelectedFileName = SelectedFile.DisplayName; SelectedFileSize = FileSize.FromBytes(properties.Size); SelectedFileType = SelectedFile.DisplayType; } catch (Exception) { SelectedFile = null; SelectedFileImage = null; return; } try { var img = await SelectedFile.GetThumbnailAsync(ThumbnailMode.SingleItem, 256); SelectedFileImage = new BitmapImage(); await SelectedFileImage.SetSourceAsync(img); } catch (Exception) { SelectedFileImage = null; } } finally { UploadFileCommand.RaiseCanExecuteChanged(); _appLoaderService.Hide(); } }
public async Task <ActionResult> UploadDoument() { if (Request.Form.Files.Count == 0) { throw new CustomException(System.Net.HttpStatusCode.NotAcceptable, "Please choose a file"); } // take first file as it is supported for single file upload for now, we can extend this for next release var formFile = Request.Form.Files[0]; // validate if the file is pdf if (formFile.ContentType != FileTypeAllowed) { throw new CustomException(System.Net.HttpStatusCode.NotAcceptable, "Invalid file type. Please choose only pdf"); } // validate if the file size is not more than max file size in mb given in appSettings var sizeInMb = formFile.Length / 1024 / 1024; var maxSize = appSettings.UploadMaxFileSizeInMb > 0 ? appSettings.UploadMaxFileSizeInMb : 5; // default to size 5MB if (sizeInMb > maxSize) { throw new CustomException(System.Net.HttpStatusCode.RequestEntityTooLarge, $"File size must not exceed {maxSize}MB"); } // upload file var newFileRequest = new UploadFileCommand(); using (var memoryStream = new MemoryStream()) { formFile.CopyTo(memoryStream); newFileRequest.File = memoryStream.ToArray(); } newFileRequest.Name = formFile.FileName; newFileRequest.MimeType = FileTypeAllowed; var documentUri = await Mediator.Send(newFileRequest); // add file to document var newDocumentRequest = new AddNewDocumentCommand { Name = string.IsNullOrEmpty(formFile.Name) ? formFile.FileName : formFile.Name, Location = documentUri, Size = formFile.Length }; await Mediator.Send(newDocumentRequest); return(Ok()); }
public ActionResult Upload(int fileModule) { try { if (Request.Files != null && Request.Files.Count > 0) { var uploadFile = Request.Files[0]; if (uploadFile != null && uploadFile.ContentLength > 0) { var file = new File { Name = System.IO.Path.GetFileName(uploadFile.FileName), Type = System.IO.Path.GetExtension(uploadFile.FileName), }; using (var reader = new System.IO.BinaryReader(uploadFile.InputStream)) { file.Data = reader.ReadBytes(uploadFile.ContentLength); } var command = new UploadFileCommand { File = file }; var uploadFileResult = mediator.Send(command); if (uploadFileResult == "Success") { return(Json(new { Error = 0, Name = file.Name, FileId = file.Id })); } else { return(Json(new { Error = -40001, Message = uploadFileResult })); } } } return(Json(new { Error = -40001, Message = "Nullable file upload error" })); } catch (Exception ex) { return(Json(new { Error = -40002, Message = ex.Message })); } }
public async Task ShouldUploadFile() { const string data = "R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw=="; byte[] bytes = Convert.FromBase64String(data); var command = new UploadFileCommand { Name = "hello.pdf", MimeType = "application/pdf", File = bytes }; var location = await SendAsync(command); var result = await SendAsync(new DownloadFileCommand { Location = location }); Assert.NotNull(result); Assert.Equal(bytes, result.File); }
public async Task <Response> Upload(UploadFileCommand request) { var category = await _context.Categories.FirstOrDefaultAsync(x => x.Id == request.CategoryId); var directory = GetUploadDirectory(category.Title, request.Title); var uploadPath = Path.Combine(_server, directory); var archive = new Archive(); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } foreach (var file in request.Files) { await using var fileStream = new FileStream(Path.Combine(uploadPath, file.FileName), FileMode.Create, FileAccess.Write); file.CopyTo(fileStream); fileStream.Flush(); } archive.Id = Guid.NewGuid().ToString(); archive.CreatedAt = DateTime.Now; archive.Category = category; archive.Name = request.Title; archive.Description = request.Description; archive.Path = directory; await _context.Archives.AddAsync(archive); await _context.SaveChangesAsync(); return(new Response() { Status = true, Message = "" }); }
public void Visit(UploadFileCommand command) { if (!TryGetPrefixedPathTo(command.DirectoryId, out var directoryPath)) { return; } Directory.CreateDirectory(directoryPath); var path = Path.Combine(directoryPath, command.Name); if (!File.Exists(path)) { using var file = File.Create(path); file.Write(command.Data); } else { File.WriteAllBytes(path, command.Data); } }
public async Task <IActionResult> UploadFilesForRequest(string projectName, Guid?projectId, string changeRequestName, Guid entityId, IFormFile file) { await Mediator.Send(new RefreshCurrentUserTokenCommand { ExternalProvider = ExternalProviders.OneDrive }); if (file.Length <= 60 * 1024 * 1024) { var command = new UploadFileCommand(); command.ExternalProvider = ExternalProviders.OneDrive; command.Filepath = "drive/special/approot:/PM/" + "Projects/" + projectName + projectId.Value + "/" + "Requests/" + (changeRequestName?.ReplaceSpecialCharacters('_') ?? string.Empty) + entityId; command.FormFile = file; if (await Mediator.Send(command) != null) { return(Ok()); } } return(BadRequest()); }
public async Task <IActionResult> AvatarUpload(Guid userId, IFormFile file) { string[] allowedAvatarExtensions = { ".png", ".jpg", ".jpeg" }; if (file != null && allowedAvatarExtensions.Contains(Path.GetExtension(file.FileName).ToLower()) == false) { throw new ValidationException($"These formats are only allowed: {string.Join(", ", allowedAvatarExtensions)}"); } var uploadFileCommand = new UploadFileCommand { File = file }; var result = await _mediator.Send(uploadFileCommand); var changeAvatarCommand = new ChangeAvatarCommand { UserAccountDataId = userId, AvatarPath = result.PathToFile }; await _mediator.Send(changeAvatarCommand); return(Ok(result)); }
public override void RaiseCommandCanExecuteChanged() { UploadFileCommand.RaiseCanExecuteChanged(); DownloadFileCommand.RaiseCanExecuteChanged(); DeleteFileCommand.RaiseCanExecuteChanged(); }
public void Setup() { UploadFileCommand uploadFileCommand = new UploadFileCommand(); _uploadFileCommand = uploadFileCommand; }
private void SynchronizeLocalFiles() { //Synchronize file sync table items of type file vs on disk files var files = SyncTableManager.GetFiles(); foreach (var file in files) { if (File.Exists(file.Path)) { var fileInfo = new FileInfo(file.Path); if (!fileInfo.IsLocked()) { //if on disk file is more new that file table item then... upload if (fileInfo.LastWriteTime.ToFileTime() > file.LastWriteTime) { SyncTableManager.ChangeSyncStatusToPending(file.Path); var command = new UploadFileCommand(_ticket, file.GroupId, file.FolderId, file.FileId, fileInfo, _path); command.ExecuteError += new ExecuteErrorEventHandler(OnExecuteError); _commandProcessor.AddCommand(command); } } } else { SyncTableManager.ChangeSyncStatusToPending(file.Path); //Delete file from file sync table and dokuflex var command = new DeleteOnlineFileCommand(_ticket, file); command.ExecuteError += new ExecuteErrorEventHandler(OnExecuteError); _commandProcessor.AddCommand(command); } } //Synchronize on disk files vs file sync table items of type file var filePaths = Directory.EnumerateFiles(_path, "*", SearchOption.AllDirectories); foreach (var filePath in filePaths) { if (filePath.Contains("~")) { continue; } if (filePath.Contains("Thumbs.")) { continue; } //Detect new files and upload if (!files.Any(f => f.Path.Equals(filePath))) { var fileInfo = new FileInfo(filePath); if (fileInfo.Length == 0) { continue; } if (fileInfo.IsLocked()) { continue; } var parentDirectory = Directory.GetParent(filePath); var parentFolder = SyncTableManager.GetByPath(parentDirectory.FullName); if (parentFolder != null) { // Add item as pending var item = new SyncTableItem { Name = fileInfo.Name, Path = fileInfo.FullName, LastWriteTime = 0, Type = "C", GroupId = parentFolder.GroupId, FolderId = parentFolder.FolderId, FileId = string.Empty, ModifiedTime = 0, SyncFolder = false, SyncStatus = SyncTableItemStatus.Pending }; SyncTableManager.Add(item); var command = new UploadFileCommand(_ticket, parentFolder.GroupId, parentFolder.FolderId, String.Empty, fileInfo, _path); command.ExecuteError += new ExecuteErrorEventHandler(OnExecuteError); _commandProcessor.AddCommand(command); } } } }
public UploadFileCommand Map(UploadFileRequest request) { var result = new UploadFileCommand(request.File, request.FileExtension); return(result); }