Exemplo n.º 1
0
        public async Task <ICommandResult <List <int> > > HandleAsync(FileUploadCommand command)
        {
            List <tvz2api_cqrs.Models.File> newFiles = new List <tvz2api_cqrs.Models.File>();

            foreach (var file in command.Files)
            {
                using (var ms = new MemoryStream())
                {
                    file.CopyTo(ms);
                    var fileBytes = ms.ToArray();

                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    fileName = fileName.Substring(0, fileName.LastIndexOf(".")) + fileName.Substring(fileName.LastIndexOf(".")).ToLower();

                    newFiles.Add(new tvz2api_cqrs.Models.File
                    {
                        Name        = Path.GetFileName(fileName),
                        ContentType = file.ContentType,
                        Data        = fileBytes,
                        Size        = fileBytes.Length
                    });
                }
            }

            await _context.File.AddRangeAsync(newFiles);

            await _context.SaveChangesAsync();

            return(CommandResult <List <int> > .Success(new List <int>(newFiles.Select(x => x.Id))));
        }
Exemplo n.º 2
0
        public async Task UploadAsync(Stream stream, FileUploadCommand command, string fileName)
        {
            var fileIdent = Guid.NewGuid().ToString();
            var filePath  = Path.Combine(FilesPath, fileIdent);

            //Ensure that stream is at begining
            stream.Position = 0;

            using (var fs = System.IO.File.Create(filePath))
            {
                await stream.CopyToAsync(fs);

                //Ensure data is flushed
                await fs.FlushAsync();
            }

            var file = new Db.Models.File()
            {
                Author    = command.Author,
                CreatedAt = command.CreatedAt,
                ExpiredAt = command.ExpiredAt,
                FileState = FileState.Created,
                Filepath  = filePath,
                Filename  = fileName,
                FileType  = command.FileType,
                Name      = command.Name
            };

            _context.Files.Add(file);

            await _context.SaveChangesAsync();
        }
Exemplo n.º 3
0
        public void AddFileUpload(FileUploadCommand model, FileTransferCompletionStatus status)
        {
            string message = "";

            if (status == FileTransferCompletionStatus.Successful)
            {
                message = string.Format("Successfully uploaded file '{0}' to user {1}", model.FileName, model.DestinationUserName);
            }
            else if (status == FileTransferCompletionStatus.Error)
            {
                message = string.Format("An error occurred uploading file '{0}' to user {1}", model.FileName, model.DestinationUserName);
            }
            else if (status == FileTransferCompletionStatus.Cancelled)
            {
                message = string.Format("Upload of file '{0}' to user {1} was cancelled", model.FileName, model.DestinationUserName);
            }
            else
            {
                return;
            }

            var pnl = AddSectionPanel(40);

            pnlMessages.ScrollControlIntoView(pnl);
            _prevControl = pnl;

            Label lbl = new Label();

            lbl.Text = message;
            pnl.Controls.Add(lbl);
            lbl.AutoSize = true;
            lbl.Location = new Point(5, 5);
        }
Exemplo n.º 4
0
        public void GivenNullMediaDto_ThenThrowsArgumentNullException()
        {
            var givenFormFile = FormFileFactory.Create("filename1234", "file content");

            Action act = () => FileUploadCommand.Create(givenFormFile, null, SampleAuthorId);

            act.Should().Throw <ArgumentNullException>();
        }
Exemplo n.º 5
0
        public void GivenNullFormFile_ThenThrowsArgumentNullException()
        {
            var givenTags     = new[] { "pigeons", "flying rats" };
            var givenMediaDto = new FileUploadDto(givenTags, SampleUploadDate, false);

            Action act = () => FileUploadCommand.Create(null, givenMediaDto, SampleAuthorId);

            act.Should().Throw <ArgumentNullException>();
        }
Exemplo n.º 6
0
        public async Task <IActionResult> UploadNewFile([FromForm] FileUploadFormData fileUploadFormData)
        {
            var mediaDto          = JsonConvert.DeserializeObject <FileUploadDto>(fileUploadFormData.Media);
            var user              = User.GetUserId();
            var fileUploadCommand = FileUploadCommand.Create(fileUploadFormData.File, mediaDto, user);
            await _mediator.Send(fileUploadCommand);

            return(StatusCode(201));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Upload([FromForm] FileUploadCommand command, IFormFile file)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrorsArray()));
            }

            await _fileService.UploadAsync(file.OpenReadStream(), command, file.FileName);

            return(Ok());
        }
Exemplo n.º 8
0
        private void NotifyFileUploadStatus(FileUploadCommand model, FileTransferCompletionStatus status)
        {
            var messageCtrl = GetMessageHistoryCtrlForUser(model.DestinationUserName);

            if (messageCtrl == null)
            {
                return;
            }

            messageCtrl.AddFileUpload(model, status);
        }
Exemplo n.º 9
0
        public void GivenMediaChangeIsSavedInDatabase_MediaChangeIsOfTypeCreate()
        {
            var givenFormFile = FormFileFactory.Create("newFile", string.Empty);
            var givenTags     = new[] { "pigeons", "flying rats" };
            var givenMediaDto = new FileUploadDto(givenTags, _givenDate, false);
            var givenUserId   = "user";

            var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, givenUserId);
            var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock,
                                                       _mediaIdProviderMock.Object, _timeProviderMock.Object);

            handler.Handle(command, CancellationToken.None).Wait();

            _contextMock.MediaChanges.Should().ContainSingle(mc => mc.Type == MediaChangeType.Create);
        }
Exemplo n.º 10
0
        private async Task ExecuteConsoleCommandFileUpload(Options options)
        {
            var fileUploadCommand = new FileUploadCommand(options);
            var storageFile       = await _mediator.Send(fileUploadCommand);

            FileUploadViewModel uploadViewModel = new FileUploadViewModel
            {
                FilePath  = fileUploadCommand.FilePath,
                FileName  = Path.GetFileName(fileUploadCommand.FilePath),
                FileSize  = ConvertingHelper.GetSizeString(storageFile.Size),
                Extension = storageFile.Extension
            };

            LogInformationMessage($"File \"{fileUploadCommand.FilePath}\" has been uploaded");
            _consolePrinter.PrintFileUploadedSuccessful(uploadViewModel);
        }
Exemplo n.º 11
0
        public void GivenMediaWithEmptyTagCollection_MediaIsCreatedWithoutTags()
        {
            var givenFileName    = "newFile";
            var givenFileContent = "None";
            var givenFormFile    = FormFileFactory.Create(givenFileName, givenFileContent);
            var givenTags        = new string[] {};
            var givenMediaDto    = new FileUploadDto(givenTags, _givenDate, false);

            var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty);
            var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock,
                                                       _mediaIdProviderMock.Object, _timeProviderMock.Object);

            handler.Handle(command, CancellationToken.None).Wait();

            _contextMock.MediaInstances.Find(_givenMediaInstanceId).MediaTags.Should().BeEmpty();
        }
Exemplo n.º 12
0
        public void GivenNewMediaIsUploadedSuccessfully_MediaIsCreatedInDatabase()
        {
            var givenFileName    = "newFile";
            var givenFileContent = "None";
            var givenFormFile    = FormFileFactory.Create(givenFileName, givenFileContent);
            var givenTags        = new[] { "pigeons", "flying rats" };
            var givenMediaDto    = new FileUploadDto(givenTags, _givenDate, false);

            var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty);
            var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock,
                                                       _mediaIdProviderMock.Object, _timeProviderMock.Object);

            handler.Handle(command, CancellationToken.None).Wait();

            _contextMock.MediaInstances.Find(_givenMediaInstanceId).Should().NotBeNull();
        }
Exemplo n.º 13
0
        public void GivenMediaWithSingleDotAtFileNameEnd_DataTypeIsEmptyString()
        {
            var givenFileName    = "newFile.";
            var givenFileContent = "None";
            var givenFormFile    = FormFileFactory.Create(givenFileName, givenFileContent);
            var givenTags        = new[] { "pigeons", "flying rats" };
            var givenMediaDto    = new FileUploadDto(givenTags, _givenDate, false);

            var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty);
            var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock,
                                                       _mediaIdProviderMock.Object, _timeProviderMock.Object);

            handler.Handle(command, CancellationToken.None).Wait();

            _contextMock.MediaInstances.Find(_givenMediaInstanceId).DataType.Should().BeEmpty();
        }
Exemplo n.º 14
0
        public void GivenMediaWithNewTag_NewTagIsCreatedInDatabase()
        {
            var givenFileName    = "newFile";
            var givenFileContent = "None";
            var formFile         = FormFileFactory.Create(givenFileName, givenFileContent);
            var givenTag         = "pigeons";
            var givenTags        = new[] { givenTag };
            var givenMediaDto    = new FileUploadDto(givenTags, _givenDate, false);

            var command = FileUploadCommand.Create(formFile, givenMediaDto, string.Empty);
            var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock,
                                                       _mediaIdProviderMock.Object, _timeProviderMock.Object);

            handler.Handle(command, CancellationToken.None).Wait();

            _contextMock.Tags.Should().ContainSingle(t => t.Name == givenTag);
        }
Exemplo n.º 15
0
        public void GivenMediaWithValidExtension_DataTypeIsEqualToFileExtension()
        {
            var givenFileName    = "newFile";
            var givenExtension   = "png";
            var givenFileContent = "None";
            var givenFormFile    = FormFileFactory.Create(givenFileName + "." + givenExtension, givenFileContent);
            var givenTags        = new[] { "pigeons", "flying rats" };
            var givenMediaDto    = new FileUploadDto(givenTags, _givenDate, false);

            var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty);
            var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock,
                                                       _mediaIdProviderMock.Object, _timeProviderMock.Object);

            handler.Handle(command, CancellationToken.None).Wait();

            _contextMock.MediaInstances.Find(_givenMediaInstanceId).DataType.Should().BeEquivalentTo(givenExtension);
        }
Exemplo n.º 16
0
        public void GivenThatFileWithGivenIdAlreadyExists_MediaIsCreatedWithDifferentId()
        {
            var givenFileName    = "newFile";
            var givenFileContent = "None";
            var givenFormFile    = FormFileFactory.Create(givenFileName, givenFileContent);
            var givenTags        = new [] { "pigeons", "flying rats" };
            var givenMediaDto    = new FileUploadDto(givenTags, _givenDate, false);

            _fileStorageMock.CreateNew(_givenMediaInstanceId);

            var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty);
            var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock,
                                                       _mediaIdProviderMock.Object, _timeProviderMock.Object);

            handler.Handle(command, CancellationToken.None).Wait();

            var streamContent = GetFileContent(_fileStorageMock.Read(_givenAlternativeMediaInstanceId));

            streamContent.Should().BeEquivalentTo(givenFileContent);
        }
        public async Task UploadFilePart(FileUploadCommand uploadCommand, byte[] data, int filePartIndex)
        {
            try
            {
                if (string.IsNullOrEmpty(_accessToken))
                {
                    throw new Exception("Not logged in");
                }

                var fileName = Path.GetFileName(uploadCommand.FileName);
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
                    {
                        content.Add(new StreamContent(new MemoryStream(data)), uploadCommand.FileId.ToString(), fileName);
                        var url = string.Format("{0}/api/file/upload/{1}/{2}", _configuration.ServerBaseUrl, uploadCommand.FileId, filePartIndex);
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
                        var response = await client.PostAsync(url, content);

                        if (!response.IsSuccessStatusCode)
                        {
                            throw new WebAPIException("An error occurred uploading file", response.ReasonPhrase, response.StatusCode);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is WebAPIException)
                {
                    throw;
                }
                throw new Exception("An error occurred uploading file. " + ex.Message);
            }
        }