public Journey AddJourney(string userId, JourneyForCreationDto journey, CarDto car) { journey.UserId = userId; journey.CarId = car.Id; var journeyToSave = Mapper.Map <Journey>(journey); if (car == null) { throw new Exception("Car does not exist"); } journeyToSave.PassengerRoutes.ForEach(pr => pr.SetDestination(journeyToSave.Destination)); _journeyRepository.Add(journeyToSave); if (!_journeyRepository.Save()) { throw new Exception("Could not save journey"); } return(journeyToSave); }
public async Task <bool> AddCar(CarDto car, ApplicationUser user) { var carRegistered = this.dbContext.Car.ToList().Where(c => c.UserId == user.Id && c.IsActive); if (carRegistered.Count() > 0) { return(false); } var carToBeAdded = new Car { Name = car.Name, Color = car.Color, RegistrationNumber = car.RegistrationNumber, RegisterTimestamp = car.RegisterTimestamp, IsActive = true, UserId = user.Id, User = user }; this.dbContext.Car.Add(carToBeAdded); await this.dbContext.SaveChangesAsync(); return(true); }
public async Task <string> Update(CarDto car) { var url = $"{Settings.SERVER_ENDPOINT}/Car/Update"; var result = await _requestService.PutAsync <CarDto, string>(url, car); return(result); }
public void UpdateProperties() { //The API would return a CarDto. CarDto newDto = APICall(); //Mock code _dto = newDto; }
public void Add(CarDto carDto) { var car = Mapper.Map <Car>(carDto); Database.Cars.Add(car); Database.Save(); }
public async Task Post_ValidCarModelIsClientDbConflict_ConflictResult() { _carService.Setup(c => c.AddCarAsync(It.IsAny <string>(), It.IsAny <CarDto>())).ReturnsAsync(() => null); _clientService.Setup(c => c.ClientExistsAsync(It.IsAny <string>())).ReturnsAsync(true); var controller = SetupControllerWithContext(); var carDto = new CarDto() { Brand = "Jeep", Description = "Nice car", Engine = "4.0", ImagePath = "www.jeep.com", Mileage = 83931, Model = "Compass", Power = 231, Price = 39000, Production = new DateTime(2010, 4, 10) }; var response = await controller.Post(carDto) as ObjectResult; Assert.IsType <ConflictObjectResult>(response); }
public async Task Put_ValidCarModelInvalidIdIsClientIsOwnerDbWorking_BadRequestResult() { _carService.Setup(c => c.CarExistsAsync(It.IsAny <int>())).ReturnsAsync(false); _clientService.Setup(c => c.CheckIfOwnerAsync(It.IsAny <string>(), It.IsAny <int>())).ReturnsAsync(true); _clientService.Setup(c => c.ClientExistsAsync(It.IsAny <string>())).ReturnsAsync(true); var controller = SetupControllerWithContext(); var carDto = new CarDto() { Brand = "Jeep", Description = "Nice car", Engine = "4.0", ImagePath = "www.jeep.com", Mileage = 83931, Model = "Compass", Power = 231, Price = 39000, Production = new DateTime(2010, 4, 10) }; var id = 1; var response = await controller.Put(id, carDto) as ObjectResult; Assert.IsType <BadRequestObjectResult>(response); }
public async Task <IActionResult> Put(int id, [FromBody] CarDto carDto) { if (!await CheckIfClientAsync()) { return(StatusCode(StatusCodes.Status403Forbidden, "No client account has been found.")); } var userId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); if (!await _clientService.CheckIfOwnerAsync(userId, id)) { return(StatusCode(StatusCodes.Status404NotFound, "Operation available only for the owner.")); } if (!await _carService.CarExistsAsync(id)) { return(BadRequest(new { Message = $"No car with ID { id } has been found." })); } var outcome = await _carService.UpdateCarAsync(id, carDto); if (outcome == null) { return(Conflict(new { Error = "Request unsuccessfull." })); } _logger.LogInformation("User {User} edited Car Model (id = {Id}) in db", HttpContext.User.Identity.Name, id); return(Ok(outcome)); }
public async Task <IActionResult> Update(int id, [FromBody] CarDto car) { if (id != car.CarId) { return(BadRequest()); } // Check for valid DriverID var driver = await _driverRepo.GetById(car.DriverId); if (driver == null) { ModelState.AddModelError("DriverID Error", "DriverID is invalid or missing"); return(BadRequest(ModelState)); } var carObj = await _repo.GetById(id); if (carObj == null) { return(NotFound()); } else { await _repo.UpdateById(id, car); } return(NoContent()); }
public async Task <CarDto> AddCarAsync(string id, CarDto carToAdd) { CarDto addedCar; try { addedCar = await _carRepository.AddAsync(carToAdd); } catch (DataException) { throw; } if (addedCar != null) { var result = await OnCarAdded?.Invoke(id, addedCar.Id); if (!result) { await _carRepository.DeleteAsync((int)addedCar.Id); } } return(addedCar); }
public ResultDto UpdateCar([FromBody] CarDto dto) { try { Car f = _context.Cars.First(x => x.Id == dto.Id); f.Brand = dto.Brand; f.Marks = dto.Marks; _context.SaveChanges(); return(new ResultDto { IsSuccessful = true, Message = "Successfully created" }); } catch (Exception) { return(new ResultDto { IsSuccessful = false, Message = "Something goes wrong!" }); throw; } }
public async Task UpdateCarAsync_PassedValidObject_ReturnsObject() { CarDto carDto = new CarDto() { CarId = 1, Brand = "KIA", Model = "Seed" }; Car car = new Car() { CarId = 1, Brand = "KIHA", Model = "Sweet" }; mockCarRepository .Setup(p => p.FindByIdAsync(carDto.CarId)) .ReturnsAsync(car); mockCarRepository .Setup(s => s.SaveChangesAsync()) .Verifiable(); var service = new CarService(mockCarRepository.Object, mapper); //Act var result = await service.UpdateCarAsync(carDto); //Assert Assert.Equal(result.CarId, carDto.CarId); Assert.Equal(result.Brand, carDto.Brand); Assert.Equal(result.Model, carDto.Model); Assert.IsType <CarDto>(result); }
public void DeleteCarTest() { CarDto tempCar = Target.GetCarById(1); Target.DeleteCar(tempCar); Assert.AreEqual(2, Target.Cars.Count); }
public static Car ToDomain(this CarDto car) { return(new Car { Id = car.Id, Seats = car.Seats }); }
public async Task <CarDto> AddOrUpdateAsync(CarDto item) { if (item == null) { throw new ArgumentException("Car is invalid!"); } Car carEntity = null; if (item.CarId <= 0) { carEntity = this.mapper.Map <Car>(item); this.context.Add(carEntity); } else { carEntity = await this.context.Cars.FindAsync(item.CarId); if (carEntity == null) { throw new ArgumentException("Car was not found!"); } this.mapper.Map(item, carEntity); this.context.Update(carEntity); } await this.context.SaveChangesAsync(); return(await this.GetAsync(carEntity.CarId)); }
public async Task <CarDto> Add(CarDto car, string email) { try { using var transaction = _unitOfWork.BeginTransaction(); var user = await CheckUser(email); car.UserId = user.Id; var entity = _mapper.Map <Car>(car); await _unitOfWork.CarRepository.Add(entity); await _unitOfWork.Save(); transaction.Commit(); _mapper.Map(entity, car); return(car); } catch (Exception ex) { _logger.LogError(ex, "Error adding new car"); throw; } }
public async Task <IActionResult> PutCarDto(int id, CarDto carDto) { if (id != carDto.CarId) { return(BadRequest()); } var car = _context.Car.FirstOrDefault(x => x.CarId == id); car.CarName = carDto.CarName; car.CarDescription = carDto.CarDescription; car.CarDate = carDto.CarDate; car.BrandId = carDto.BrandId; _context.Entry(car).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CarDtoExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
private async Task <CarViewModel> GetCarViewModel(CarDto carDto) { var models = await this.carService.GetAllModelAsync(); var allmodells = this.mapper.Map <List <CarBrandViewModel> >(models); var carBrand = await this.carService.GetModelByBrandIdAsync(carDto.CarBrandId); var carBrandView = this.mapper.Map <List <CarModelViewModel> >(carBrand); var carViewModel = new CarViewModel { Id = carDto.Id, Door = carDto.Door, EngineTypeId = carDto.EngineTypeId, CarBrandId = carDto.CarBrandId, CarModelId = carDto.CarModelId, Price = carDto.Price, ProductionYear = carDto.ProductionYear, AllCarModel = allmodells, UserId = carDto.UserId, AllCarBrandByModel = carDto.CarBrandId == 0 ? Enumerable.Empty <CarModelViewModel>() : carBrandView }; return(carViewModel); }
public async Task Put_ValidCarModelValidIdIsNotClientIsOwnerDbWorking_403StatusCode() { _clientService.Setup(c => c.ClientExistsAsync(It.IsAny <string>())).ReturnsAsync(false); var controller = SetupControllerWithContext(); var carDto = new CarDto() { Brand = "Jeep", Description = "Nice car", Engine = "4.0", ImagePath = "www.jeep.com", Mileage = 83931, Model = "Compass", Power = 231, Price = 39000, Production = new DateTime(2010, 4, 10) }; var id = 1; var response = await controller.Put(id, carDto) as ObjectResult; Assert.True(response.StatusCode == 403); }
public async Task InsertReservationWithAutoNotAvailableTest() { // arrange GetCarRequest carRequestId = new GetCarRequest { IdFilter = 2 }; CarDto car = _autoClient.GetCar(carRequestId); GetCustomerRequest customerRequestId = new GetCustomerRequest { IdFilter = 1 }; CustomerDto customer = _kundeClient.GetCustomer(customerRequestId); DateTime from = new DateTime(2020, 1, 19, 0, 0, 0, DateTimeKind.Utc); DateTime to = new DateTime(2020, 1, 22, 0, 0, 0, DateTimeKind.Utc); ReservationDto reservation = new ReservationDto { Car = car, Customer = customer, From = from.ToTimestamp(), To = to.ToTimestamp(), }; // act // assert Assert.Throws <RpcException>(() => _target.InsertReservation(reservation)); }
protected void btnCreate_Click(object sender, EventArgs e) { CarDto car = new CarDto(); car.Brand = carBrand.Text; car.Model = carModel.Text; car.SerialNumber = carSerialNumber.Text; car.Color = carColor.Text; car.Price = int.Parse(carPrice.Text); var _loadedManufact = forManufact.GetEntities().Where(i => i.Name == carManufacturer.Text).FirstOrDefault(); car.ManufacturerId = _loadedManufact != null ? _loadedManufact.Id : Guid.Empty; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)) { client.CreateEntity(car); scope.Complete(); } Thread.Sleep(3000); Response.Redirect("carPage"); }
public async Task CheckAvailabilityIsFalseTest() { //arrange GetCarRequest carRequestId = new GetCarRequest { IdFilter = 2 }; CarDto car = _autoClient.GetCar(carRequestId); GetCustomerRequest customerRequestId = new GetCustomerRequest { IdFilter = 1 }; CustomerDto customer = _kundeClient.GetCustomer(customerRequestId); DateTime from = new DateTime(2020, 1, 19, 0, 0, 0, DateTimeKind.Utc); DateTime to = new DateTime(2020, 1, 22, 0, 0, 0, DateTimeKind.Utc); ReservationDto reservation = new ReservationDto { Car = car, Customer = customer, From = from.ToTimestamp(), To = to.ToTimestamp(), }; //act CheckResponse available = _target.AvailabilityCheck(reservation); //assert Assert.False(available.IsValid); }
public int GetId(CarDto carDto) { var carInDb = Database.Cars.GetAll().Last(); if (carInDb.BodyTypeId == carDto.BodyTypeId & carInDb.CarClassId == carDto.CarClassId & carInDb.Description == carDto.Description & carInDb.FuelTypeId == carDto.FuelTypeId & carInDb.GearboxTypeId == carDto.GearboxTypeId & carInDb.IsAvailable == carDto.IsAvailable & carInDb.IsDeleted == carDto.IsDeleted & carInDb.LicensePlate == carDto.LicensePlate & carInDb.ManufacturerId == carDto.ManufacturerId & carInDb.Name == carDto.Name & carInDb.NumberOfSeats == carDto.NumberOfSeats & carInDb.PricePerDay == carDto.PricePerDay & carInDb.ProductionYear == carDto.ProductionYear & carInDb.TransmissionTypeId == carDto.TransmissionTypeId & carInDb.WithAirConditioning == carDto.WithAirConditioning & carInDb.PictureLink == carDto.PictureLink) { return(carInDb.Id); } else { return(carDto.Id); } }
public async Task InsertReservationTest() { // arrange GetCarRequest carRequestId = new GetCarRequest { IdFilter = 2 }; CarDto car = _autoClient.GetCar(carRequestId); GetCustomerRequest customerRequestId = new GetCustomerRequest { IdFilter = 1 }; CustomerDto customer = _kundeClient.GetCustomer(customerRequestId); DateTime from = new DateTime(2020, 12, 1, 0, 0, 0, DateTimeKind.Utc); DateTime to = new DateTime(2020, 12, 3, 0, 0, 0, DateTimeKind.Utc); ReservationDto reservation = new ReservationDto { Car = car, Customer = customer, From = from.ToTimestamp(), To = to.ToTimestamp(), }; // act ReservationDto insertedReservation = _target.InsertReservation(reservation); // assert Assert.Equal(reservation.Car, insertedReservation.Car); Assert.Equal(customer.Id, insertedReservation.Customer.Id); }
public void Edit(CarDto carDto) { var car = Mapper.Map <Car>(carDto); Database.Cars.Update(car); Database.Save(); }
private TCar BuildCar <TCar>(CarDto dto) where TCar : class, ICar { var factory = carFactoryProvider.Create <TCar>(); return(factory.Create(dto)); }
public IHttpActionResult PutCar(int id, CarDto carDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var car = db.Cars.SingleOrDefault(c => c.Id == carDto.Id); if (car == null) { return(NotFound()); } Mapper.Map(carDto, car); //car.Brand_Id = carDto.Brand_Id; //car.Miles = carDto.Miles; //car.ReleaseDate = carDto.ReleaseDate; //car.Stock = carDto.Stock; db.SaveChanges(); return(Ok()); }
public async Task Add_WhenACarIsAddedWithAllRequiredData_ReturnsCreatedStatusCode() { CarDto newCar = new CarDto { Make = "Toyota", Model = "Yaris", BodyType = "Hatchback", Engine = "500CC", Wheels = 4, Doors = 3, VehicleTypeID = _vehicleType.VehicleTypeID }; Car expectedResult = new Car { Make = "Toyota", Model = "Yaris", BodyType = "Hatchback", Engine = "500CC", Wheels = 4, Doors = 3, VehicleTypeID = _vehicleType.VehicleTypeID }; _carService.Setup(cs => cs.AddCar(newCar)).Returns(Task.FromResult(expectedResult)); CarController controller = new CarController(_carService.Object, _vehicleTypeService.Object); ActionResult result = (await controller.Add(newCar)).Result; var createdResult = result as ObjectResult; Assert.IsNotNull(createdResult); Assert.AreEqual(201, createdResult.StatusCode); Assert.That(createdResult.Value, Is.EqualTo(expectedResult)); }
public void UpdateCar(CarDto car) { var carToSave = new Car(); if (car.IsIdSet) { carToSave = _carsDataService.GetCar(car.Id); if (carToSave == null) { throw new ArgumentException($"Car with Id={car.Id} was not found"); } } UpdateCarToSaveWithNewData(carToSave, car); var validationResult = _carValidator.Validate(carToSave); if (!validationResult.IsValid) { throw new ArgumentException($"Data is invalid: {validationResult.Errors.FirstOrDefault()?.ErrorMessage}"); } if (carToSave.Id == 0) { _carsDataService.InsertCar(carToSave); } else { _carsDataService.UpdateCar(carToSave); } }
// GET: Cars/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var carItem = Db.Cars.Where(car => car.Id == id).Single(); var CarDto = new CarDto { Id = carItem.Id, LicensePlate = carItem.LicensePlate, OwnerUserName = carItem.Owner.UserName, Picture = "data:image/jpeg;base64, " + Convert.ToBase64String(carItem.Picture.PictureData), Title = carItem.Title, }; var leaseItem = Db.Leases.Where(lease => lease.Car.Id == carItem.Id).ToArray(); if (leaseItem.Count() == 0) { CarDto.Status = LeaseStatus.Verified; } else { var lease = leaseItem.Last(); CarDto.Status = lease.Status; } return(View(CarDto)); }