Exemplo n.º 1
0
        public void SetUp()
        {
            _autoMocker = new();

            _userId = Guid.NewGuid();
            _items  = new Dictionary <object, object>();
            _items.Add("UserId", _userId);

            _dbFileMapper = _autoMocker.CreateInstance <DbFileMapper>();

            _autoMocker
            .Setup <IHttpContextAccessor, IDictionary <object, object> >(x => x.HttpContext.Items)
            .Returns(_items);

            _fileRequest = new AddFileRequest
            {
                Content   = "RGlnaXRhbCBPZmA5Y2U=",
                Extension = ".txt",
                Name      = "DigitalOfficeTestFile"
            };

            _dbFile = new DbFile
            {
                Id        = Guid.NewGuid(),
                Content   = "RGlnaXRhbCBPZmA5Y2U=",
                Extension = ".txt",
                Name      = "DigitalOfficeTestFile"
            };
        }
        public async Task AddDocument_GivenCorrectInput_AddsDocument(
            [Frozen] Mock <IDocumentService> documentServiceMock,
            [Frozen] Mock <IFormFile> formFileMock,
            MemoryStream fileContentStream,
            Task <string> addDocumentServiceTask,
            AddFileRequest request)
        {
            // Arrange
            formFileMock.Setup(formFile => formFile.OpenReadStream())
            .Returns(fileContentStream);

            documentServiceMock.Setup(service =>
                                      service.AddAsync(request.File.Name, request.File.ContentType,
                                                       ByteSize.FromBytes(request.File.Length), fileContentStream))
            .Returns(addDocumentServiceTask)
            .Verifiable();

            DocumentsController sut = new DocumentsController(documentServiceMock.Object);

            // Act
            Task  addDocumentTask = sut.AddDocument(request);
            await addDocumentTask;

            // Verify
            addDocumentTask.Should().BeSameAs(addDocumentServiceTask);

            documentServiceMock.Verify();
        }
Exemplo n.º 3
0
        public async Task <Register> AddFile(int userId, int?parentFolder, AddFileRequest request)
        {
            string relativeFilePath;

            if (parentFolder.HasValue)
            {
                var folder = await _context.Register.Where(
                    register => register.Id == parentFolder.Value).AsNoTracking().FirstOrDefaultAsync();

                if (folder == null)
                {
                    return(null);
                }

                relativeFilePath = await _userFilesService.SaveFile(
                    formFile : request.File,
                    relativeParentFolderPath : folder.PathOrUrl,
                    parentFolderId : folder.Id
                    );
            }
            else
            {
                // IMPORTANT: When the parentFolder is null, the relativeParentFolderPath will be the user id
                // and the parentFolderId (only for the relativeFilePath) will be 0.
                // For example: If the user id is 5, the file path will be "5/0-fileName.extension"
                relativeFilePath = await _userFilesService.SaveFile(
                    formFile : request.File,
                    relativeParentFolderPath : userId.ToString(),
                    parentFolderId : 0
                    );
            }

            if (relativeFilePath == null)
            {
                return(null);
            }

            var fileToAdd = _context.Register.Add(new Register
            {
                Name             = request.File.FileName,
                PathOrUrl        = relativeFilePath,
                FileExtension    = Path.GetExtension(path: relativeFilePath),
                Size             = (int?)request.File.Length,
                UploadDate       = DateTime.Now,
                LastModifiedDate = DateTime.Now,
                IsFolder         = false,
                ParentFolder     = parentFolder,
                Author           = userId,
            });

            var entriesWritten = await _context.SaveChangesAsync();

            if (entriesWritten > 0)
            {
                return(fileToAdd.Entity);
            }

            return(null);
        }
Exemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="request"> (optional)</param>
        /// <returns>Task of ApiResponse</returns>
        public async System.Threading.Tasks.Task <ApiResponse <Object> > FilePostAsyncWithHttpInfo(AddFileRequest request = null)
        {
            var    localVarPath         = "/File";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json-patch+json",
                "application/json",
                "text/json",
                "application/_*+json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
            };
            String localVarHttpHeaderAccept    = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (request != null && request.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(request); // http body (model) parameter
            }
            else
            {
                localVarPostBody = request; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                       Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                       localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("FilePost", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <Object>(localVarStatusCode,
                                            localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                            null));
        }
Exemplo n.º 5
0
        internal async Task <AddFileResponse> AddFile(AddFileRequest request)
        {
            if (string.IsNullOrWhiteSpace(request?.File?.Url))
            {
                throw new Exception("No data provided to request");
            }

            var apiResponse = await _client.PostAsync <AddFileResponse, File>("files", request.File);

            return(apiResponse);
        }
        public void SetUp()
        {
            _fileRequest = new AddFileRequest
            {
                Content   = "RGlnaXRhbCBPZmA5Y2U=",
                Extension = ".txt",
                Name      = "DigitalOfficeTestFile"
            };

            _validator = new FileRequestValidator();
        }
Exemplo n.º 7
0
        public IActionResult AddFile([FromBody] AddFileRequest request)
        {
            var dbFile = new DbFile
            {
                ContentType = request.ContentType,
                FileName    = request.FileName,
                Contents    = Convert.FromBase64String(request.Contents)
            };

            _dbContext.Files.Add(dbFile);
            _dbContext.SaveChanges();

            return(Ok(dbFile));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Add([FromBody] AddFileRequest content)
        {
            var command = new AddFileCommand(content);

            try
            {
                await _commandProcessor.SendAsync(command);
            }
            catch (Exception exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, $"Failed to add the content: {exception.Message}."));
            }

            return(Ok());
        }
Exemplo n.º 9
0
        public async Task <IActionResult> AddFile([FromForm] AddFileRequest request)
        {
            var userIdString = JWTUtility.GetUserId(User);

            if (userIdString == null)
            {
                return(BadRequest());
            }

            var userId = int.Parse(userIdString);

            if (request.ParentFolder != null)
            {
                // Check if the parent folder does belong to the user
                if (!await _registerService.DoesFolderBelongToUser(
                        userId, folderId: request.ParentFolder.Value))
                {
                    return(BadRequest());
                }
            }

            // Check if the filename is valid
            if (!FileNameUtility.FileFolderNameIsValid(request.File.FileName))
            {
                return(BadRequest(Texts.INVALID_FILE_NAME));
            }

            // Check if the file does not exist
            if (await _registerService.DoesFileOrFolderAlreadyExist(userId, name: request.File.FileName, parentFolder: request.ParentFolder))
            {
                return(BadRequest(Texts.FILE_FOLDER_ALREADY_EXISTS));
            }

            var fileAdded = await _registerService.AddFile(userId, parentFolder : request.ParentFolder, request);

            if (fileAdded == null)
            {
                return(StatusCode(statusCode: 500, value: Texts.ERROR_SAVING_FILE));
            }

            return(Ok(fileAdded));
        }
Exemplo n.º 10
0
        public ActionResult AddFile([FromRoute] string key, [FromBody] AddFileRequest request)
        {
            try
            {
                var path     = ConfigHelper.GetAppSetting("CachePath");
                var filePath = System.IO.Path.Combine(path, key.Replace("___", "/"));

                this.CreateFolderForFile(filePath);

                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }

                System.IO.File.WriteAllBytes(filePath, request.content);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(this.LogAndReturn500(ex));
            }
        }
Exemplo n.º 11
0
 public AddFileCommand(AddFileRequest addFileRequest)
 {
     Content = addFileRequest.Content;
     Id      = Guid.NewGuid();
 }
Exemplo n.º 12
0
        public async Task <AddFileResponse> AddFile(AddFileRequest request)
        {
            var result = await _fileLibraryService.AddFile(request);

            return(result);
        }
Exemplo n.º 13
0
 public void Post([FromForm] AddFileRequest addFileRequest)
 {
     addFileCommandHandler.Handle(addFileRequest);
 }
Exemplo n.º 14
0
 /// <summary>
 ///
 /// </summary>
 /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="request"> (optional)</param>
 /// <returns>Task of void</returns>
 public async System.Threading.Tasks.Task FilePostAsync(AddFileRequest request = null)
 {
     await FilePostAsyncWithHttpInfo(request);
 }
Exemplo n.º 15
0
 /// <summary>
 ///
 /// </summary>
 /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="request"> (optional)</param>
 /// <returns></returns>
 public void FilePost(AddFileRequest request = null)
 {
     FilePostWithHttpInfo(request);
 }