public ICollection <string> ValidateCar(AddCarViewModel model) { var errors = new List <string>(); if (model.Model.Length < ModelMinLength || model.Model.Length > ModelMaxLength) { errors.Add($"Car's model name must be between {ModelMinLength} and {ModelMaxLength} characters."); } if (model.Year < 1900 || model.Year > 2021) { errors.Add("Car's year must be in range 1900 - 2021."); } if (String.IsNullOrWhiteSpace(model.Url)) { errors.Add("The Url must be a valid url."); } if (!Regex.IsMatch(model.PlateNumber, @"[A-Z]{2}[0-9]{4}[A-Z]{2}")) { errors.Add("The Plate Number must be in format 'AA0000AA'"); } return(errors); }
public async Task <bool> CreateCar(AddCarViewModel model, ApplicationUser user) { Enum.TryParse(model.Fuel, out Fuel fuel); Enum.TryParse(model.Fuel, out Transmission transmission); Enum.TryParse(model.Fuel, out VehicleType vehicleType); var car = new Car() { Brand = model.CarBrand, Model = model.CarModel, ImageUrl = model.ImageUrl, Kilometre = model.Kilometre, Transmission = transmission, Color = model.Color, VehicleType = vehicleType, AdTitle = model.AdTitle, CreatedOn = DateTime.UtcNow, Description = model.Description, Price = model.Price, YearOfProduction = model.YearOfProduction, Fuel = fuel, Hp = model.Hp, ApplicationUserId = user.Id, CarOwner = user }; await this.context.Cars.AddAsync(car); var isSuccessful = await this.context.SaveChangesAsync(); return(isSuccessful > 0 ? true : false); }
public IEnumerable <string> AddCarValidateErrors(AddCarViewModel viewModel) { var errorList = new List <string>(); if (viewModel.Model.Length < 5 || viewModel.Model.Length > 20) { errorList.Add("Model must be between 5 and 20 characters long."); } if (!Regex.IsMatch(viewModel.PlateNumber, @"[A-Z]{2}[0-9]{4}[A-Z]{2}")) { errorList.Add("PlateNumber must be in format 'AA1111AA'."); } if (String.IsNullOrEmpty(viewModel.Year.ToString())) { errorList.Add("Field 'Year' is required."); } if (String.IsNullOrEmpty(viewModel.Image)) { errorList.Add("Field 'Image' is required."); } return(errorList); }
public AddCarDialog(AddCarViewModel viewModel) { viewModel.ThisWindow = this; DataContext = viewModel; InitializeComponent(); }
public async Task DeleteCar() { var options = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase("delete_car").Options; var dbContext = new ApplicationDbContext(options); var imageService = new ImageService(dbContext); var carService = new CarService(dbContext, imageService); AutoMapperConfig.RegisterMappings(typeof(CarViewModel).Assembly, typeof(Car).Assembly); var car = new AddCarViewModel() { FuelType = FuelType.Diesel, Made = "Honda", Transmission = TransmissionType.Automatic, Places = CarPlaces.Four, Category = CarCategory.Sedan, FuelConsumption = 5.0, Model = "Civic", PriceForHour = 21, Description = "Something", }; var addedCar = await carService.AddVehicle <AddCarViewModel>(car); await carService.Delete(addedCar); var cars = carService.GetAll <CarViewModel>(false); Assert.Empty(cars.ToList()); }
public async Task <ActionResult> AddCar([FromBody] AddCarViewModel carAd) { if (carAd == null) { return(this.BadRequest("The input model cannot be null")); } var userId = this.Request.Headers["UserId"]; if (string.IsNullOrWhiteSpace(userId)) { return(this.BadRequest("The user id cannot be empty")); } var user = await this.userManager.FindByIdAsync(userId); if (user == null) { return(this.Unauthorized()); } var isSuccessful = await this._carService.CreateCar(carAd, user); if (!isSuccessful) { return(this.BadRequest()); } return(this.Ok(isSuccessful)); }
public async Task AddImageToCar() { var options = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase("add_image_car").Options; var dbContext = new ApplicationDbContext(options); var imageService = new ImageService(dbContext); var carService = new CarService(dbContext, imageService); AutoMapperConfig.RegisterMappings(typeof(BicycleViewModel).Assembly, typeof(Bicycle).Assembly); AutoMapperConfig.RegisterMappings(typeof(EditBicycleViewModel).Assembly, typeof(Bicycle).Assembly); var car = new AddCarViewModel() { FuelType = FuelType.Diesel, Made = "Honda", Transmission = TransmissionType.Automatic, Places = CarPlaces.Four, Category = CarCategory.Sedan, FuelConsumption = 5.0, Model = "Civic", PriceForHour = 21, Description = "Something", }; var imagePath = "Test"; var addedCar = await carService.AddVehicle <AddCarViewModel>(car); await carService.AddImageUrls(addedCar, imagePath); var result = carService.EditDetails <CarViewModel>(addedCar); Assert.Equal(imagePath, result.ImageUrl); }
public IEnumerable <string> CarValidator(AddCarViewModel input) { if (input.Model == null) { this.errorMessage.Add(string.Format(REQUIRED, "model")); } else if (input.Model.Length < 5 || input.Model.Length > 20) { this.errorMessage.Add(string.Format(MaxMinLength, "Model")); } if (input.Year == 0) { this.errorMessage.Add(string.Format(REQUIRED, "year")); } if (input.PlateNumber == null) { this.errorMessage.Add(string.Format(REQUIRED, "plate number")); } string plateNumber = @"[A-Z]{2}[0-9]{4}[A-Z]{2}$"; Match matches = Regex.Match(input.PlateNumber, plateNumber); if (matches == null) { this.errorMessage.Add(plateNumber); } return(this.errorMessage); }
public ActionResult AddVehicle() { var model = new AddCarViewModel().Populate(); model.Car = new CarModel(); return(View(model)); }
public ActionResult NewCar(int personId) { var vm = new AddCarViewModel(); var repo = new PersonRepository(Properties.Settings.Default.ConStr); vm.Person = repo.GetPerson(personId); return(View(vm)); }
public ActionResult Index() { AddCarViewModel cModel = new AddCarViewModel() { Id = 0 }; return(View(cModel)); }
public IActionResult SaveCar(AddCarViewModel viewModel) { var car = mapper.Map <Car>(viewModel.CarDto); car.Manufacturer = manufacturerRepo.Get(car.Manufacturer.Id); carRepo.Add(car); return(RedirectToAction("Index")); }
public ActionResult AddCar(AddCarViewModel car, HttpPostedFileBase file) { if (!ModelState.IsValid || file == null) { return(View(ModelState)); } var carToAdd = Mapper.Map <Car>(car); if (Path.GetExtension(file.FileName).ToLower() == ".jpg" || Path.GetExtension(file.FileName).ToLower() == ".png" || Path.GetExtension(file.FileName).ToLower() == ".gif" || Path.GetExtension(file.FileName).ToLower() == ".jpeg") { var path = Path.Combine(Server.MapPath("~/Images"), file.FileName); file.SaveAs(path); carToAdd.PicturePath = file.FileName; } try { var userId = User.Identity.GetUserId(); var currentUser = this.Data .Users .All() .SingleOrDefault(x => x.Id == userId); //carToAdd.Brand = car.Brand; //carToAdd.Mileage = car.Mileage; //carToAdd.DateManufacturer = car.Year; this.Data.Cars.Add(carToAdd); carToAdd.CarModelsId = car.CarModelsId; this.Data.SaveChanges(); return(RedirectToAction("ViewAllCars", "Car")); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); raise = new InvalidOperationException(message, raise); } } throw raise; } }
public ActionResult EditVehicle(AddCarViewModel model) { if (ModelState.IsValid) { DataManager.Instance.EditCar(model.Car); return(RedirectToAction("Vehicles")); } // if we got here then the model is invalid return(View(model.Populate())); }
public ActionResult AddCar() { AddCarViewModel vm = new AddCarViewModel(); tblCarsService cservice = new tblCarsService(); tblColorsService colservice = new tblColorsService(); tblBrandsService bservice = new tblBrandsService(); vm.brandChoice = bservice.getBrands(); vm.colorChoice = colservice.getColors(); return(View(vm)); }
public ActionResult Update(AddCarViewModel model) { if (!ModelState.IsValid) { return(View(model)); } _carService.Update(Mapper.Map <CarModelWithDrivers>(model)); this.FlashSuccess("Данные успешно обновленны"); return(RedirectToAction("Index")); }
public ActionResult Edit(int CarId) { var carInDb = _context.Cars.SingleOrDefault(c => c.Id == CarId); var ModelId = _context.ManufacturerModels.Where(m => m.Name == carInDb.Model).SingleOrDefault().Id; var imagesInDb = _context.Images.Where(i => i.CarId == CarId).ToList(); var CarEdit = new AddCarViewModel(carInDb, imagesInDb, ModelId); return(View("Index", CarEdit)); }
public IActionResult AddCar(AddCarViewModel input) { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); if (!ModelState.IsValid) { return(this.View(new AddCarViewModel(dbContext))); } this.offerService.AddCar(input, userId); return(this.Redirect("/Cars/AllCars")); }
public IActionResult AddCar() { var manufacturersFromRepo = manufacturerRepo.GetAll(); var manufacturersDto = mapper.Map <IEnumerable <ManufacturerDto> >(manufacturersFromRepo); var viewModel = new AddCarViewModel { CarDto = new CarForCreationDto(), Manufacturers = manufacturersDto }; return(View(viewModel)); }
public IActionResult AddCar([FromForm] AddCarViewModel model) { if (!ModelState.IsValid) { return(BadRequest()); } adminsService.AddCar(model.CarType, model.CivSeries, model.BodySeries, model.CarMileage, model.YearOfManufacture, model.ItpValability, model.OwnerFirstName, model.OwnerLastName, model.OwnerCNP); return(Redirect(Url.Action("Index", "Admins"))); }
public ActionResult EditVehicle(int id) { var car = DataManager.Instance.GetCarById(id); if (car == null) { return(RedirectToAction("Vehicles")); } var model = new AddCarViewModel().Populate(); model.Car = car; return(View(model)); }
public ActionResult AddCar(AddCarViewModel vm) { tblCarsService cservice = new tblCarsService(); tblColorsService colservice = new tblColorsService(); tblBrandsService bservice = new tblBrandsService(); tblCars car = new tblCars(); car.BrandID = vm.selectedBrandId; car.ColorID = vm.selectedColorId; car.CarModel = vm.car.CarModel; car.CarDescription = vm.car.CarDescription; car.CarFuel = vm.fuelChoice.ToString(); car.CarKilometers = vm.car.CarKilometers; car.CarPrice = vm.car.CarPrice; car.CarEquipment = vm.car.CarEquipment; car.CarYearOfConstruction = vm.car.CarYearOfConstruction; car.Sold = (byte)0; car.C02Emissions = vm.car.C02Emissions; car.PowerKW = vm.car.PowerKW; car.PowerPK = vm.car.PowerPK; car.CylinderCapacity = vm.car.CylinderCapacity; car.FirstRegistration = vm.car.FirstRegistration; car.Transmission = vm.transmissionChoice.ToString(); car.Createdate = DateTime.Now.Date; cservice.addCar(car); List <HttpPostedFileBase> files = vm.files.ToList(); for (int i = 0; i < files.Count(); i++) { if (files.ElementAt(i) != null && files.ElementAt(i).ContentLength > 0) { tblImages Image = new tblImages(); System.Diagnostics.Debug.WriteLine("image"); Image.CarID = car.CarID; Image.ImageOrder = i; Image.ImagePath = @"Cars\Car" + car.CarID + @"\Image"; tblImagesService iservice = new tblImagesService(); iservice.AddImage(Image); Image.ImagePath = @"Cars/Car" + car.CarID + @"/Image" + Image.ImageID + ".jpg"; iservice.UpdateImage(Image); CSCBelgiumCloudService cloudservice = new CSCBelgiumCloudService(); cloudservice.UploadImageAsBlob(Image, files.ElementAt(i)); } else { Debug.WriteLine("file null"); } } return(RedirectToAction("CarIndex")); }
public void AddCar(AddCarViewModel viewModel, string userId) { var car = new Car { Model = viewModel.Model, OwnerId = userId, PictureUrl = viewModel.Image, PlateNumber = viewModel.PlateNumber, Year = viewModel.Year, }; dbContext.Cars.Add(car); dbContext.SaveChanges(); }
public void AddCar(AddCarViewModel model, string userId) { Car car = new Car() { Model = model.Model, Year = model.Year, PlateNumber = model.PlateNumber, PictureUrl = model.Url, OwnerId = userId }; this.db.Cars.Add(car); this.db.SaveChanges(); }
public HttpResponse Add(AddCarViewModel input) { var errorsMessage = this.validator.CarValidator(input); if (errorsMessage.Any()) { return(this.Error(errorsMessage)); } input.OwnerId = this.User.Id; this.carService.AddCar(input); return(this.Redirect("/Cars/All")); }
public HttpResponse Add(AddCarViewModel model) { var userId = this.User.Id; var errors = this.carsService.ValidateCar(model); if (errors.Any()) { return(this.Error(errors)); } this.carsService.AddCar(model, userId); return(this.Redirect("/Cars/All")); }
public void AddCar(AddCarViewModel input) { var car = new Car() { Model = input.Model, Year = input.Year, PictureUrl = input.Image, PlateNumber = input.PlateNumber, OwnerId = input.OwnerId, Owner = this.db.Users.FirstOrDefault(u => u.Id == input.OwnerId), }; this.db.Cars.Add(car); this.db.SaveChanges(); }
public ActionResult AddCar(AddCarViewModel model) { Car car = new Car(); car = model.Car; if (Request.Files[0].FileName == "" || car.BrandId < 1 || car.ModelYear < 1900 || car.Power < 1 || car.Price < 1 || car.Color == null || car.FuelType == null || car.FuelType == null || car.GearBox == null || car.Model == null || model.ImageUpload.Count() < 1) { TempData["AddCarError"] = "Lütfen tüm bilgileri eksiksiz doldurup tekrar deneyin."; return(View(_addModel)); } List <string> imagePaths = new List <string>(); foreach (var image in model.ImageUpload) { if (image.ContentType != "image/jpeg" && image.ContentType != "image/jpg" && image.ContentType != "image/png") { TempData["AddCarError"] = "İlan fotoğrafları '.jpg', '.jpeg' veya '.png' dosya türünde olmalıdır."; return(View(_addModel)); } var path = Path.Combine(Server.MapPath("/Content/images/cars/"), image.FileName); string uploadPath = ConfigurationManager.AppSettings["ImagePath"].ToString(); imagePaths.Add(uploadPath + image.FileName); image.SaveAs(path); } if (imagePaths.Count() > 0) { car.CarPhoto1 = imagePaths[0]; } if (imagePaths.Count() > 1) { car.CarPhoto2 = imagePaths[1]; } if (imagePaths.Count() > 2) { car.CarPhoto3 = imagePaths[2]; } car.ListDate = DateTime.Now; _context.Car.Add(car); _context.SaveChanges(); TempData["AddCarMessage"] = "İlan başarıyla yayınlandı."; return(RedirectToAction("Index")); }
public async Task EditCarShouldEdit() { var options = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase("Edit_Car").Options; var dbContext = new ApplicationDbContext(options); var imageService = new ImageService(dbContext); var carService = new CarService(dbContext, imageService); AutoMapperConfig.RegisterMappings(typeof(AddCarViewModel).Assembly, typeof(Car).Assembly); AutoMapperConfig.RegisterMappings(typeof(EditCarViewModel).Assembly, typeof(Car).Assembly); var addCar = new AddCarViewModel() { FuelType = FuelType.Diesel, Made = "Honda", Transmission = TransmissionType.Automatic, Places = CarPlaces.Four, Category = CarCategory.Sedan, FuelConsumption = 5.0, Model = "Civic", PriceForHour = 21, Description = "Something", }; var addedBycicle = await carService.AddVehicle <AddCarViewModel>(addCar); var editCar = new EditCarViewModel() { Id = addedBycicle, FuelType = FuelType.Diesel, Made = "Peugeot", Transmission = TransmissionType.Automatic, Places = CarPlaces.Four, Category = CarCategory.Sedan, FuelConsumption = 5.0, Model = "Civic", PriceForHour = 21, Description = "Something", }; await carService.DoEdit <EditCarViewModel>(editCar); var editCarResult = carService.EditDetails <EditCarViewModel>(addedBycicle); Assert.Equal("Peugeot", editCarResult.Made); }
public ActionResult Create(AddCarViewModel m) { //var v = Request.Params; if (ModelState.IsValid) { var user = User.Identity.GetUserId(); byte[] content = null; string fileExtension = null; if (m.UploadedImage != null) { using (var memory = new MemoryStream()) { m.UploadedImage.InputStream.CopyTo(memory); content = memory.GetBuffer(); fileExtension = m.UploadedImage.FileName.Split(new[] { '.' }).Last(); } } Car car = new Car { Price = m.Price, Model = new CarModel { Name = m.ModelName, Year = m.ModelYear, Brand = new Brand { Name = m.BrandName } }, Color = m.Color, Mileage = m.Mileage, Transmission = m.Transmission, Fuel = m.Fuel, NumberOfCylinders = m.NumberOfCylinders, SellerNotes = m.SellerNotes, ListingDate = DateTime.Now, SellerId = user, Image = new Image { Content = content, FileExtension = fileExtension } }; this.Data.Cars.Add(car); this.Data.SaveChanges(); } return(RedirectToAction("Index", "Home")); }
public ActionResult Create(AddCarViewModel m) { var v = Request.Params; if (ModelState.IsValid) { var user = User.Identity.GetUserId(); byte[] content = null; string fileExtension = null; if (m.UploadedImage != null) { using (var memory = new MemoryStream()) { m.UploadedImage.InputStream.CopyTo(memory); content = memory.GetBuffer(); fileExtension = m.UploadedImage.FileName.Split(new[] { '.' }).Last(); } } Car car = new Car { Price = m.Price, Model = new CarModel { Name = m.ModelName, Year = m.ModelYear, Brand = new Brand { Name = m.BrandName } }, Color = m.Color, Mileage = m.Mileage, Transmission = m.Transmission, Fuel = m.Fuel, NumberOfCylinders = m.NumberOfCylinders, ListingDate = DateTime.Now, SellerId = user, Image = new Image { Content = content, FileExtension= fileExtension} }; this.Data.Cars.Add(car); this.Data.SaveChanges(); } return RedirectToAction("Index", "Home"); }
public ActionResult Create() { var model = new AddCarViewModel(); return View(model); }