Beispiel #1
0
        public async Task <ResultResponse> RemoveDebtorFileAsync(int id)
        {
            try
            {
                var debtorFile = await _debtorFilesRepository.GetAsync(id);

                if (debtorFile == null)
                {
                    return(ResultResponse.GetBadResponse(StatusCode.NotFound, "Не найден файл по этому идентификатору"));
                }

                debtorFile.is_active = false;
                var updated = await _debtorFilesRepository.UpdateAsync(debtorFile);

                if (updated != null)
                {
                    return(ResultResponse.GetSuccessResponse());
                }
                else
                {
                    return(ResultResponse.GetInternalServerErrorResponse());
                }
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, id, GetType().Name, nameof(RemoveDebtorFileAsync));
                return(ResultResponse.GetInternalServerErrorResponse());
            }
        }
Beispiel #2
0
		public async Task<ResultResponse<PostGetDto>> CreatePostAsync(PostCreateDto dto, int creatorId)
		{
			try
			{
				var creator = await _usersRepository.GetAsync(creatorId);
				if (creator == null)
				{
					return ResultResponse<PostGetDto>.GetBadResponse(StatusCode.NotFound, "Пользователь не найден");
				}

				var post = _mapper.Map<Post>(dto);
				post.creator_id = creatorId;
				post.created = DateTime.Now;
				var added = await _postsRepository.AddAsync(post);
				if (added == null)
				{
					return ResultResponse<PostGetDto>.GetBadResponse(StatusCode.InternalServerError, "Не удалось добавить пост");
				}
				var addedView = await _postsViewRepository.GetAsync(post.id);
				var addedViewDto = _mapper.Map<PostGetDto>(addedView);

				return ResultResponse<PostGetDto>.GetSuccessResponse(addedViewDto);
			}
			catch (Exception ex)
			{
				_progressLogger.Error(ex, new { dto, creatorId }, GetType().Name, nameof(CreatePostAsync));
				return ResultResponse<PostGetDto>.GetInternalServerErrorResponse();
			}
		}
Beispiel #3
0
        public async Task <ResultResponse <LegislationDto> > AddAsync(LegislationCreateDto createDto, int creatorId)
        {
            try
            {
                var creator = await _usersRepository.GetAsync(creatorId);

                if (creator == null)
                {
                    return(ResultResponse <LegislationDto> .GetBadResponse(StatusCode.NotFound, "Пользователь с таким идентификатором не найден"));
                }
                var legislation = _mapper.Map <Legislation>(createDto);
                legislation.creator_id = creatorId;
                legislation.created    = DateTime.Now;
                var added = await _legislationsRepository.AddAsync(legislation);

                if (added == null)
                {
                    return(ResultResponse <LegislationDto> .GetInternalServerErrorResponse());
                }
                var newLegislationDto = _mapper.Map <LegislationDto>(added);
                return(ResultResponse <LegislationDto> .GetSuccessResponse(newLegislationDto));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { createDto, creatorId }, GetType().Name, nameof(AddAsync));
                return(ResultResponse <LegislationDto> .GetInternalServerErrorResponse());
            }
        }
Beispiel #4
0
        public async Task <ResultResponse <UserDto> > EditAsync(int userId, UserEditDto dto)
        {
            try
            {
                var user = await _userRepository.GetAsync(userId);

                if (user == null)
                {
                    return(ResultResponse <UserDto> .GetBadResponse(StatusCode.NotFound, "Пользователь с таким id не найден"));
                }

                user.fname       = dto.FName;
                user.lname       = dto.LName;
                user.mname       = dto.MName;
                user.age         = dto.Age;
                user.address     = dto.Address;
                user.area_number = dto.AreaNumber;

                var updated = await _userRepository.UpdateAsync(user);

                if (updated == null)
                {
                    return(ResultResponse <UserDto> .GetInternalServerErrorResponse());
                }

                var updatedDto = _mapper.Map <UserDto>(updated);
                return(ResultResponse <UserDto> .GetSuccessResponse(updatedDto));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { userId, dto }, GetType().Name, nameof(EditAsync));
                return(ResultResponse <UserDto> .GetInternalServerErrorResponse());
            }
        }
Beispiel #5
0
        public async Task <ResultResponse <AdvertisementDto> > EditAdvertisementAsync(int id, AdvertisementEditDto dto)
        {
            try
            {
                var advertisement = await _advertisementsRepository.GetAsync(id);

                if (advertisement == null)
                {
                    return(ResultResponse <AdvertisementDto> .GetBadResponse(StatusCode.NotFound, "Объявление не найдено"));
                }
                advertisement.text            = dto.Text;
                advertisement.title           = dto.Title;
                advertisement.price           = dto.Price;
                advertisement.square          = dto.Square;
                advertisement.is_privatizated = dto.IsPrivatizated;
                var edited = await _advertisementsRepository.UpdateAsync(advertisement);

                if (edited != null)
                {
                    var editedView = await _advertisementViewsRepository.GetAsync(edited.id);

                    var editedDto = _mapper.Map <AdvertisementDto>(editedView);
                    return(ResultResponse <AdvertisementDto> .GetSuccessResponse(editedDto));
                }
                else
                {
                    return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse("Произошла неизвестная ошибка при редактировании объявления"));
                }
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { id, dto }, GetType().Name, nameof(EditAdvertisementAsync));
                return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse());
            }
        }
Beispiel #6
0
        public async Task <ResultResponse> RegisterAsync(UserRegisterDto dto)
        {
            try
            {
                var user = (await _userRepository.GetAsync($"where lower(email) = lower('{dto.Email}')")).FirstOrDefault();
                if (user != null)
                {
                    return(ResultResponse.GetBadResponse(StatusCode.BadRequest, "Пользователь с таким Email уже зарегистрирован"));
                }

                var newUser = _mapper.Map <User>(dto);
                newUser.registered    = DateTime.Now;
                newUser.salt          = GenerateSalt();
                newUser.password_hash = await _passwordHashService.GetPasswordHashWithSalt(dto.Password, newUser.salt);

                var added = await _userRepository.AddAsync(newUser);

                if (added != null)
                {
                    return(ResultResponse.GetSuccessResponse());
                }
                else
                {
                    return(ResultResponse.GetInternalServerErrorResponse());
                }
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, dto, GetType().Name, nameof(RegisterAsync));
                return(ResultResponse.GetInternalServerErrorResponse());
            }
        }
Beispiel #7
0
        public async Task <ResultResponse> DeleteMemberAsync(int userId)
        {
            try
            {
                var user = await _usersRepository.GetAsync(userId);

                if (user != null)
                {
                    user.is_government_member = false;
                    var updated = await _usersRepository.UpdateAsync(user);

                    if (updated == null)
                    {
                        return(ResultResponse.GetInternalServerErrorResponse());
                    }
                    return(ResultResponse.GetSuccessResponse());
                }
                else
                {
                    return(ResultResponse.GetBadResponse(StatusCode.NotFound));
                }
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { userId }, GetType().Name, nameof(DeleteMemberAsync));
                return(ResultResponse.GetInternalServerErrorResponse());
            }
        }
Beispiel #8
0
        public async Task <ResultResponse> ChangePasswordAsync(int userId, ChangePasswordDto dto)
        {
            try
            {
                var user = await _userRepository.GetAsync(userId);

                if (user == null)
                {
                    return(ResultResponse.GetBadResponse(StatusCode.NotFound, "Пользователь с таким id не найден"));
                }

                var oldHash        = user.password_hash;
                var oldConfirmHash = await _passwordHashService.GetPasswordHashWithSalt(dto.OldPassword, user.salt);

                if (oldHash == oldConfirmHash)                 // Если хеши равны, то и пароли равны (если не менялся алгоритм хеширования и соль)
                {
                    var newHash = await _passwordHashService.GetPasswordHashWithSalt(dto.NewPassword, user.salt);

                    user.password_hash = newHash;
                    var updated = await _userRepository.UpdateAsync(user);

                    if (updated != null)
                    {
                        return(ResultResponse.GetSuccessResponse());
                    }
                }
                return(ResultResponse.GetBadResponse(StatusCode.BadRequest, "Неверный старый пароль"));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, userId, GetType().Name, nameof(ChangePasswordAsync));
                return(ResultResponse.GetInternalServerErrorResponse());
            }
        }
Beispiel #9
0
        public async Task <ResultResponse <IEnumerable <QuestionDto> > > GetQuestionListAsync(int userId)
        {
            try
            {
                var user = await _usersRepository.GetAsync(userId);

                if (user == null)
                {
                    return(ResultResponse <IEnumerable <QuestionDto> > .GetBadResponse(StatusCode.NotFound, "Пользователь не найден"));
                }
                var questionViews = await _questionsViewRepository.GetAsync("WHERE is_active = TRUE");

                var questionMiddleDtos = _mapper.Map <IEnumerable <QuestionFullDto> >(questionViews);              // Конвертируем в промежуточный ДТО
                var questionDtos       = _mapper.Map <IEnumerable <QuestionDto> >(questionMiddleDtos);
                foreach (var q in questionDtos)
                {
                    q.IsVoted = await IsUserVotedInQuestion(userId, q.Id);
                }
                return(ResultResponse <IEnumerable <QuestionDto> > .GetSuccessResponse(questionDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { userId }, GetType().Name, nameof(GetQuestionListAsync));
                return(ResultResponse <IEnumerable <QuestionDto> > .GetInternalServerErrorResponse());
            }
        }
Beispiel #10
0
        public async Task <ResultResponse <DocumentDto> > AddDocumentAsync(DocumentCreateDto dto, int userId)
        {
            try
            {
                var uploader = await _usersRepository.GetAsync(userId);

                if (uploader == null)
                {
                    return(ResultResponse <DocumentDto> .GetBadResponse(StatusCode.NotFound, "Не найден пользователь"));
                }

                byte[] bytes = new byte[dto.File.Length];
                using (var stream = dto.File.OpenReadStream())
                {
                    await stream.ReadAsync(bytes, 0, (int)dto.File.Length);
                }
                var fileManager = new FileManager.Infrasructure.FileManager(
                    baseAddress: _configurationService.WebAppSettings.BaseAddress,
                    folder: _configurationService.UploadedFilesSettings.DocumentsFilesFolderRelativePath,
                    progressLogger: _progressLogger);
                var uploadingResult = await fileManager.UploadFileAsync(new FileDto(dto.File.FileName, bytes),
                                                                        new string[] { "png", "jpg", "gif", "jpeg", "bmp" });

                if (uploadingResult.IsSuccess)
                {
                    var document = await _documentsRepository.AddAsync(new Document
                    {
                        length      = (int)dto.File.Length,
                        name        = dto.Name,
                        native_name = dto.File.FileName,
                        path        = uploadingResult.FilePath,
                        created     = DateTime.Now,
                        creator_id  = userId,
                    });

                    if (document != null)
                    {
                        var documentView = await _documentViewsRepository.GetAsync(document.id);

                        var documentDto = _mapper.Map <DocumentDto>(documentView);
                        return(ResultResponse <DocumentDto> .GetSuccessResponse(documentDto));
                    }
                    else
                    {
                        return(ResultResponse <DocumentDto> .GetInternalServerErrorResponse());
                    }
                }
                else
                {
                    return(ResultResponse <DocumentDto> .GetInternalServerErrorResponse(uploadingResult.ErrorDescription));
                }
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { dto, userId }, GetType().Name, nameof(AddDocumentAsync));
                return(ResultResponse <DocumentDto> .GetInternalServerErrorResponse());
            }
        }
Beispiel #11
0
        public async Task <ResultResponse <QuestionDto> > AddQuestionAsync(QuestionCreateDto dto, int userId)
        {
            try
            {
                // Тексты вариантов не должны содержать | , т.к. этот символ используется в STRING_AGG в progress.questionsview
                // != false, потому что может быть как true, так и null, и эти оба варианта нам не подходят = ошибка
                if (dto?.Choises?.Any(x => x.Text.Contains('|')) != false)
                {
                    return(ResultResponse <QuestionDto> .GetBadResponse(StatusCode.NotFound, "Тексты вариантов ответа не должны содержать знак |"));
                }

                var user = await _usersRepository.GetAsync(userId);

                if (user == null)
                {
                    return(ResultResponse <QuestionDto> .GetBadResponse(StatusCode.NotFound, "Пользователь не найден"));
                }
                var question = _mapper.Map <Question>(dto);
                question.creator_id = userId;
                question.created    = DateTime.Now;

                var addedQuestion = await _questionsRepository.AddAsync(question);

                if (addedQuestion == null)
                {
                    return(ResultResponse <QuestionDto> .GetInternalServerErrorResponse("Произошла ошибка при добавлении опроса"));
                }

                var choises = _mapper.Map <IEnumerable <Choise> >(dto.Choises);
                foreach (var ch in choises)
                {
                    ch.question_id = addedQuestion.id;
                    var addedChoise = await _choisesRepository.AddAsync(ch);

                    if (addedChoise == null)
                    {
                        return(ResultResponse <QuestionDto> .GetInternalServerErrorResponse("Произошла ошибка при добавлении варианта ответа"));
                    }
                }

                var questionView = await _questionsViewRepository.GetAsync(question.id);

                var questionMiddleDto = _mapper.Map <QuestionFullDto>(questionView);                // Конвертируем в промежуточный ДТО
                var addedQuestionDto  = _mapper.Map <QuestionDto>(questionMiddleDto);
                return(ResultResponse <QuestionDto> .GetSuccessResponse(addedQuestionDto));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { dto, userId }, GetType().Name, nameof(AddQuestionAsync));
                return(ResultResponse <QuestionDto> .GetInternalServerErrorResponse());
            }
        }
Beispiel #12
0
 public async Task <ResultResponse <string> > GetValueAsync(string key)
 {
     try
     {
         var value = (await _valuePairsRepository.GetAsync($"WHERE key='{key}'")).FirstOrDefault()?.value;
         return(ResultResponse <string> .GetSuccessResponse(value));
     }
     catch (Exception ex)
     {
         _progressLogger.Error(ex, key, GetType().Name, nameof(GetValueAsync));
         return(ResultResponse <string> .GetInternalServerErrorResponse());
     }
 }
Beispiel #13
0
        public async Task <ResultResponse <QuestionDto> > VoteAsync(int id, int voteId, int voterId)
        {
            try
            {
                var voter = await _usersRepository.GetAsync(voterId);

                if (voter == null)
                {
                    return(ResultResponse <QuestionDto> .GetBadResponse(StatusCode.NotFound, "Пользователь не найден"));
                }

                var question = (await _questionsRepository.GetAsync($"WHERE id = {id} AND is_active = TRUE")).FirstOrDefault();
                if (question == null)
                {
                    return(ResultResponse <QuestionDto> .GetBadResponse(StatusCode.NotFound, "Опрос не найден"));
                }

                var choise = await _choisesRepository.GetAsync(voteId);

                if (choise == null)
                {
                    return(ResultResponse <QuestionDto> .GetBadResponse(StatusCode.NotFound, "Вариант ответа не найден"));
                }

                if (await IsUserVotedInQuestion(voterId, id))                 // Если уже принимал участие
                {
                    return(ResultResponse <QuestionDto> .GetBadResponse(StatusCode.Forbidden, "Пользователь уже принимал участие в этом опросе"));
                }
                else
                {
                    await _userToChoisesRepository.AddAsync(
                        new UserToChoise { choise_id = voteId, user_id = voterId }
                        );

                    choise.votes_count++;
                    await _choisesRepository.UpdateAsync(choise);

                    var questionView = await _questionsViewRepository.GetAsync(id);

                    var questionMiddleDto = _mapper.Map <QuestionFullDto>(questionView);                    // Конвертируем в промежуточный ДТО
                    var questionDto       = _mapper.Map <QuestionDto>(questionMiddleDto);
                    questionDto.IsVoted = true;
                    return(ResultResponse <QuestionDto> .GetSuccessResponse(questionDto));
                }
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { id, voteId, voterId }, GetType().Name, nameof(VoteAsync));
                return(ResultResponse <QuestionDto> .GetInternalServerErrorResponse());
            }
        }
Beispiel #14
0
		public async Task<ResultResponse<IEnumerable<PostGetDto>>> GetPostsAsync()
		{
			try
			{
				var posts = await _postsViewRepository.GetAsync();
				var postDtos = _mapper.Map<IEnumerable<PostGetDto>>(posts);
				return ResultResponse<IEnumerable<PostGetDto>>.GetSuccessResponse(postDtos);
			}
			catch (Exception ex)
			{
				_progressLogger.Error(ex, null, GetType().Name, nameof(GetPostsAsync));
				return ResultResponse<IEnumerable<PostGetDto>>.GetInternalServerErrorResponse();
			}
		}
Beispiel #15
0
        public async Task <ResultResponse <IEnumerable <UserDto> > > GetMembersAsync()
        {
            try
            {
                var users = await _usersRepository.GetAsync("where is_government_member = TRUE");

                var userDtos = _mapper.Map <IEnumerable <UserDto> >(users);
                return(ResultResponse <IEnumerable <UserDto> > .GetSuccessResponse(userDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, null, GetType().Name, nameof(GetMembersAsync));
                return(ResultResponse <IEnumerable <UserDto> > .GetInternalServerErrorResponse());
            }
        }
Beispiel #16
0
        public async Task <ResultResponse <IEnumerable <AdvertisementDto> > > GetAdvertisementListAsync()
        {
            try
            {
                var advertisementViews = await _advertisementViewsRepository.GetAsync("WHERE is_active = TRUE");

                var advertisementDtos = _mapper.Map <IEnumerable <AdvertisementDto> >(advertisementViews);
                return(ResultResponse <IEnumerable <AdvertisementDto> > .GetSuccessResponse(advertisementDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, null, GetType().Name, nameof(GetAdvertisementListAsync));
                return(ResultResponse <IEnumerable <AdvertisementDto> > .GetInternalServerErrorResponse());
            }
        }
Beispiel #17
0
        public async Task <ResultResponse <IEnumerable <LegislationDto> > > GetListAsync()
        {
            try
            {
                var legislations = await _legislationsRepository.GetAsync();

                var legislationDtos = _mapper.Map <IEnumerable <LegislationDto> >(legislations);
                return(ResultResponse <IEnumerable <LegislationDto> > .GetSuccessResponse(legislationDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, null, GetType().Name, nameof(GetListAsync));
                return(ResultResponse <IEnumerable <LegislationDto> > .GetInternalServerErrorResponse());
            }
        }
Beispiel #18
0
        public async Task <ResultResponse <IEnumerable <DebtorFileDto> > > GetListAsync()
        {
            try
            {
                var debtorFiles = await _debtorFilesRepository.GetAsync($"WHERE is_active = TRUE");

                var debtorFileDtos = _mapper.Map <IEnumerable <DebtorFileDto> >(debtorFiles);
                return(ResultResponse <IEnumerable <DebtorFileDto> > .GetSuccessResponse(debtorFileDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, null, GetType().Name, nameof(GetListAsync));
                return(ResultResponse <IEnumerable <DebtorFileDto> > .GetInternalServerErrorResponse());
            }
        }
Beispiel #19
0
        public async Task <ResultResponse <JwtAuthorizationDto> > LoginAsync(string login, string password)
        {
            try
            {
                var identity = await GetIdentityAsync(login, password);

                if (identity == null)
                {
                    return(ResultResponse <JwtAuthorizationDto> .GetBadResponse(StatusCode.BadRequest, "Неверный логин и(или) пароль"));
                }

                DateTime?endLifeTime = null;
                DateTime?notBefore   = null;
                DateTime?expires     = null;

                if (_authSettings.ValidateLifetime)                 // Если токен валидируется по времени
                {
                    notBefore = DateTime.UtcNow;
                    expires   = notBefore.Value.Add(TimeSpan.FromMinutes(_authSettings.Lifetime));
                }

                // Создаем JWT-токен
                var jwt = new JwtSecurityToken(
                    issuer: _authSettings.Issuer,
                    audience: _authSettings.Audience,
                    notBefore: notBefore,
                    claims: identity.Claims,
                    expires: expires,
                    signingCredentials: new SigningCredentials(_authSettings.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                return(ResultResponse <JwtAuthorizationDto> .GetSuccessResponse(
                           new JwtAuthorizationDto
                {
                    UsedLifetime = _authSettings.ValidateLifetime,
                    EndLifetime = endLifeTime,

                    Token = encodedJwt
                }));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { login, password }, GetType().Name, nameof(LoginAsync));
                return(ResultResponse <JwtAuthorizationDto> .GetInternalServerErrorResponse());
            }
        }
Beispiel #20
0
 public async Task <ResultResponse <AdvertisementDto> > GetAdvertisementAsync(int id)
 {
     try
     {
         var advertisementView = (await _advertisementViewsRepository.GetAsync($"WHERE id = {id} AND is_active = TRUE")).FirstOrDefault();
         if (advertisementView == null)
         {
             return(ResultResponse <AdvertisementDto> .GetBadResponse(StatusCode.NotFound));
         }
         var advertisementDto = _mapper.Map <AdvertisementDto>(advertisementView);
         return(ResultResponse <AdvertisementDto> .GetSuccessResponse(advertisementDto));
     }
     catch (Exception ex)
     {
         _progressLogger.Error(ex, new { id }, GetType().Name, nameof(GetAdvertisementAsync));
         return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse());
     }
 }
Beispiel #21
0
		public async Task<ResultResponse<PostGetDto>> GetPostAsync(int id)
		{
			try
			{
				var post = await _postsViewRepository.GetAsync(id);
				if (post == null)
				{
					return ResultResponse<PostGetDto>.GetBadResponse(StatusCode.NotFound);
				}
				var postDto = _mapper.Map<PostGetDto>(post);
				return ResultResponse<PostGetDto>.GetSuccessResponse(postDto);
			}
			catch (Exception ex)
			{
				_progressLogger.Error(ex, id, GetType().Name, nameof(GetPostAsync));
				return ResultResponse<PostGetDto>.GetInternalServerErrorResponse();
			}
		}		
Beispiel #22
0
 public async Task <ResultResponse <DebtorFileDto> > GetDebtorFileAsync(int id)
 {
     try
     {
         var debtorFile = (await _debtorFilesRepository.GetAsync($"WHERE id = {id} AND is_active = TRUE")).FirstOrDefault();
         if (debtorFile == null)
         {
             return(ResultResponse <DebtorFileDto> .GetBadResponse(StatusCode.NotFound, "Не найден файл с указанным идентификатором"));
         }
         var debtorFileDto = _mapper.Map <DebtorFileDto>(debtorFile);
         return(ResultResponse <DebtorFileDto> .GetSuccessResponse(debtorFileDto));
     }
     catch (Exception ex)
     {
         _progressLogger.Error(ex, id, GetType().Name, nameof(GetDebtorFileAsync));
         return(ResultResponse <DebtorFileDto> .GetInternalServerErrorResponse());
     }
 }
Beispiel #23
0
        public async Task <ResultResponse <UserDto> > GetAsync(int userId)
        {
            try
            {
                var user = await _userRepository.GetAsync(userId);

                if (user == null)
                {
                    return(ResultResponse <UserDto> .GetBadResponse(StatusCode.NotFound, "Пользователь с таким id не найден"));
                }
                var userDto = _mapper.Map <UserDto>(user);
                return(ResultResponse <UserDto> .GetSuccessResponse(userDto));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, userId, GetType().Name, nameof(GetAsync));
                return(ResultResponse <UserDto> .GetInternalServerErrorResponse());
            }
        }
Beispiel #24
0
		public async Task<ResultResponse<PagingData<PostGetDto>>> GetPagingPostsAsync(int numberPage, int pageSize)
		{
			try
			{
				var posts = await _postsViewRepository.GetAsync($"LIMIT {pageSize} OFFSET {(numberPage - 1) * pageSize}");
				var postDtos = _mapper.Map<IEnumerable<PostGetDto>>(posts);
				var count = await _postsViewRepository.GetCountAsync();

				return ResultResponse<PagingData<PostGetDto>>.GetSuccessResponse(new PagingData<PostGetDto>(
					postDtos.ToArray(),
					numberPage,
					count
				));
			}
			catch (Exception ex)
			{
				_progressLogger.Error(ex, new { numberPage, pageSize }, GetType().Name, nameof(GetPagingPostsAsync));
				return ResultResponse<PagingData<PostGetDto>>.GetInternalServerErrorResponse();
			}
		}
Beispiel #25
0
		public async Task<ResultResponse<PostGetDto>> UpdatePostAsync(int postId, PostEditDto dto, int editorId)
		{
			try
			{
				var editor = await _usersRepository.GetAsync(editorId);
				if (editor == null)
				{
					return ResultResponse<PostGetDto>.GetBadResponse(StatusCode.NotFound, "Пользователь не найден");
				}

				var post = await _postsRepository.GetAsync(postId);
				if (post == null)
				{
					return ResultResponse<PostGetDto>.GetBadResponse(StatusCode.NotFound, "Не найден пост");
				}

				post.text = dto.Text;
				post.title = dto.Title;
				post.edited = DateTime.Now;
				post.editor_id = editor.id;

				var updated = await _postsRepository.UpdateAsync(post);
				if (updated == null)
				{
					return ResultResponse<PostGetDto>.GetBadResponse(StatusCode.InternalServerError, "Не удалось отредактировать пост");
				}

				var editedView = await _postsViewRepository.GetAsync(updated.id);
				var editedViewDto = _mapper.Map<PostGetDto>(editedView);

				return ResultResponse<PostGetDto>.GetSuccessResponse(editedViewDto);
			}
			catch (Exception ex)
			{
				_progressLogger.Error(ex, new { dto, editorId }, GetType().Name, nameof(UpdatePostAsync));
				return ResultResponse<PostGetDto>.GetInternalServerErrorResponse();
			}
		}
Beispiel #26
0
        public async Task <ResultResponse <string[]> > GetUserAccess(int userId)
        {
            try
            {
                var user = await _userRepository.GetAsync(userId);

                if (user == null)
                {
                    return(ResultResponse <string[]> .GetBadResponse(StatusCode.NotFound, "Пользователь с таким id не найден"));
                }
                var rolesIds  = (await _userToRolesRepository.GetAsync($"WHERE user_id={userId}")).Select(x => x.role_id);
                var roleNames = Array.Empty <string>();
                if (rolesIds.Any())
                {
                    roleNames = (await _rolesRepository.GetAsync($"WHERE id IN ({string.Join(",", rolesIds)})")).Select(x => x.name).ToArray();
                }
                return(ResultResponse <string[]> .GetSuccessResponse(roleNames));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, userId, GetType().Name, nameof(ChangePasswordAsync));
                return(ResultResponse <string[]> .GetInternalServerErrorResponse());
            }
        }
Beispiel #27
0
        public async Task <ResultResponse <AdvertisementDto> > AddAdvertisementAsync(AdvertisementCreateDto dto, int creatorId)
        {
            try
            {
                int?imageId = null;                  // Идентификатор изображения (если прикреплеено)
                var creator = await _usersRepository.GetAsync(creatorId);

                if (creator == null)
                {
                    return(ResultResponse <AdvertisementDto> .GetBadResponse(StatusCode.NotFound, "Пользователь не найден"));
                }
                if (dto.Image != null)                 // Загрузить картинку (опционально)
                {
                    var fileManager = new FileManager.Infrasructure.FileManager(
                        baseAddress: _configurationService.WebAppSettings.BaseAddress,
                        folder: _configurationService.UploadedFilesSettings.AdvertisementFilesFolderRelativePath,
                        progressLogger: _progressLogger);
                    var bytes = new byte[dto.Image.Length];
                    using (var stream = dto.Image.OpenReadStream())
                    {
                        await stream.ReadAsync(bytes, 0, bytes.Length);
                    }
                    var uploadingResult = await fileManager.UploadFileAsync(
                        file : new FileDto(dto.Image.FileName, bytes),
                        allowedFormats : new string[] { "png", "jpg", "gif", "jpeg", "bmp" });

                    if (uploadingResult.IsSuccess)                     // Если удалось загрузить изображение, то сохраняем в БД
                    {
                        var newAdvertisementFile = new AdvertisementFile
                        {
                            length      = bytes.Length,
                            native_name = dto.Image.FileName,
                            path        = uploadingResult.FilePath,
                            uploaded    = DateTime.Now,
                            uploader_id = creatorId
                        };
                        var addedFile = await _advertisementFilesRepository.AddAsync(newAdvertisementFile);

                        if (addedFile == null)
                        {
                            return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse("Не удалось загрузить изображение"));
                        }
                        else                         // Если загрузили изображение, то сохраняем его id
                        {
                            imageId = addedFile.id;
                        }
                    }
                    else
                    {
                        return(ResultResponse <AdvertisementDto> .GetBadResponse(StatusCode.BadRequest, uploadingResult.ErrorDescription));
                    }
                }
                var advertisement = _mapper.Map <Advertisement>(dto);
                advertisement.created       = DateTime.Now;
                advertisement.creator_id    = creatorId;
                advertisement.image_file_id = imageId;
                var added = await _advertisementsRepository.AddAsync(advertisement);

                if (added == null)
                {
                    return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse("Произошла ошибка при добавлении объявления"));
                }
                else
                {
                    var addedView = await _advertisementViewsRepository.GetAsync(added.id);

                    var addedDto = _mapper.Map <AdvertisementDto>(addedView);
                    return(ResultResponse <AdvertisementDto> .GetSuccessResponse(addedDto));
                }
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { dto, creatorId }, GetType().Name, nameof(AddAdvertisementAsync));
                return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse());
            }
        }