示例#1
0
        public async Task <IActionResult> CreateAd(CreateAdViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }

            var user = await this.userManager.GetUserAsync(this.User);

            var ad = await this.ads.Find(user.Id);

            if (ad != null)
            {
                return(this.BadRequest());
            }

            var success = await this.ads.CreateAd(
                model.Name,
                model.Description,
                model.AdProfilePicUrl,
                model.Website,
                user.Id);

            if (!success)
            {
                return(this.BadRequest());
            }

            this.TempData.AddSuccessMessage($"Ad {model.Name} has been successfully created.");
            return(this.RedirectToAction("Ad", "Users", new { Area = "", id = 0 }));
        }
        public ActionResult Create(CreateAdViewModel ad)
        {
            if (ModelState.IsValid)
            {
                RealEstateAd realtyAd = _mappingSvc.Map <CreateAdViewModel, RealEstateAd>(ad);
                realtyAd.Id = Guid.NewGuid();
                _adSvc.Add(realtyAd);

                if (ad.PostedImage != null)
                {
                    var userDir  = _server.MapPath(string.Format("~/Content/UserFiles/{0}", _curUserSvc.UserID));
                    var fileName = _fileSvc.UploadFile(ad.PostedImage.InputStream, userDir, ad.PostedImage.FileName, ad.PostedImage.ContentLength);
                    var img      = new Image {
                        RealEstateAd_Id = realtyAd.Id, FileName = Path.GetFileName(fileName)
                    };
                    _imgSvc.Add(img);
                }
                //no need to commit _imgService since DbContext is global per request using IOC lifetime manager
                _adSvc.Commit();
            }
            else
            {
                ad.Cities = new SelectList(_citySvc.GetAll(), "Id", "Name");
                return(View(ad));
            }

            return(RedirectToAction("Index", new { userId = _curUserSvc.UserID }));
        }
        public void Create_Controller_Returns_View_To_Index_When_Model_Is_Not_Valid()
        {
            var adService      = new Mock <RealEstateAdService>(It.IsAny <IApplicationDbContext>());
            var cityService    = new Mock <CityService>(It.IsAny <IApplicationDbContext>());
            var imgService     = new Mock <RealEstateImageService>(It.IsAny <IApplicationDbContext>());
            var fileService    = new Mock <UserFileService>();
            var mappingService = new Mock <MappingService>();
            var server         = new Mock <HttpServerUtilityBase>();
            var curUserSvc     = new Mock <CurrentUserService>();

            var controller = new RealEstateAdController(adService.Object, cityService.Object,
                                                        imgService.Object, fileService.Object, curUserSvc.Object, mappingService.Object, server.Object);

            var ad = new CreateAdViewModel()
            {
                Title = "The New Mansion"
            };

            //Simulate validation otherwise ModelState.IsValid will always be true
            controller.ModelState.AddModelError("Error", "Title is incorrect");
            var view = controller.Create(ad) as ViewResult;

            Assert.IsNotNull(view);
            Assert.AreEqual(view.Model, ad, "Failed");
        }
        public ActionResult Create()
        {
            var adModel = new CreateAdViewModel();

            adModel.Cities = new SelectList(_citySvc.GetAll(), "Id", "Name");
            return(View(adModel));
        }
示例#5
0
        public async Task <IActionResult> CreateAd()
        {
            var categories = await categoryService.GetAll();

            var model = new CreateAdViewModel();

            model.Categories = this.mapper.Map <List <CategoryViewModel> >(categories);
            return(View(model));
        }
示例#6
0
 public Ad ToAd(CreateAdViewModel model)
 {
     return(new Ad
     {
         Title = model.Title,
         Description = model.Description,
         Price = model.Price
     });
 }
        public ActionResult Create()
        {
            CreateAdViewModel model = new CreateAdViewModel();

            model.bikeBrands      = bikeBrandRepo.GetAll().ToList();
            model.bikeCategories  = bikeCategoryRepo.GetAll().ToList();
            model.bikeEngineTypes = bikeEngineTypeRepo.GetAll().ToList();
            model.regions         = regionRepo.GetAll().ToList();
            model.bikeColors      = bikeColorRepo.GetAll().ToList();

            return(View("CreateAd", model));
        }
示例#8
0
        public async Task <IActionResult> CreateAd(CreateAdViewModel model)
        {
            var categories = await categoryService.GetAll();

            model.Categories = this.mapper.Map <List <CategoryViewModel> >(categories);
            if (ModelState.IsValid)
            {
                var user = await userManager.GetUserAsync(httpContextAccessor.HttpContext.User);

                var creatAdDto = this.mapper.Map <CreateAdDTO>(model);
                var result     = await adService.CreateAd(creatAdDto, user.Id);
            }
            return(this.View(model));
        }
示例#9
0
        public async Task <IActionResult> Create([Bind("Title,Description,AdType")] CreateAdViewModel advw)
        {
            if (ModelState.IsValid)
            {
                var ad = new Ad
                {
                    Description = advw.Description,
                    Title       = advw.Title,
                    AdType      = _context.AdTypes.FirstOrDefault(x => x.Type == advw.AdType),
                };
                _context.Add(ad);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(advw));
        }
示例#10
0
        //create new Product model from data in view model.
        public Product CreateNewProductFromViewModelAndUser(CreateAdViewModel vm, User owner)
        {
            var product = new Product()
            {
                Title            = vm.Title,
                Owner            = owner,
                ShortDescription = vm.ShortDescription,
                LongDescription  = vm.LongDescription,
                Date             = DateTime.Now,
                Price            = vm.Price,
                Picture1         = vm.Picture1,
                Picture2         = vm.Picture2,
                Picture3         = vm.Picture3
            };

            return(product);
        }
示例#11
0
        // GET: Ad/Create
        public async Task <IActionResult> Create()
        {
            string accountId = _userManager.GetUserId(HttpContext.User);

            CreateAdViewModel viewModel = new CreateAdViewModel
            {
                Ad = new Ad()
                {
                    UserAccountID = _context.UserAccounts.Where(a => a.UserID == accountId).FirstOrDefault().UserAccountID
                },
                StatusList     = await _context.RealEstateStatuses.ToListAsync(),
                Towns          = new SelectList(_context.Towns, "TownID", "Name"),
                Types          = new SelectList(_context.RealEstateTypes, "RealEstateTypeID", "Name"),
                SelectedStatus = 1
            };

            return(View(viewModel));
        }
示例#12
0
        public async Task <IActionResult> Create(CreateAdViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                viewModel.Ad.DateInit           = DateTime.Now;
                viewModel.Ad.RealEstateStatusID = viewModel.SelectedStatus;
                _context.Add(viewModel.Ad);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            viewModel.StatusList = await _context.RealEstateStatuses.ToListAsync();

            viewModel.Towns = new SelectList(_context.Towns, "TownID", "Name");
            viewModel.Types = new SelectList(_context.RealEstateTypes, "RealEstateTypeID", "Name");

            return(View(viewModel));
        }
        public ActionResult ViewEditAd(int id)
        {
            var modelCreateAdViewModel = new CreateAdViewModel();

            var modelAdvertisement = advertisementRepo.GetById(id);

            if (!(User.FindFirstValue(ClaimTypes.NameIdentifier).Equals(modelAdvertisement.userId)))
            {
                Response.StatusCode = 403;
                return(View("~/Views/ErrorPages/Error403.cshtml"));
            }

            modelAdvertisement.bikeModel           = bikeModelRepo.GetById(modelAdvertisement.modelId);
            modelAdvertisement.bikeModel.bikeBrand = bikeBrandRepo.GetById(modelAdvertisement.bikeModel.brandID);
            modelAdvertisement.bikeCategory        = bikeCategoryRepo.GetById(modelAdvertisement.categoryId);
            modelAdvertisement.city      = cityRepo.GetById(modelAdvertisement.cityId);
            modelAdvertisement.bikeColor = bikeColorRepo.GetById(modelAdvertisement.colorId);

            modelCreateAdViewModel.bikeBrands      = bikeBrandRepo.GetAll().ToList();
            modelCreateAdViewModel.bikeCategories  = bikeCategoryRepo.GetAll().ToList();
            modelCreateAdViewModel.bikeEngineTypes = bikeEngineTypeRepo.GetAll().ToList();
            modelCreateAdViewModel.regions         = regionRepo.GetAll().ToList();
            modelCreateAdViewModel.bikeColors      = bikeColorRepo.GetAll().ToList();

            ViewBag.AdvertisementId = id;
            ViewBag.StringImage     = modelAdvertisement.photoPath;
            modelCreateAdViewModel.advertisementUserId    = modelAdvertisement.userId;
            modelCreateAdViewModel.description            = modelAdvertisement.description;
            modelCreateAdViewModel.selectedBikeModel      = modelAdvertisement.modelId;
            modelCreateAdViewModel.selectedBikeBrand      = modelAdvertisement.bikeModel.brandID;
            modelCreateAdViewModel.bikeHorsePower         = modelAdvertisement.horsePower;
            modelCreateAdViewModel.selectedBikeEngineType = modelAdvertisement.engineTypeId;
            modelCreateAdViewModel.bikeEngineSize         = modelAdvertisement.engineSize;
            modelCreateAdViewModel.bikePrice            = modelAdvertisement.price;
            modelCreateAdViewModel.selectedBikeCategory = modelAdvertisement.categoryId;
            modelCreateAdViewModel.bikeYear             = modelAdvertisement.productionYear;
            modelCreateAdViewModel.bikeMileage          = modelAdvertisement.mileage;
            modelCreateAdViewModel.selectedRegion       = modelAdvertisement.city.regionID;
            modelCreateAdViewModel.selectedCity         = modelAdvertisement.cityId;
            modelCreateAdViewModel.selectedBikeColor    = modelAdvertisement.colorId;

            return(View("EditAd", modelCreateAdViewModel));
        }
        public void Create_Controller_Redirects_To_Index_When_Model_Is_Valid()
        {
            //Arrange
            var controller = new RealEstateAdController(_adSvc.Object, _citySvc.Object,
                                                        _imgSvc.Object, _fileSvc.Object, _curUserSvc.Object, _mappingSvc.Object, _server.Object);
            var ad = new CreateAdViewModel()
            {
                Title = "The New Mansion", PostedImage = _postedFile.Object
            };
            //Act
            var view = controller.Create(ad) as RedirectToRouteResult;

            //Assert

            _adSvc.Verify(a => a.Add(It.IsAny <RealEstateAd>()), Times.Once, "Failed to call Add method of adService");
            _fileSvc.Verify(f => f.UploadFile(It.IsAny <Stream>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()), Times.Once, "Failed to call UploadFile");
            _mappingSvc.Verify(m => m.Map <CreateAdViewModel, RealEstateAd>(It.IsAny <CreateAdViewModel>()), Times.Once, "Failed to call mapper");
            _imgSvc.Verify(i => i.Add(It.IsAny <Image>()), Times.Once);
            Assert.IsNotNull(view, "Controller does not redirect");
        }
示例#15
0
        public static void MapToDto(this PolicyDto policyDto, CreateAdViewModel createAdViewModel)
        {
            policyDto.Id = createAdViewModel.Id == null ? int.MinValue : createAdViewModel.Id.Value;

            policyDto.Category.MapToDto(createAdViewModel.Category);
            policyDto.SubCategory.MapToDto(createAdViewModel.SubCategory);
            policyDto.Province.MapToDto(createAdViewModel.Province);
            policyDto.City.MapToDto(createAdViewModel.City);

            if (createAdViewModel.RegisterUser != null)
            {
                policyDto.CreateUser.MapToDto(createAdViewModel.RegisterUser);
            }
            else
            {
                policyDto.CreateUser = new UserDto {
                    Id = createAdViewModel.CreateUserId.Value
                };
            }

            foreach (PolicyImageViewModel policyImageViewModel in createAdViewModel.PolicyImages)
            {
                PolicyImageDto policyImage = new PolicyImageDto();
                policyImage.MapToDto(policyImageViewModel);
                policyDto.PolicyImages.Add(policyImage);
            }

            foreach (PolicySubCategoryAdditionalFieldViewModel policySubCategoryAdditionalFieldViewModel in createAdViewModel.PolicySubCategoryAdditionalFields)
            {
                PolicySubCategoryAdditionalFieldDto policySubCategoryAdditionalFieldDto = new PolicySubCategoryAdditionalFieldDto();

                policySubCategoryAdditionalFieldDto.MapToDto(policySubCategoryAdditionalFieldViewModel);
                policyDto.PolicySubCategoryAdditionalFields.Add(policySubCategoryAdditionalFieldDto);
            }

            policyDto.Subject       = createAdViewModel.Subject;
            policyDto.Description   = createAdViewModel.Description;
            policyDto.NegotiableInd = createAdViewModel.NegotiableInd;
            policyDto.OfferType     = createAdViewModel.OfferType;
            policyDto.Price         = Converter.StringToDecimal(createAdViewModel.Price);
        }
示例#16
0
        public PolicyViewModel CreateAd(CreateAdViewModel model)
        {
            PolicyDto policy = new PolicyDto();

            policy.MapToDto(model);

            Response <PolicyDto> response = EntityFactory.PolicyManager.SavePolicy(policy, CrudStatus.CREATE);

            if (response.HasErrors)
            {
                ModelStateException modelStateException = new ModelStateException();
                response.ErrorMessages.ToList().ForEach(item => modelStateException.ModelErrors.Add(new ModelStateError()
                {
                    FieldName = item.FieldName, Message = item.Message
                }));

                throw modelStateException;
            }

            return(response.Model.MapFromDto());
        }
示例#17
0
        public IActionResult SaveAd(CreateAdViewModel vm, IFormFile Picture1, IFormFile Picture2, IFormFile Picture3)
        {
            //if model from form is not complete, redirects back to CreateAd view.
            if (!ModelState.IsValid)
            {
                return(View("CreateAd", vm));
            }

            //converts pic to array.
            vm.Picture1 = _productsManagement.ConvertPicToByteArray(Picture1);

            vm.Picture2 = _productsManagement.ConvertPicToByteArray(Picture2);

            vm.Picture3 = _productsManagement.ConvertPicToByteArray(Picture3);

            //get the signed in user as the owner.
            var owner = _db.UserRepository.Get(_um.GetUser().Id);

            //translate viewmodel into database model.
            var product = _productsManagement.CreateNewProductFromViewModelAndUser(vm, owner);

            //tries to update database.
            if (!_db.ProductsRepository.Create(product))
            {
                //flag to change view if saving in the database fails.
                ViewBag.Success = false;
            }
            else
            {
                //create a new log entry for the newly created product.
                LogEntry log = new LogEntry()
                {
                    Content   = $"Ad: {product.Title} was created by {owner.UserName}",
                    TimeStamp = DateTime.Now
                };
                _db.LogEntryRepository.Create(log);
                ViewBag.Success = true;
            }
            return(View());
        }
示例#18
0
        public void LoadView(MainWindowViewType typeView)
        {
            switch (typeView)
            {
            case MainWindowViewType.Main:
                //загружаем вьюшку, ее вьюмодель
                HomePage          view = new HomePage();
                HomePageViewModel vm   = new HomePageViewModel(this);
                //связываем их м/собой
                view.DataContext = vm;
                //отображаем
                this.OutputView.Content = view;
                break;

            case MainWindowViewType.CreateAd:
                CreateAdPage      viewCreateAd = new CreateAdPage();
                CreateAdViewModel vmCreateAd   = new CreateAdViewModel(this);
                viewCreateAd.DataContext = vmCreateAd;
                this.OutputView.Content  = viewCreateAd;
                break;
            }
        }
        public ActionResult Create(CreateAdViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("CreateAd"));
            }

            string uniqueFileName;

            if (model.photo != null)
            {
                uniqueFileName = FileUpload.ProcessUploadedFile(model.photo, hostingEnvironment, "images");
            }
            else
            {
                uniqueFileName = "default-ad-image.png";
            }

            Advertisement advertisement = new Advertisement
            {
                modelId        = model.selectedBikeModel,
                horsePower     = model.bikeHorsePower,
                engineSize     = model.bikeEngineSize,
                engineTypeId   = model.selectedBikeEngineType,
                productionYear = model.bikeYear,
                mileage        = model.bikeMileage,
                price          = model.bikePrice,
                cityId         = model.selectedCity,
                colorId        = model.selectedBikeColor,
                categoryId     = model.selectedBikeCategory,
                description    = model.description,
                userId         = User.FindFirstValue(ClaimTypes.NameIdentifier),
                photoPath      = uniqueFileName
            };

            advertisementRepo.Insert(advertisement);

            return(RedirectToAction("view", new { id = advertisement.id }));
        }
        public ActionResult ViewEditAd(CreateAdViewModel model, int id)
        {
            if (!ModelState.IsValid)
            {
                return(View("EditAd"));
            }

            var advertisement = advertisementRepo.GetById(id);

            string uniqueFileName;

            if (model.photo != null)
            {
                uniqueFileName = FileUpload.ProcessUploadedFile(model.photo, hostingEnvironment, "images");
            }
            else
            {
                uniqueFileName = advertisement.photoPath;
            }

            advertisement.modelId        = model.selectedBikeModel;
            advertisement.horsePower     = model.bikeHorsePower;
            advertisement.engineSize     = model.bikeEngineSize;
            advertisement.engineTypeId   = model.selectedBikeEngineType;
            advertisement.productionYear = model.bikeYear;
            advertisement.mileage        = model.bikeMileage;
            advertisement.price          = model.bikePrice;
            advertisement.cityId         = model.selectedCity;
            advertisement.colorId        = model.selectedBikeColor;
            advertisement.categoryId     = model.selectedBikeCategory;
            advertisement.description    = model.description;
            advertisement.photoPath      = uniqueFileName;

            advertisementRepo.Update(advertisement);

            return(RedirectToAction("view", new { id = advertisement.id }));
        }
        public async Task <IActionResult> Create(CreateAdViewModel model, IFormFile imageFile)
        {
            if (ModelState.IsValid)
            {
                var ad = _mapper.ToAd(model);
                ad.Username = GetUsername();
                var createResponse = await _client.CreateAsync(ad);

                var id       = createResponse.Id;
                var filePath = string.Empty;

                if (imageFile != null)
                {
                    var bucket   = _configuration.GetValue <string>("ImageBucket");
                    var fileName = !string.IsNullOrEmpty(imageFile.FileName) ? Path.GetFileName(imageFile.FileName) : id;
                    filePath = $"{id}/{fileName}";

                    try
                    {
                        using (var readStream = imageFile.OpenReadStream())
                        {
                            var result = await _fileUploader.UploadFileAsync(filePath, readStream, bucket)
                                         .ConfigureAwait(false);

                            if (!result)
                            {
                                throw new Exception(
                                          "Could not upload the image to file repository. Please see the logs for details.");
                            }
                        }

                        var isConfirmed = await _client.ConfirmAsync(new ConfirmRequest {
                            Id       = id,
                            FilePath = filePath,
                            Status   = AdApi.Shared.Models.AdStatus.Active
                        });

                        if (!isConfirmed)
                        {
                            throw new Exception($"Cannot confirm ad id = {id}");
                        }

                        return(RedirectToAction("Index", "Home"));
                    }
                    catch (Exception e)
                    {
                        await _client.ConfirmAsync(new ConfirmRequest {
                            Id       = id,
                            FilePath = filePath,
                            Status   = AdApi.Shared.Models.AdStatus.Pending
                        });

                        Console.WriteLine(e.Message);
                        _logger.LogError($"{nameof(AdManagementController)} : {e.Message}");
                    }
                }

                return(RedirectToAction("Index", "Home"));
            }

            return(View(model));
        }
 public IActionResult Create(CreateAdViewModel model)
 {
     ViewBag.Current = "Create";
     _logger.LogInformation(nameof(AdManagementController));
     return(View(model));
 }