Exemplo n.º 1
0
            protected override async Task PerformOperation(Domain.Models.File file)
            {
                var isAdmin = await _identityResolver.IsAdminAsync();

                var userId             = _user.GetId();
                var isNotAlreadyLocked = (userId != file.LockedById);

                if (isNotAlreadyLocked)
                {
                    file.Lock(userId, isAdmin);
                }

                try
                {
                    file.Name = _request.Name;
                    file.Save(userId, isAdmin);
                }
                finally
                {
                    if (isNotAlreadyLocked)
                    {
                        file.Unlock(userId);
                    }
                }
            }
Exemplo n.º 2
0
        private async Task <FileUpdateResult> UpdateFile(Domain.Models.File dbFile, Domain.Models.File file)
        {
            var result = new FileUpdateResult();

            result.LockResult = await _lockService.GetFileLock(dbFile.Id).LockAsync(0);

            // Don't need to update or throw error if contents haven't changed
            if (!dbFile.Content.Equals(file.Content))
            {
                if (!result.LockResult.AcquiredLock)
                {
                    result.UnableToLock = true;
                    result.FileUpdated  = false;
                }
                else if (dbFile.CanLock(_userId, _isAdmin))
                {
                    dbFile.Content = file.Content;
                    dbFile.Save(
                        _userId,
                        _isAdmin,
                        bypassLock: true);

                    result.FileUpdated  = true;
                    result.UnableToLock = false;
                }
                else
                {
                    result.FileUpdated  = false;
                    result.UnableToLock = true;
                }
            }

            return(result);
        }
Exemplo n.º 3
0
            protected override async Task PerformOperation(Domain.Models.File file)
            {
                await ValidateEntities(file, _request.DirectoryId, _request.WorkspaceId);

                file = _mapper.Map(_request, file);
                file.Save(_user.GetId(), isAdmin: (await _identityResolver.IsAdminAsync()));
            }
Exemplo n.º 4
0
        public async Task <CommandResult> Handle(UploadFileCommand request, CancellationToken cancellationToken)
        {
            var user = await _context.Users.FirstOrDefaultAsync(u => u.Login == request.UserName, cancellationToken);

            if (user == null)
            {
                return(CommandResult.Fail(CommandErrors.UserNotExists));
            }

            var localName  = Guid.NewGuid().ToString();
            var saveResult = await _fileService.SaveFile(request.FileStream, localName, cancellationToken);

            if (!saveResult)
            {
                return(CommandResult.Fail(CommandErrors.FileSave));
            }

            var filename = request.FileName.Split(ExtensionDelimiter);

            var file = new Domain.Models.File
            {
                Name        = filename[0],
                Extension   = filename[1],
                LocalName   = localName,
                ContentType = request.ContentType,
                SizeBytes   = request.SizeBytes,
                UploadDate  = _dateTime.Now,
                UserId      = user.Id
            };

            _context.Files.Add(file);
            await _context.SaveChangesAsync(cancellationToken);

            return(CommandResult.Success);
        }
Exemplo n.º 5
0
            protected override async Task PerformOperation(Domain.Models.File file)
            {
                var isAdmin = await _identityResolver.IsAdminAsync();

                var userId             = _user.GetId();
                var isNotAlreadyLocked = (userId != file.LockedById);

                if (isNotAlreadyLocked)
                {
                    try
                    {
                        file.Lock(userId, isAdmin);
                    }
                    catch (FileConflictException)
                    {
                        throw new FileConflictException("Cannot rename a file while it's being edited or locked by another user.");
                    }
                }

                try
                {
                    file.Name = _request.Name;
                    file.Save(userId, isAdmin);
                }
                finally
                {
                    if (isNotAlreadyLocked)
                    {
                        file.Unlock(userId);
                    }
                }
            }
Exemplo n.º 6
0
        public void Create(FileViewModel command)
        {
            var newfile = new Domain.Models.File(command.Title, command.FileExtention, command.Description, command.FileTypeId);

            _irepository.Create(newfile);
            _irepository.SaveChanges();
        }
Exemplo n.º 7
0
        public async Task GetFileAsync_OneMetaDataRecordFoundForUrnFileExists_ReturnsOriginalFile()
        {
            // Arrange
            int urn = 1234;

            int[]             fallbackUrns      = null;
            FileTypeOption    fileType          = FileTypeOption.Report;
            CancellationToken cancellationToken = CancellationToken.None;

            Uri location = new Uri(
                "https://some-storage-container.azure.example/exists.png",
                UriKind.Absolute);

            FileMetaData fileMetaData = new FileMetaData()
            {
                Location = location,
            };

            IEnumerable <FileMetaData> fileMetaDatas = new FileMetaData[]
            {
                fileMetaData,
            };

            this.mockFileMetaDataAdapter
            .Setup(x => x.GetFileMetaDatasAsync(It.IsAny <int>(), It.IsAny <FileTypeOption>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(fileMetaDatas));

            Random random = new Random();

            byte[] contentBytes = new byte[2048];

            random.NextBytes(contentBytes);

            File expectedFile = new File()
            {
                FileName     = "exists.png",
                ContentType  = "image/png",
                ContentBytes = contentBytes,
            };

            this.mockFileStorageAdapter
            .Setup(x => x.GetFileAsync(It.IsAny <FileMetaData>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(expectedFile));

            File actualFile = null;

            // Act
            actualFile = await this.fileManager.GetFileAsync(
                urn,
                fileType,
                fallbackUrns,
                cancellationToken);

            // Assert
            Assert.AreEqual(actualFile, expectedFile);
        }
        private async Task <IActionResult> GetFileAsync(
            int urn,
            FileTypeOption fileType,
            int[] fallbackUrns,
            CancellationToken cancellationToken)
        {
            IActionResult toReturn = null;

            Domain.Models.File file =
                await this.fileManager.GetFileAsync(
                    urn,
                    fileType,
                    fallbackUrns,
                    cancellationToken)
                .ConfigureAwait(false);

            if (file != null)
            {
                this.loggerProvider.Info(
                    $"The method " +
                    $"{nameof(IFileManager)}.{nameof(IFileManager.GetFileAsync)} " +
                    $"method returned {file} for {nameof(urn)} = \"{urn}\" " +
                    $"and {nameof(fileType)} = \"{fileType}\" - returning " +
                    $"with a {nameof(FileContentResult)}.");

                byte[] contentBytes = file.ContentBytes.ToArray();
                string contentType  = file.ContentType;

                FileContentResult fileContentResult = new FileContentResult(
                    contentBytes,
                    contentType);

                fileContentResult.FileDownloadName = file.FileName;

                toReturn = fileContentResult;
            }
            else
            {
                this.loggerProvider.Warning(
                    $"The method " +
                    $"{nameof(IFileManager)}.{nameof(IFileManager.GetFileAsync)} " +
                    $"method returned null for {nameof(urn)} = \"{urn}\" " +
                    $"and {nameof(fileType)} = \"{fileType}\" - returning " +
                    $"{nameof(NotFoundResult)}.");

                toReturn = new NotFoundResult();
            }

            return(toReturn);
        }
Exemplo n.º 9
0
        private IEnumerable <ZipArchiveEntry> ExtractZipEntries(File file)
        {
            IEnumerable <ZipArchiveEntry> toReturn = null;

            byte[] zipBytes = file.ContentBytes.ToArray();

            using (MemoryStream memoryStream = new MemoryStream(zipBytes))
            {
                using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Read, false))
                {
                    toReturn = zipArchive.Entries.ToArray();
                }
            }

            return(toReturn);
        }
Exemplo n.º 10
0
            protected override async Task PerformOperation(Domain.Models.File file)
            {
                var isAdmin = await _identityResolver.IsAdminAsync();

                var userId = _user.GetId();

                file.Lock(userId, isAdmin);

                try
                {
                    file.Delete(isAdmin);
                }
                finally
                {
                    file.Unlock(userId);
                }
            }
Exemplo n.º 11
0
        public async Task <(Guid id, string name)> SaveFileAsync(IFormFile formFile)
        {
            var name = await _fileSystemService.SaveFile(formFile);

            var file = new File
            {
                Caption = formFile.Name,
                Name    = name
            };

            var repository = UnitOfWork.Repository <File>();
            await repository.AddAsync(file);

            await UnitOfWork.CommitAsync();

            return(file.Id, file.Name);
        }
Exemplo n.º 12
0
            private async Task ValidateEntities(Domain.Models.File file, Guid directoryId, Guid?workspaceId)
            {
                var directory = await _db.Directories.FindAsync(directoryId);

                if (directory == null)
                {
                    throw new EntityNotFoundException <Directory>();
                }

                if (workspaceId.HasValue)
                {
                    var workspace = await _db.Workspaces.FindAsync(workspaceId.Value);

                    if (workspace == null)
                    {
                        throw new EntityNotFoundException <Workspace>();
                    }
                }
            }
Exemplo n.º 13
0
        public async Task GetFileAsync_NoMetaDataFoundForUrnOrFallbackUrns_ReturnsNull()
        {
            // Arrange
            int            urn      = 1234;
            FileTypeOption fileType = FileTypeOption.Report;

            int[]             fallbackUrns      = new int[] { 4567, 890 };
            CancellationToken cancellationToken = CancellationToken.None;

            File file = null;

            // Act
            file = await this.fileManager.GetFileAsync(
                urn,
                fileType,
                fallbackUrns,
                cancellationToken);

            // Assert
            Assert.IsNull(file);
        }
Exemplo n.º 14
0
        public async Task GetFileAsync_OneMetaDataRecordFoundForUrnFileMissing_ReturnsNull()
        {
            // Arrange
            int            urn      = 1234;
            FileTypeOption fileType = FileTypeOption.Report;

            int[]             fallbackUrns      = null;
            CancellationToken cancellationToken = CancellationToken.None;

            Uri location = new Uri(
                "https://some-storage-container.azure.example/doesntexist.pdf",
                UriKind.Absolute);

            FileMetaData fileMetaData = new FileMetaData()
            {
                Location = location,
            };

            IEnumerable <FileMetaData> fileMetaDatas = new FileMetaData[]
            {
                fileMetaData,
            };

            this.mockFileMetaDataAdapter
            .Setup(x => x.GetFileMetaDatasAsync(It.IsAny <int>(), It.IsAny <FileTypeOption>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(fileMetaDatas));

            File file = null;

            // Act
            file = await this.fileManager.GetFileAsync(
                urn,
                fileType,
                fallbackUrns,
                cancellationToken);

            // Assert
            Assert.IsNull(file);
        }
Exemplo n.º 15
0
 protected override async Task PerformOperation(Domain.Models.File file)
 {
     file.AdministrativelyLock((await _identityResolver.IsAdminAsync()));
 }
Exemplo n.º 16
0
        public async Task GetFileAsync_MultipleMetaDataRecordsFoundForUrnAllFilesExist_ReturnsZip()
        {
            // Arrange
            int urn = 1234;

            int[]             fallbackUrns      = null;
            FileTypeOption    fileType          = FileTypeOption.Report;
            CancellationToken cancellationToken = CancellationToken.None;

            string[] exampleDocs = new string[]
            {
                "doc1.pdf",
                "doc2.pdf",
                "doc3.pdf"
            };

            IEnumerable <FileMetaData> fileMetaDatas = exampleDocs
                                                       .Select(x => $"https://some-storage-container.azure.example/{x}")
                                                       .Select(x => new Uri(x, UriKind.Absolute))
                                                       .Select(x => new FileMetaData()
            {
                Location = x
            })
                                                       .ToArray();

            this.mockFileMetaDataAdapter
            .Setup(x => x.GetFileMetaDatasAsync(It.IsAny <int>(), It.IsAny <FileTypeOption>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(fileMetaDatas));

            Random random = new Random();

            byte[] contentBytes = null;

            File file = null;
            Func <FileMetaData, CancellationToken, Task <File> > getFileAsyncCallback =
                (fmd, ct) =>
            {
                contentBytes = new byte[random.Next(1024, 2048)];

                random.NextBytes(contentBytes);

                file = new File()
                {
                    FileName     = fmd.Location.Segments.Last(),
                    ContentType  = "application/pdf",
                    ContentBytes = contentBytes,
                };

                return(Task.FromResult(file));
            };

            this.mockFileStorageAdapter
            .Setup(x => x.GetFileAsync(It.IsAny <FileMetaData>(), It.IsAny <CancellationToken>()))
            .Returns(getFileAsyncCallback);

            File actualFile = null;

            string expectedContentType = "application/zip";
            string actualContentType   = null;

            string expectedFilename = $"{urn} files.zip";
            string actualFilename   = null;

            IEnumerable <ZipArchiveEntry> zipArchiveEntries = null;
            int expectedNumberOfArchiveEntries = 3;
            int actualNumberOfArchiveEntries;

            // Act
            actualFile = await this.fileManager.GetFileAsync(
                urn,
                fileType,
                fallbackUrns,
                cancellationToken);

            // Assert
            actualContentType = actualFile.ContentType;
            Assert.AreEqual(expectedContentType, actualContentType);

            actualFilename = actualFile.FileName;
            Assert.AreEqual(expectedFilename, actualFilename);

            // -> Actually open the zip to check that the bytes are all good.
            zipArchiveEntries            = this.ExtractZipEntries(actualFile);
            actualNumberOfArchiveEntries = zipArchiveEntries.Count();

            Assert.AreEqual(
                expectedNumberOfArchiveEntries,
                actualNumberOfArchiveEntries);
        }
Exemplo n.º 17
0
        public async Task GetFileAsync_NoResultsForPrimaryUrnButResultsForFallbackUrns_ReturnsZip()
        {
            // Arrange
            int urn = 1234;

            int[]             fallbackUrns      = new int[] { 3456, 7890 };
            FileTypeOption    fileType          = FileTypeOption.Report;
            CancellationToken cancellationToken = CancellationToken.None;

            Func <int, FileTypeOption, CancellationToken, Task <IEnumerable <FileMetaData> > > getFileMetaDataCallback =
                (urn, fileType, cancellationToken) =>
            {
                IEnumerable <FileMetaData> results = null;

                // Only return results for a fallback.
                if (fallbackUrns.Contains(urn))
                {
                    results = new string[]
                    {
                        $"{urn} docs/report-{urn}.pdf",
                        $"{urn} docs/{Guid.NewGuid()}.docx",
                    }
                    .Select(x => $"https://some-storage-container.azure.example/{x}")
                    .Select(x => new Uri(x, UriKind.Absolute))
                    .Select(x => new FileMetaData()
                    {
                        Location = x
                    })
                    .ToArray();
                }
                else
                {
                    results = Array.Empty <FileMetaData>();
                }

                return(Task.FromResult(results));
            };

            this.mockFileMetaDataAdapter
            .Setup(x => x.GetFileMetaDatasAsync(It.IsAny <int>(), It.IsAny <FileTypeOption>(), It.IsAny <CancellationToken>()))
            .Returns(getFileMetaDataCallback);

            Random random = new Random();

            byte[] contentBytes = null;

            File file = null;
            Func <FileMetaData, CancellationToken, Task <File> > getFileAsyncCallback =
                (fmd, ct) =>
            {
                contentBytes = new byte[random.Next(1024, 2048)];

                random.NextBytes(contentBytes);

                file = new File()
                {
                    FileName     = fmd.Location.Segments.Last(),
                    ContentType  = "application/pdf",
                    ContentBytes = contentBytes,
                };

                return(Task.FromResult(file));
            };

            this.mockFileStorageAdapter
            .Setup(x => x.GetFileAsync(It.IsAny <FileMetaData>(), It.IsAny <CancellationToken>()))
            .Returns(getFileAsyncCallback);

            File actualFile = null;

            string expectedContentType = "application/zip";
            string actualContentType   = null;

            string expectedFilename = $"{urn} files.zip";
            string actualFilename   = null;

            IEnumerable <ZipArchiveEntry> zipArchiveEntries = null;

            int expectedNumberOfArchiveEntries = 4;
            int actualNumberOfArchiveEntries;

            // Act
            actualFile = await this.fileManager.GetFileAsync(
                urn,
                fileType,
                fallbackUrns,
                cancellationToken);

            // Assert
            actualContentType = actualFile.ContentType;
            Assert.AreEqual(expectedContentType, actualContentType);

            actualFilename = actualFile.FileName;
            Assert.AreEqual(expectedFilename, actualFilename);

            // -> Actually open the zip to check that the bytes are all good.
            zipArchiveEntries            = this.ExtractZipEntries(actualFile);
            actualNumberOfArchiveEntries = zipArchiveEntries.Count();

            Assert.AreEqual(
                expectedNumberOfArchiveEntries,
                actualNumberOfArchiveEntries);
        }
Exemplo n.º 18
0
 protected override Task PerformOperation(Domain.Models.File file)
 {
     file.Unlock(_user.GetId());
     return(Task.CompletedTask);
 }
Exemplo n.º 19
0
 protected override async Task PerformOperation(Domain.Models.File file)
 {
     file.Lock(_user.GetId(), isAdmin: (await _identityResolver.IsAdminAsync()));
 }
Exemplo n.º 20
0
 protected abstract Task PerformOperation(Domain.Models.File file);