Exemple #1
0
        public Advert Update(Advert advert, AdvertDto fromDto)
        {
            var resultingAdvert = BuildNew(fromDto);

            resultingAdvert.Status = advert.Status;
            resultingAdvert.Update();
            return(resultingAdvert);
        }
        public async Task <IActionResult> PhotoModal([FromQuery] int advert_id, [FromQuery] int photo_id)
        {
            var response = await _advertApiClient.GetAdvertsByFilterAsync(new AdvertFilter { AdvertId = advert_id, Size = 1, CurrentPage = 1 });

            AdvertDto ad = response.Data.FirstOrDefault();

            ViewBag.PhotoData = ad.Photo.Where(p => p.Id == photo_id).FirstOrDefault().Data;
            return(PartialView());
        }
Exemple #3
0
        private static AdvertDto ParseJsonToDto(string content)
        {
            var       jsonObject = JObject.Parse(content);
            AdvertDto advert     = jsonObject.ToObject <AdvertDto>();

            advert.AdvertiserId = (int)jsonObject.SelectToken("advertiser.id");
            advert.CatchTypeId  = (int)jsonObject.SelectToken("catchType.id");
            return(advert);
        }
Exemple #4
0
        private ICommand <Advert> CreateCommandForState(AdvertDto newState)
        {
            if (_queryMediator.Get(newState.Id) == null)
            {
                return((ICommand <Advert>) new CreateAdvertCommand(newState, GetUserId()));
            }

            return((ICommand <Advert>) new UpdateAdvertCommand(newState, GetUserId()));
        }
        public async Task <IActionResult> Create(AdvertDto model)
        {
            var advertId = await _advertStorageService.AddAsync(model);

            var result = new CreateAdvertResponseDto {
                Id = advertId
            };

            return(Created($"adverts/v1/{result.Id}", result));
        }
Exemple #6
0
 private T BuildBaseViewModel <T>(AdvertDto advertData) where T : AdvertViewModel, new()
 {
     return(new T()
     {
         DashboardUrl = _options.Value.DashboardUrl,
         UserName = _userDetails.GetUserName(),
         UserId = _userDetails.GetUserId(),
         AdvertData = advertData
     });
 }
Exemple #7
0
        public async Task <IActionResult> UpdateAdvert([FromBody] AdvertDto advertDto)
        {
            if (advertDto == null)
            {
                return(BadRequest());
            }

            await _iAdvertService.Update(advertDto);

            return(Ok($"Updated advert with name = {advertDto.Name}"));
        }
Exemple #8
0
        public async Task <IActionResult> CreateAdvert([FromBody] AdvertDto advertDto)
        {
            if (advertDto == null)
            {
                return(BadRequest());
            }

            await _iAdvertService.Add(advertDto);

            return(Created("Created new advert", advertDto));
        }
Exemple #9
0
        public async Task <IActionResult> Edit(Guid?advertId)
        {
            var advert = new AdvertDto();

            if (advertId.HasValue)
            {
                advert = await GetAdvert((Guid)advertId);
            }

            return(View(CreateAdvertViewModel <EditAdvertViewModel>(advert)));
        }
Exemple #10
0
 private static void UpdateBaseInfo(Advert advert, AdvertDto dto)
 {
     advert.Name               = dto.Name;
     advert.IsVisible          = dto.IsVisible;
     advert.RequestType        = dto.RequestType;
     advert.ImpressingDateFrom = dto.ImpressingDateFrom;
     advert.ImpressingDateTo   = dto.ImpressingDateTo;
     advert.ImpressingTimeFrom = dto.ImpressingTimeFrom;
     advert.ImpressingTimeTo   = dto.ImpressingTimeTo;
     advert.ImpressingAlways   = dto.ImpressingAlways;
 }
Exemple #11
0
        private static void ValidateInput(AdvertDto fromDto)
        {
            if (fromDto.CatchTypeId == null)
            {
                throw new ArgumentNullException("Catch Type");
            }

            if (fromDto.CatchTypeId == 0)
            {
                throw new ArgumentOutOfRangeException("Catch Type");
            }
        }
Exemple #12
0
        public async Task <List <AdvertResponse> > GetAdverts(AdvertDto advertDto)
        {
            var advertRequest = RestClient.For <IAdvertRequest>(BaseUrl);

            advertRequest.ApiKey = _apiKey;
            //advertRequest.LastHours = advertDto.LastHours;
            advertRequest.LimitAds = 10000;

            var response = await advertRequest.GetAdvertsAsync();

            var result = JsonConvert.DeserializeObject <List <AdvertResponse> >(response);

            return(result);
        }
Exemple #13
0
        public Advert BuildNew(AdvertDto buildData)
        {
            ValidateInput(buildData);

            var resultingAdvert = new Advert(
                buildData.Id,
                LookupItem.GetFromCache <CatchType>(_cache, (int)buildData.CatchTypeId),
                (double)buildData.Price,
                LookupItem.GetFromCache <Advertiser>(_cache, (int)buildData.AdvertiserId));

            resultingAdvert.Pitch         = buildData.Pitch;
            resultingAdvert.FishingMethod = (FishingMethod)(buildData.FishingMethod ?? (int)FishingMethod.Unknown);

            return(resultingAdvert);
        }
Exemple #14
0
        public async Task <ActionResult> Add(AdvertDto advert)
        {
            var ad = _mapper.Map <Advert>(advert);

            try
            {
                ad.Id        = Guid.NewGuid().ToString();
                ad.CreatedAt = DateTime.UtcNow;
                ad.Status    = AdvertStatus.Pending;
                return(Ok(await _advertService.Add(ad)));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        public void SaveAdvert_ThrowsArgumentNull_IfUserIsNull()
        {
            //Arrange
            AdvertDto advert = null;

            //Act
            try
            {
                _advertService.SaveAdvert(advert);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                //Assert
                Assert.IsInstanceOf <ArgumentNullException>(ex);
            }
        }
        public async Task <string> AddAsync(AdvertDto model)
        {
            var dbModel = _mapper.Map <AdvertDbModel>(model);

            dbModel.Id = Guid.NewGuid().ToString();
            dbModel.CreationDateTime = DateTime.UtcNow;
            dbModel.Status           = AdvertStatus.Pending;

            using (var client = new AmazonDynamoDBClient())
            {
                using (var context = new DynamoDBContext(client))
                {
                    await context.SaveAsync(dbModel);
                }
            }

            return(dbModel.Id);
        }
        public void SaveAdvert(AdvertDto advert)
        {
            if (advert == null)
            {
                throw new ArgumentNullException(nameof(advert));
            }

            var advertDal = Mapper.Map <AdvertDto, Advert>(advert);

            if (advertDal.Id == 0)
            {
                advertDal.PublishDate = DateTime.UtcNow;
                _advertRepository.Add(advertDal);
            }
            else
            {
                _advertRepository.Update(advertDal);
            }
        }
Exemple #18
0
        public async Task <Result <Advert> > Create(long userId, Role role, AdvertDto dto, File primaryImage,
                                                    File secondaryImage)
        {
            if (role != Role.Advertiser)
            {
                return(new Error("У вас нет прав на создание кампании", "403"));
            }

            var primaryCreated = primaryImage != null
                ? await _fileRepository.Create(primaryImage.Name, primaryImage.Content)
                : null;

            var secondaryCreated = secondaryImage != null
                ? await _fileRepository.Create(secondaryImage.Name, secondaryImage.Content)
                : null;

            var advert = new Advert
            {
                Name               = dto.Name,
                OwnerId            = userId,
                IsBlocked          = false,
                IsVisible          = dto.IsVisible,
                DateCreated        = DateTime.UtcNow,
                DateUpdated        = DateTime.UtcNow,
                RequestType        = dto.RequestType,
                ImpressingDateFrom = dto.ImpressingDateFrom,
                ImpressingDateTo   = dto.ImpressingDateTo,
                ImpressingTimeFrom = dto.ImpressingTimeFrom,
                ImpressingTimeTo   = dto.ImpressingTimeTo,
                ImpressingAlways   = dto.ImpressingAlways,
                PrimaryImageId     = primaryCreated?.Id,
                SecondaryImageId   = secondaryCreated?.Id,
                AdvertStatistics   = new List <AdvertStatistic>
                {
                    new() { AdvertStatisticType = AdvertStatisticType.Filled },
                    new() { AdvertStatisticType = AdvertStatisticType.Impression },
                    new() { AdvertStatisticType = AdvertStatisticType.Followed },
                }
            };

            return(await _advertRepository.Insert(advert));
        }
Exemple #19
0
        public async Task <Result <Advert> > Update(long userId, Role role, AdvertDto dto, File primaryImage,
                                                    File secondaryImage)
        {
            var advert = await _advertRepository.Get(dto.Id);

            if (advert == null)
            {
                return(new Error("Кампания не найдена", "campaign-not-found"));
            }

            if (!CanAdvertAccessByRole(role) && !UserIsOwner(advert.Owner, userId))
            {
                return(new Error("У вас нет прав на изменение", "403"));
            }

            if (primaryImage != null)
            {
                if (advert.PrimaryImage != null)
                {
                    await _fileRepository.Delete(advert.PrimaryImage);
                }
                var created = await _fileRepository.Create(primaryImage.Name, primaryImage.Content);

                advert.PrimaryImageId = created.Id;
            }

            if (secondaryImage != null)
            {
                if (advert.SecondaryImage != null)
                {
                    await _fileRepository.Delete(advert.SecondaryImage);
                }
                var created = await _fileRepository.Create(secondaryImage.Name, secondaryImage.Content);

                advert.SecondaryImageId = created.Id;
            }

            UpdateBaseInfo(advert, dto);
            advert.DateUpdated = DateTime.UtcNow;
            return(await _advertRepository.Update(advert));
        }
Exemple #20
0
        public IActionResult Put(Guid id, [FromBody] AdvertDto newState)
        {
            // Set the Id from the URI to the DTO to send on
            if (newState.Id == Guid.Empty)
            {
                newState.Id = id;
            }

            // Ensure the posting user is the advertiserId
            newState.AdvertiserId = GetUserId();

            try
            {
                _commandMediator.Send(CreateCommandForState(newState));
                return(Created($"/api/{GetControllerName()}/{id}", _queryMediator.Get(id)));
            }
            catch (System.Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
 public static Infrastructure.Bundles.Advert.Model.Advert MapDtoToAdvert(AdvertDto advert)
 {
     return(new Infrastructure.Bundles.Advert.Model.Advert()
     {
         Title = advert.Title,
         Description = advert.Description,
         Price = advert.Price,
         Status = advert.Status,
         Id = advert.Id.GetValueOrDefault(),
         UserId = advert.UserId.GetValueOrDefault(),
         Car = new Infrastructure.Bundles.Car.Model.Car()
         {
             EngineSize = advert.EngineSize.GetValueOrDefault(),
             Name = advert.Name,
             FuelType = advert.FuelType,
             Mileage = advert.Mileage.GetValueOrDefault(),
             IsBroken = advert.IsBroken,
             IsNew = advert.IsNew,
             HorsePower = advert.HorsePower.GetValueOrDefault(),
         },
     });
 }
Exemple #22
0
 private AdvertViewModel CreateAdvertViewModel <T>(AdvertDto advertData) where T : AdvertViewModel, new()
 {
     advertData.AdvertiserId = _userDetails.GetUserId();
     return(BuildBaseViewModel <T>(advertData));
 }
        public async Task <IActionResult> EditAdvert(UpdateAdvertViewModel advert)
        {
            if (string.IsNullOrEmpty(advert.Header) ||
                advert.CategoryId == 0)
            {
                return(View("Error", new ErrorViewModel {
                    RequestId = "Enter all data"
                }));
            }
            var dto = _mapper.Map <UpdateAdvertDto>(advert);

            if (advert.Photo?.Count > 0)
            {
                List <PhotoDto> photoList = new List <PhotoDto>();
                foreach (var photo in advert.Photo)
                {
                    byte[] p1 = null;
                    using (var fs1 = photo.OpenReadStream())
                        using (var ms1 = new MemoryStream())
                        {
                            fs1.CopyTo(ms1);
                            p1 = ms1.ToArray();
                        }

                    photoList.Add(new PhotoDto {
                        Data = p1
                    });
                }
                dto.Photo = photoList.ToArray();
            }

            var cats = await _categoryApiClient.GetCategoriesAsync();

            IReadOnlyCollection <CategoryDto> _cats = cats.Data;

            ViewBag.Categories = _cats;
            ApiResponse <AdvertDto> response = null;

            try
            {
                response = await _advertApiClient.UpdateAdvertAsync(dto);
            }
            catch (ApplicationException ex) {
                if (ex.Message.Equals("401"))
                {
                    return(Redirect($"~/Home/Logout"));
                }
                else
                {
                    return(View("Error", new ErrorViewModel {
                        RequestId = ex.Message
                    }));
                }
            }

            if (response.HasErrors)
            {
                return(View("Error", new ErrorViewModel {
                    RequestId = response.Errors.FirstOrDefault()
                }));
            }
            AdvertDto result = response.Data;

            return(Redirect($"~/Advert/{result.Id}"));
        }
 public async Task Add(AdvertDto advertDto)
 {
     await _iAdvertRepository.Add(AdvertMapper.MapDtoToAdvert(advertDto));
 }
        public async Task <IActionResult> AddAdvert(NewAdvertViewModel advert)
        {
            advert.UserId = User.Claims.FirstOrDefault(c => c.Type.Contains("nameidentifier")).Value;
            if (string.IsNullOrEmpty(advert.Header) ||
                string.IsNullOrEmpty(advert.Description) ||
                advert.CategoryId == 0)
            {
                return(View("Error", new ErrorViewModel {
                    RequestId = "Enter all data"
                }));
            }

            var dto = _mapper.Map <NewAdvertDto>(advert);

            if (advert.Photo?.Count > 0)
            {
                List <PhotoDto> photoList = new List <PhotoDto>();
                foreach (var photo in advert.Photo)
                {
                    byte[] p1 = null;
                    using (var fs1 = photo.OpenReadStream())
                        using (var ms1 = new MemoryStream())
                        {
                            fs1.CopyTo(ms1);
                            p1 = ms1.ToArray();
                        }

                    photoList.Add(new PhotoDto {
                        Data = p1
                    });
                }
                dto.Photo = photoList.ToArray();
            }



            ApiResponse <AdvertDto> response = null;

            try
            {
                response = await _advertApiClient.AddAdvertAsync(dto);
            }
            catch (ApplicationException ex)
            {
                if (ex.Message.Equals("401"))
                {
                    return(Redirect($"~/Home/Logout"));
                }
                else
                {
                    return(View("Error", new ErrorViewModel {
                        RequestId = ex.Message
                    }));
                }
            }



            if (response.HasErrors)
            {
                return(Ok(response.Errors.FirstOrDefault()));
            }
            AdvertDto result = response.Data;

            return(Redirect($"Advert/{result.Id}"));
        }
 public async Task Update(AdvertDto entity)
 {
     await _iAdvertRepository.Update(AdvertMapper.MapDtoToAdvert(entity));
 }
Exemple #27
0
 public CreateAdvertCommand(AdvertDto advert, int userId) : base(userId)
 {
     Advert = advert;
 }
Exemple #28
0
 public IHttpActionResult Save([FromBody] AdvertDto advert)
 {
     _advertService.SaveAdvert(advert);
     return(Ok());
 }