public async Task <ResultResponse <AdvertisementDto> > AddAdvertisement([FromForm] AdvertisementCreateDto dto) { if (await IsInRole(Roles.Admin, Roles.Moderator)) { if (dto != null && ModelState.IsValid) { return(await _advertisementsService.AddAdvertisementAsync(dto, UserId.Value)); } return(ResultResponse <AdvertisementDto> .GetBadResponse(BussinesLogic.Models.StatusCode.BadRequest)); } return(ResultResponse <AdvertisementDto> .GetBadResponse(BussinesLogic.Models.StatusCode.Forbidden)); }
public async Task <IActionResult> CreateAdvertisement(AdvertisementCreateDto adv) { if (!ModelState.IsValid) { return(BadRequest("Fill all fields")); } var advertisement = _mapper.Map <Advertisement>(adv); try { advertisement = await _advertisementsService.CreateAsync(advertisement); return(Created(Request.Path, advertisement.Id)); } catch (EntityNotFoundException e) { return(BadRequest(e.Message)); } catch (Exception) { return(this.ServerError("Failed to create advertisement")); } }
public async Task <IHttpActionResult> Create(AdvertisementCreateDto advertisementCreate) { if (ModelState.IsValid) { var session = await db.Sessions.SingleOrDefaultAsync( QueryHelper.GetSessionObjectValidationQuery(advertisementCreate.Session)); if (session != null) { var user = session.User; var isImageEmpty = string.IsNullOrEmpty(advertisementCreate.UserImage); Models.Image userImage = null; if (!isImageEmpty) { //we write user's uploaded image in memory userImage = ImageHandler.CreateUserImage(db, user.Id, advertisementCreate.UserImage); } var newAdvertisement = new Advertisement() { User = user, MedType = advertisementCreate.MedType, GameId = advertisementCreate.GameId, GameReg = advertisementCreate.GameReg, Latitude = advertisementCreate.Latitude, Longitude = advertisementCreate.Longitude, LocationRegionId = advertisementCreate.LocationRegionId, LocationCityId = advertisementCreate.LocationCityId, LocationProvinceId = advertisementCreate.LocationProvinceId, Price = advertisementCreate.Price, PlatformId = advertisementCreate.PlatformId, Caption = advertisementCreate.Caption, UserImage = userImage, isDeleted = false, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now }; db.Advertisements.Add(newAdvertisement); if (advertisementCreate.ExchangeGames.Count > 0) //we have some games to exchange { foreach (var game in advertisementCreate.ExchangeGames) { var newExchange = new Exchange() { AdvertisementId = newAdvertisement.Id, GameId = game }; db.Exchanges.Add(newExchange); } } await db.SaveChangesAsync(); // Broadcasting NotificationGenerator.NewAdvertisementNotification(db, newAdvertisement); return(Ok(newAdvertisement.Id)); } return(Unauthorized()); } return(BadRequest()); }
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()); } }