Exemplo n.º 1
0
        public FileDto Create(FileCreateDto dto)
        {
            this._fileAuthService.VerifyComm100Platform(dto.Auth);

            this._fileDomainService.Create(new File());
            throw new NotImplementedException();
        }
Exemplo n.º 2
0
        public async Task <ActionResult <FileDto> > StudentCreateVerifyFile([FromForm] FileCreateDto dto)
        {
            FileCreateDtoValidator validator = new FileCreateDtoValidator();
            ValidationResult       result    = await validator.ValidateAsync(dto);

            if (result.IsValid)
            {
                var userId = User.Claims
                             .Single(p => p.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
                var student = await _dbContext.Students
                              .Include(x => x.StudentVerify)
                              .Include(x => x.StudentVerify.StudentVerifyFiles)
                              .SingleOrDefaultAsync(x => x.ApplicationUserId == userId);

                if (student.StudentConfirmed)
                {
                    return(Problem(title: "禁止修改", detail: "在校生已驗證", statusCode: 403));
                }
                var entity = _mapper.Map <StudentVerifyFile>(dto);

                #region 處理檔案

                await using (var transaction = await _dbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        using (var stream = new FileStream(entity.Path, FileMode.Create))
                        {
                            await dto.FileData.CopyToAsync(stream);
                        }
                        student.StudentVerify.StudentVerifyFiles.Add(entity);
                        _dbContext.Students.Update(student);
                        await _dbContext.SaveChangesAsync();

                        await transaction.CommitAsync();
                    }
                    catch (IOException)
                    {
                        await transaction.RollbackAsync();

                        throw;
                    }
                    catch (DbUpdateException)
                    {
                        System.IO.File.Delete(entity.Path);
                        await transaction.RollbackAsync();

                        throw;
                    }
                }

                #endregion

                var returnDto   = _mapper.Map <FileDto>(entity);
                var routeValues = new { fileId = returnDto.Id };
                return(CreatedAtAction(nameof(StudentVerifyFile), routeValues, returnDto));
            }
            return(BadRequest(result.Errors));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> CreatePhoto([FromForm] FileCreateDto dto)
        {
            FileCreateDtoValidator validator = new FileCreateDtoValidator();
            ValidationResult       result    = await validator.ValidateAsync(dto);

            if (result.IsValid)
            {
                var userId = User.Claims
                             .Single(p => p.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
                var user = await _dbContext.Users
                           .Include(x => x.UserPhoto)
                           .SingleOrDefaultAsync(x => x.Id == userId);

                if (user.UserPhoto != null)
                {
                    return(Problem(title: "禁止修改", detail: "使用者照片已存在", statusCode: 403));
                }

                var entity = _mapper.Map(dto, user.UserPhoto);

                #region 處理檔案

                await using (var transaction = await _dbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        using (var stream = new FileStream(entity.Path, FileMode.Create))
                        {
                            await dto.FileData.CopyToAsync(stream);
                        }
                        user.UserPhoto = entity;
                        _dbContext.Users.Update(user);
                        await _dbContext.SaveChangesAsync();

                        await transaction.CommitAsync();
                    }
                    catch (IOException)
                    {
                        await transaction.RollbackAsync();

                        throw;
                    }
                    catch (DbUpdateException)
                    {
                        System.IO.File.Delete(entity.Path);
                        await transaction.RollbackAsync();

                        throw;
                    }
                }

                #endregion

                var returnDto = _mapper.Map <FileDto>(user.UserPhoto);
                return(CreatedAtAction(nameof(Photo), null, returnDto));
            }
            return(BadRequest(result.Errors));
        }
Exemplo n.º 4
0
        public async Task <int> Create(FileCreateDto dto, string userId)
        {
            var createdFile = _mapper.Map <FileDbEntity>(dto);

            createdFile.FilePath = await _storageService.SaveFile(dto.File, $"Transaction{dto.TransactionId}", dto.FileExtension);

            await _dbContext.Files.AddAsync(createdFile);

            await _dbContext.SaveChangesAsync();

            return(createdFile.Id);
        }
Exemplo n.º 5
0
        public async Task <FileDto> Create(FileCreateDto dto)
        {
            await this._fileAuthService.VerifyComm100Platform(dto.Auth);

            bool ifExists = await _fileDomainService.Exist(dto.File.FileKey);

            if (ifExists)
            {
                throw new FileKeyExistsException();
            }
            var file   = FileMapping(dto);
            var result = await this._fileDomainService.Create(file);

            return(FileDtoMapping(result));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> CreateResume([FromForm] FileCreateDto dto)
        {
            var userId = User.Claims
                         .Single(p => p.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
            var user = await _dbContext.Users
                       .Include(x => x.FileResumes)
                       .SingleOrDefaultAsync(x => x.Id == userId);

            var entity = _mapper.Map <FileResume>(dto);

            #region 處理檔案

            await using (var transaction = await _dbContext.Database.BeginTransactionAsync())
            {
                try
                {
                    using (var stream = new FileStream(entity.Path, FileMode.Create))
                    {
                        await dto.FileData.CopyToAsync(stream);
                    }
                    user.FileResumes.Add(entity);
                    _dbContext.Users.Update(user);
                    await _dbContext.SaveChangesAsync();

                    await transaction.CommitAsync();
                }
                catch (IOException)
                {
                    await transaction.RollbackAsync();

                    throw;
                }
                catch (DbUpdateException)
                {
                    System.IO.File.Delete(entity.Path);
                    await transaction.RollbackAsync();

                    throw;
                }
            }

            #endregion

            var routeValues = new { resumeId = entity.FileResumeId };
            var returnDto   = _mapper.Map <FileDto>(entity);
            return(CreatedAtAction(nameof(GetResume), routeValues, returnDto));
        }
Exemplo n.º 7
0
        private File FileMapping(FileCreateDto dto)
        {
            var checksum = CalCulateChecksum(dto.File.Name, dto.File.Content);

            return(new File()
            {
                FileKey = dto.File.FileKey,
                SiteId = dto.File.SiteId,
                Checksum = checksum,
                ExpireTime = dto.File.ExpireTime,
                Content = new FileContent()
                {
                    Checksum = checksum,
                    Name = dto.File.Name,
                    Content = dto.File.Content,
                    StorageType = StorageType.Db,
                    Link = ""
                },
                CreationTime = DateTime.UtcNow,
            });
        }
        public ActionResult <FileReadDto> CreateFile(FileCreateDto fileCreateDto)
        {
            var fileModel     = _mapper.Map <Files>(fileCreateDto);
            var fileDataModel = _mapper.Map <Filedata>(fileCreateDto);

            if (_validate.GetAccountById(fileModel.AccountId) == null)
            {
                ModelState.AddModelError("accountId", $"The account with key: {fileModel.AccountId}, does not exist");
                return(ValidationProblem());
            }

            _data.CreateFileData(fileDataModel);
            _repository.SaveChanges();

            fileModel.DataId = fileDataModel.Id;

            _repository.CreateFile(fileModel);
            _repository.SaveChanges();

            var fileReadDto = _mapper.Map <FileReadDto>(fileModel);

            return(CreatedAtAction(nameof(CreateFile), new { id = fileReadDto.Id }, fileReadDto));
        }
        public async Task <IActionResult> CreateRecruitmentFile([FromRoute] string campaignId, [FromRoute] string recruitmentId, [FromForm] FileCreateDto dto)
        {
            FileCreateDtoValidator validator = new FileCreateDtoValidator();
            ValidationResult       result    = await validator.ValidateAsync(dto);

            if (result.IsValid)
            {
                var userId = User.Claims
                             .Single(p => p.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
                var administrator = await _dbContext.Administrators
                                    .AsNoTracking()
                                    .SingleOrDefaultAsync(x => x.ApplicationUserId == userId);

                #region 驗證

                if (!administrator.AdministratorConfirmed)
                {
                    return(Problem(title: "禁止修改", detail: "管理員尚未驗證", statusCode: 403));
                }

                #endregion

                var act = await _dbContext.RecruitmentCampaigns
                          .Include(x => x.RecruitmentCampaignFiles)
                          .SingleOrDefaultAsync(x => x.CampaignId == campaignId && x.RecruitmentCampaignId == recruitmentId);

                if (act == null)
                {
                    return(NotFound());
                }

                var entity = _mapper.Map <RecruitmentCampaignFile>(dto);

                #region 處理檔案

                await using (var transaction = await _dbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        using (var stream = new FileStream(entity.Path, FileMode.Create))
                        {
                            await dto.FileData.CopyToAsync(stream);
                        }
                        act.RecruitmentCampaignFiles.Add(entity);
                        _dbContext.RecruitmentCampaigns.Update(act);
                        await _dbContext.SaveChangesAsync();

                        await transaction.CommitAsync();
                    }
                    catch (IOException)
                    {
                        await transaction.RollbackAsync();

                        throw;
                    }
                    catch (DbUpdateException)
                    {
                        System.IO.File.Delete(entity.Path);
                        await transaction.RollbackAsync();

                        throw;
                    }
                }

                #endregion

                var routeValues = new { campaignId = act.CampaignId, recruitmentId = act.RecruitmentCampaignId, fileId = entity.RecruitmentCampaignFileId };
                var returnDto   = _mapper.Map <FileDto>(entity);
                return(CreatedAtAction(nameof(RecruitmentFile), routeValues, returnDto));
            }
            return(BadRequest(result.Errors));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> CreateNewFile([FromForm] FileCreateDto fileCreateDto)
        {
            var authorizationHeader = HttpContext.Request.Headers["Authorization"].ToString();
            var clientId            = authorizationHeader.GetClientId();

            var user = await _userRepository.GetUserByIdAsync(clientId);

            var userPath = Path.Combine(Directory.GetCurrentDirectory(), user.Id.ToString());
            var filePath = Path.Combine(userPath, fileCreateDto.FileName + fileCreateDto.FileType);

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

            if (!System.IO.File.Exists(filePath))
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new ValidationErrorDto
                {
                    TraceId = HttpContext.TraceIdentifier,
                    Status = StatusCodes.Status500InternalServerError.ToString(),
                    Errors = new Dictionary <string, string[]>
                    {
                        { "IOError", new[] { "Błąd podczas zapisywania pliku na serwerze!" } }
                    }
                }));
            }

            FileDto result;

            if (await _fileRepository.CheckIfFileExist(fileCreateDto.FileName, fileCreateDto.FileType))
            {
                var file = await _fileRepository.GetFileByNameAsync(fileCreateDto.FileName, fileCreateDto.FileType);

                _mapper.Map(fileCreateDto, file);
                var updatedFileModel = await _fileRepository.UpdateFile(file);

                result           = _mapper.Map <FileDto>(updatedFileModel);
                result.ShareLink = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}/api/file/{result.Id}";
            }
            else
            {
                var fileModel = _mapper.Map <FileModel>(fileCreateDto);
                fileModel.UserId = clientId;

                var createdFileModel = await _fileRepository.CreateFileAsync(fileModel);

                if (createdFileModel == null)
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, new ValidationErrorDto
                    {
                        TraceId = HttpContext.TraceIdentifier,
                        Status = StatusCodes.Status500InternalServerError.ToString(),
                        Errors = new Dictionary <string, string[]>
                        {
                            { "ServerError", new[] { "Błąd podczas zapisywania pliku na serwerze!" } }
                        }
                    }));
                }

                result           = _mapper.Map <FileDto>(createdFileModel);
                result.ShareLink = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}/api/file/{result.Id}";
            }

            return(Ok(result));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> CreateCompanyLogo([FromRoute] string companyId, [FromForm] FileCreateDto dto)
        {
            FileCreateDtoValidator validator = new FileCreateDtoValidator();
            ValidationResult       result    = await validator.ValidateAsync(dto);

            if (result.IsValid)
            {
                var userId = User.Claims
                             .Single(p => p.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
                var company = await _dbContext.Companies
                              .Include(x => x.CompanyLogo)
                              .Include(x => x.Managers)
                              .SingleOrDefaultAsync(x => x.CompanyId == companyId);

                if (company == null)
                {
                    return(NotFound());
                }
                var manager = company.Managers
                              .SingleOrDefault(x => x.ApplicationUserId == userId);
                if (manager == null)
                {
                    return(Problem(title: "禁止修改", detail: "非該公司管理者", statusCode: 403));
                }
                if (!manager.ManagerConfirmed)
                {
                    return(Problem(title: "禁止修改", detail: "企業使用者尚未驗證", statusCode: 403));
                }

                var entity = _mapper.Map(dto, company.CompanyLogo);

                #region 處理檔案

                await using (var transaction = await _dbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        using (var stream = new FileStream(entity.Path, FileMode.Create))
                        {
                            await dto.FileData.CopyToAsync(stream);
                        }
                        company.CompanyLogo = entity;
                        _dbContext.Companies.Update(company);
                        await _dbContext.SaveChangesAsync();

                        await transaction.CommitAsync();
                    }
                    catch (IOException)
                    {
                        await transaction.RollbackAsync();

                        throw;
                    }
                    catch (DbUpdateException)
                    {
                        System.IO.File.Delete(entity.Path);
                        await transaction.RollbackAsync();

                        throw;
                    }
                }

                #endregion

                var routeValues = new { companyId = entity.CompanyId };
                var returnDto   = _mapper.Map <FileDto>(entity);
                return(CreatedAtAction(nameof(CompanyLogo), routeValues, returnDto));
            }
            return(BadRequest(result.Errors));
        }
Exemplo n.º 12
0
 public async Task <IActionResult> Create([FromBody] FileCreateDto dto)
 => await GetResponse(async (userId) =>
                      new ApiResponseViewModel(true, "File Created Successfully", await _service.Create(dto, userId)));