public ActionResult Add(FormCollection formValues, VehicleFormModel vehicleForm, HttpPostedFileBase photoFile)
        {
            if (IsSaveOperation(formValues))
            {
                if (TrySaveVehicle(vehicleForm, photoFile))
                {
                    return(RedirectToRoute("Dashboard"));
                }
            }

            AddYearMakeModelSelectListsToViewBag(vehicleForm);

            var vehicles = Using <GetVehicleListForUser>().Execute(CurrentUserId);

            var vm = new VehicleAddViewModel
            {
                User         = CurrentUser,
                VehiclesList = new VehicleListViewModel(vehicles),
                Vehicle      = vehicleForm
            };

            vm.VehiclesList.IsCollapsed = true;

            return(View(vm));
        }
        public IActionResult Edit(int?id)
        {
            try
            {
                var vm = new VehicleFormModel();

                if (id.HasValue)
                {
                    var vehicle = _vehicleService.GetVehicle(id.Value, withIncludes: false);

                    if (vehicle == null)
                    {
                        TempData["InfoMessage"] = AppStrings.VehicleNotFoundMsg;
                        return(RedirectToAction(nameof(Index)));
                    }

                    vm = _mapper.Map <VehicleFormModel>(vehicle);
                }

                return(View("VehicleForm", vm));
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                TempData["ErrorMsg"] = AppStrings.GenericErrorMsg;
                return(RedirectToAction(nameof(Index)));
            }
        }
Esempio n. 3
0
        private VehicleFormModel GetVehicleForm(int vehicleId)
        {
            var vehicles = Using <GetVehicleListForUser>()
                           .Execute(CurrentUserId);

            var selected = vehicles
                           .FirstOrDefault(x => x.VehicleId == vehicleId);

            if (selected == null)
            {
                throw new HttpException((int)HttpStatusCode.NotFound,
                                        Messages.VehicleController_VehicleNotFound);
            }

            var vehicleForm = new VehicleFormModel
            {
                VehicleId = selected.VehicleId,
                Name      = selected.Name,
                Year      = selected.Year,
                MakeName  = selected.MakeName,
                ModelName = selected.ModelName,
                SortOrder = selected.SortOrder,
                CancelUrl = Url.Action("Details", "Vehicle", new { vehicleId })
            };

            return(vehicleForm);
        }
Esempio n. 4
0
        public ActionResult Add(VehicleFormModel vehicleForm, HttpPostedFileBase photoFile, string action)
        {
            if (!string.IsNullOrEmpty(action) && action.Equals("Save") && ModelState.IsValid)
            {
                int vehicleId;

                if (TrySaveVehicle(vehicleForm, photoFile, out vehicleId))
                {
                    this.SetConfirmationMessage(Messages.VehicleController_VehicleAdded);

                    return(new ContentTypeAwareResult(new { VehicleId = vehicleId })
                    {
                        WhenHtml = (m, v, t) => RedirectToAction("Details", "Vehicle", new { vehicleId })
                    });
                }
            }

            if (ModelState.IsValid)
            {
                //Only proceed to next action if form is valid.
                vehicleForm.Action = action;
            }
            else
            {
                vehicleForm.Action = null;
            }

            return(SetupVehicleForm(vehicleForm));
        }
Esempio n. 5
0
        public void WithMissingYearForMake_ThenReturnsValidationResult()
        {
            var vehicleForm = new VehicleFormModel
            {
                Name     = "vehicle",
                MakeName = "Test"
            };

            _manufacturerRepo
            .Setup(x => x.IsValidYear(It.IsAny <int>()))
            .Returns(true);

            _manufacturerRepo
            .Setup(x => x.IsValidMake(It.IsAny <int>(), It.IsAny <string>()))
            .Returns(true);

            _manufacturerRepo
            .Setup(x => x.IsValidModel(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(true);

            var handler = new CanValidateVehicleYearMakeAndModel(_manufacturerRepo.Object);
            var actual  = handler.Execute(vehicleForm).ToList();

            Assert.Equal(1, actual.Count);
            Assert.Contains("missing", actual[0].Message, StringComparison.CurrentCultureIgnoreCase);
            Assert.Contains("year", actual[0].Message, StringComparison.CurrentCultureIgnoreCase);
            Assert.Contains("make", actual[0].Message, StringComparison.CurrentCultureIgnoreCase);
        }
Esempio n. 6
0
        public void WhenConstructed_ThenSuccessful()
        {
            var actual = new VehicleFormModel();

            Assert.NotNull(actual);
            Assert.Equal(0, actual.VehicleId);
            Assert.Null(actual.Name);
        }
Esempio n. 7
0
        public void WhenSortOrderSet_ThenValueUpdated()
        {
            var target = new VehicleFormModel();

            target.SortOrder = 1;

            int actual = target.SortOrder;

            Assert.Equal(1, actual);
        }
Esempio n. 8
0
        public void WhenIdSet_ThenValueUpdated()
        {
            var target = new VehicleFormModel();

            target.VehicleId = 4;

            int actual = target.VehicleId;

            Assert.Equal(4, actual);
        }
Esempio n. 9
0
        public void WhenNameSet_ThenValueUpdated()
        {
            var target = new VehicleFormModel();

            target.Name = "Name";

            string actual = target.Name;

            Assert.Equal("Name", actual);
        }
Esempio n. 10
0
        public void WhenYearSet_ThenValueUpdated()
        {
            var target = new VehicleFormModel();

            target.Year = 1971;

            int?actual = target.Year;

            Assert.True(actual.HasValue);
            Assert.Equal(1971, actual.Value);
        }
Esempio n. 11
0
        private ActionResult SetupVehicleForm(VehicleFormModel vehicleForm)
        {
            var handler             = Using <GetYearsMakesAndModels>();
            var yearsMakesAndModels = handler.Execute(vehicleForm.Year, vehicleForm.MakeName);

            ViewBag.Years  = EnumerableToSelectList(yearsMakesAndModels.Item1, vehicleForm.Year);
            ViewBag.Makes  = EnumerableToSelectList(yearsMakesAndModels.Item2, vehicleForm.MakeName);
            ViewBag.Models = EnumerableToSelectList(yearsMakesAndModels.Item3, vehicleForm.ModelName);

            return(new ContentTypeAwareResult(vehicleForm));
        }
Esempio n. 12
0
        public void WhenNameSetToNull_ThenUpdatesValue()
        {
            var target = new VehicleFormModel();

            target.Name = "Name";

            target.Name = null;

            string actual = target.Name;

            Assert.Null(actual);
        }
Esempio n. 13
0
        public void WhenYearSetToNull_ThenUpdatesValue()
        {
            var target = new VehicleFormModel();

            target.Year = 1971;

            target.Year = null;

            int?actual = target.Year;

            Assert.False(actual.HasValue);
        }
Esempio n. 14
0
        public void WhenNameSetToValidValue_ThenValidationPasses()
        {
            var target = new VehicleFormModel();

            target.Name = "Name";

            var  validationContext = new ValidationContext(target, null, null);
            var  validationResults = new List <ValidationResult>();
            bool actual            = Validator.TryValidateObject(target, validationContext, validationResults, true);

            Assert.True(actual);
            Assert.Equal(0, validationResults.Count);
        }
Esempio n. 15
0
        public void InvokesVehicleRepository()
        {
            var vehicleForm = new VehicleFormModel {
                Name = "vehicle"
            };

            var handler = new CreateVehicle(_vehicleRepo.Object, _photoRepo.Object);

            handler.Execute(UserId, vehicleForm, null);

            _vehicleRepo
            .Verify(r => r.Create(UserId, It.IsAny <Vehicle>()), Times.Once());
        }
        // GET: AdminsArea/Vehicle/Edit/5
        public ActionResult Edit(int id)
        {
            IEnumerable <Model>    models;
            IEnumerable <Customer> customers;
            Vehicle vehicle = new Vehicle();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:44318/");
                //HTTP GET
                var responseTask  = client.GetAsync("Model/Get");
                var responseTask2 = client.GetAsync("Customer/Get/");
                var responseTask3 = client.GetAsync("Vehicle/Get/" + id);
                responseTask.Wait();
                responseTask2.Wait();
                responseTask3.Wait();
                var result  = responseTask.Result;
                var result2 = responseTask2.Result;
                var result3 = responseTask3.Result;
                if (result.IsSuccessStatusCode && result2.IsSuccessStatusCode && result3.IsSuccessStatusCode)
                {
                    var readTask = result.Content.ReadAsAsync <IEnumerable <Model> >();
                    readTask.Wait();
                    models = readTask.Result;

                    var readTask2 = result2.Content.ReadAsAsync <IEnumerable <Customer> >();
                    readTask2.Wait();
                    customers = readTask2.Result;

                    var readTask3 = result3.Content.ReadAsAsync <Vehicle>();
                    readTask3.Wait();
                    vehicle = readTask3.Result;
                }
                else
                {
                    models    = Enumerable.Empty <Model>();
                    customers = Enumerable.Empty <Customer>();
                    vehicle   = null;
                    ModelState.AddModelError(string.Empty, "Server error occured while retriving data");
                }
            }
            VehicleFormModel entity = new VehicleFormModel
            {
                models    = models,
                customers = customers,
                vehicle   = vehicle
            };

            return(PartialView(entity));
        }
Esempio n. 17
0
        public ActionResult Edit(VehicleFormModel vehicleForm, HttpPostedFileBase photoFile, string action)
        {
            if (!string.IsNullOrEmpty(action) && action.Equals("Save") && ModelState.IsValid)
            {
                if (TryUpdateVehicle(vehicleForm, photoFile))
                {
                    this.SetConfirmationMessage(Messages.VehicleController_VehicleUpdated);

                    return(RedirectToAction("Details", "Vehicle", new { vehicleId = vehicleForm.VehicleId }));
                }
            }

            return(SetupVehicleForm(vehicleForm));
        }
Esempio n. 18
0
        public void WhenNameSetToNull_ThenValidationFails()
        {
            var target = new VehicleFormModel();

            target.Name = null;

            var  validationContext = new ValidationContext(target, null, null);
            var  validationResults = new List <ValidationResult>();
            bool actual            = Validator.TryValidateObject(target, validationContext, validationResults, true);

            Assert.False(actual);
            Assert.Equal(1, validationResults.Count);
            Assert.Equal(1, validationResults[0].MemberNames.Count());
            Assert.Equal("Name", validationResults[0].MemberNames.First());
        }
        private void AddYearMakeModelSelectListsToViewBag(VehicleFormModel vehicle = null)
        {
            var handler = Using <GetYearsMakesAndModels>();

            Tuple <int[], string[], string[]> yearsMakesAndModels = (vehicle != null)
                                                                       ? handler.Execute(vehicle.Year, vehicle.MakeName)
                                                                       : handler.Execute();

            ViewData["Years"] = EnumerableToSelectList(yearsMakesAndModels.Item1,
                                                       (vehicle != null) ? vehicle.Year : null);
            ViewData["Makes"] = EnumerableToSelectList(yearsMakesAndModels.Item2,
                                                       (vehicle != null) ? vehicle.MakeName : null);
            ViewData["Models"] = EnumerableToSelectList(yearsMakesAndModels.Item3,
                                                        (vehicle != null) ? vehicle.ModelName : null);
        }
        public IActionResult Save(VehicleFormModel formModel)
        {
            var _validator = new VehicleValidator();
            var results    = _validator.Validate(formModel);

            if (results.Errors.Any())
            {
                foreach (var error in results.Errors)
                {
                    ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var vehicle = (formModel.VehicleId == AppStrings.NotSet) ?
                                  _mapper.Map <Vehicle>(formModel) :
                                  _mapper.Map <VehicleFormModel, Vehicle>(formModel, _vehicleService.GetVehicle(formModel.VehicleId, withIncludes: true));

                    _vehicleService.SaveVehicle(vehicle);

                    if (formModel.AddRepairOption)
                    {
                        return(RedirectToAction("Edit", "Repair", new { vehicleId = vehicle.Id }));
                    }

                    TempData["SuccessMessage"] = AppStrings.VehicleSavedSuccessMsg;
                    return(RedirectToAction(nameof(Details), new { id = vehicle.Id }));
                }
                catch (DuplicateVehicleVinException ex)
                {
                    ModelState.AddModelError("VIN", ex.Message);
                }
                catch (VehicleNotGreaterThanRequiredYearException ex)
                {
                    ModelState.AddModelError("Year", ex.Message);
                }
                catch (Exception ex)
                {
                    _logger.LogWarning("Error attempting to save vehicle", ex.Message);
                    TempData["ErrorMessage"] = AppStrings.GenericErrorMsg;
                }
            }

            return(View("VehicleForm", formModel));
        }
Esempio n. 21
0
        public void ForOtherUser_ThenThrows()
        {
            const int anotherUserId = 87;

            var vehicleForm = new VehicleFormModel {
                Name = "vehicle", VehicleId = DefaultVehicleId
            };

            _vehicleRepo
            .Setup(vr => vr.GetVehicle(anotherUserId, DefaultVehicleId))
            .Throws(new InvalidOperationException());

            var handler = new UpdateVehicle(_vehicleRepo.Object, _photoRepo.Object);

            Assert.Throws <UnauthorizedException>(() => handler.Execute(anotherUserId, vehicleForm, null));
        }
Esempio n. 22
0
        public void ThenDelegatesToVehicleRepository()
        {
            var vehicleForm = new VehicleFormModel {
                VehicleId = DefaultVehicleId
            };

            _vehicleRepo
            .Setup(vr => vr.GetVehicle(UserId, DefaultVehicleId))
            .Returns(new Vehicle());

            var handler = new UpdateVehicle(_vehicleRepo.Object, _photoRepo.Object);

            handler.Execute(UserId, vehicleForm, null);

            _vehicleRepo.Verify(r => r.Update(It.IsAny <Vehicle>()), Times.Once());
        }
Esempio n. 23
0
        public void AndVehicleRepositoryThrows_ThenWrapsException()
        {
            _vehicleRepo
            .Setup(v => v.Create(It.IsAny <int>(), It.IsAny <Vehicle>()))
            .Throws <InvalidOperationException>();

            var vehicleForm = new VehicleFormModel {
                Name = "vehicle"
            };

            var handler = new CreateVehicle(_vehicleRepo.Object, _photoRepo.Object);

            var ex = Assert.Throws <BusinessServicesException>(() => handler.Execute(UserId, vehicleForm, null));

            Assert.IsType <InvalidOperationException>(ex.InnerException);
        }
        public void WhenEditVehicleActionExecutedWithInvalidVehicle_ThenSelectListsPopulated()
        {
            const int    year = 1984;
            const string make = "make";

            var data = new Tuple <int[], string[], string[]>(
                new[] { 1, 2, 3, 4, 5 },
                new[] { "A", "B" },
                new[] { "i", "ii", "iii" }
                );

            MockHandlerFor(
                () => new Mock <GetYearsMakesAndModels>(null),
                x => x
                .Setup(h => h.Execute(year, make))
                .Returns(data));

            MockVehicleListWithVehicles();

            TestableVehicleController controller = GetTestableVehicleController();

            controller.ModelState.AddModelError("bad", "bad");

            var vehicleForm = new VehicleFormModel {
                VehicleId = DefaultVehicleId, Name = null, Year = year, MakeName = make
            };
            var form = new FormCollection {
                { "Save", "true" }
            };

            var actual = (ViewResult)controller.Edit(form, vehicleForm, null);

            var yearsSelectList = (SelectList)actual.ViewData["Years"];

            Assert.NotNull(yearsSelectList);
            Assert.Equal(5, yearsSelectList.Count());

            var makesSelectList = (SelectList)actual.ViewData["Makes"];

            Assert.NotNull(makesSelectList);
            Assert.Equal(2, makesSelectList.Count());

            var modelsSelectList = (SelectList)actual.ViewData["Models"];

            Assert.NotNull(modelsSelectList);
            Assert.Equal(3, modelsSelectList.Count());
        }
Esempio n. 25
0
        public void WhenAddVehicleActionExecutedWithValidVehicle_ThenRedirectsToVehicleDetails()
        {
            var vehicleForm = new VehicleFormModel();

            MockVehicleList();
            MockDefaultYearMakeModel();

            MockHandlerFor <CanAddVehicle>();
            MockHandlerFor <CreateVehicle>(
                x => x.Setup(h => h.Execute(defaultUser.UserId, vehicleForm, null)));

            var controller = GetTestableVehicleController();

            ActionResult result = controller.Add(vehicleForm, null, "Save");

            Assert.IsAssignableFrom <ContentTypeAwareResult>(result);
        }
Esempio n. 26
0
        public void ThatAndVehicleDoesNotExist_ThenThrowsNonExistent_ThenThrows()
        {
            // this is the same test as FromOtherUsers_ThenThrows
            const int nonExistentVehicleId = 87;
            var       vehicleForm          = new VehicleFormModel {
                Name = "vehicle", VehicleId = nonExistentVehicleId
            };

            // the repo throws an exception when it can't find a match with both the user and the vehicle
            _vehicleRepo
            .Setup(vr => vr.GetVehicle(UserId, It.IsAny <int>()))
            .Returns((Vehicle)null);

            var handler = new UpdateVehicle(_vehicleRepo.Object, _photoRepo.Object);

            Assert.Throws <HttpException>(() => handler.Execute(UserId, vehicleForm, null));
        }
Esempio n. 27
0
        public void Throws_ThenWrapsException()
        {
            var vehicleForm = new VehicleFormModel {
                Name = "vehicle", VehicleId = DefaultVehicleId
            };

            _vehicleRepo
            .Setup(vr => vr.GetVehicle(UserId, DefaultVehicleId))
            .Throws(new InvalidOperationException());

            var handler = new UpdateVehicle(_vehicleRepo.Object, _photoRepo.Object);

            Exception ex = Assert.Throws <UnauthorizedException>(() => handler.Execute(UserId, vehicleForm, null));

            Assert.NotNull(ex.InnerException);
            Assert.IsType <InvalidOperationException>(ex.InnerException);
        }
Esempio n. 28
0
        public void WithAPhoto_ThenInvokesVehicleRepositoryToUpdatePhotoInfo()
        {
            var vehicleForm = new VehicleFormModel {
                Name = "vehicle"
            };
            var photoStream = Mock.MockPhotoStream();

            var handler = new CreateVehicle(_vehicleRepo.Object, _photoRepo.Object);

            handler.Execute(UserId, vehicleForm, photoStream.Object);

            _vehicleRepo
            .Verify(r => r.Create(UserId, It.IsAny <Vehicle>()), Times.Once());

            _vehicleRepo
            .Verify(r => r.Update(It.IsAny <Vehicle>()), Times.Once());
        }
Esempio n. 29
0
        public void WithInvalidYear_ThenReturnsValidationResult()
        {
            var vehicleForm = new VehicleFormModel
            {
                Name = "vehicle",
                Year = 2100,
            };

            SetupManufacturerRepo(isYearValid: false);

            var handler = new CanValidateVehicleYearMakeAndModel(_manufacturerRepo.Object);
            var actual  = handler.Execute(vehicleForm).ToList();

            Assert.Equal(1, actual.Count);
            Assert.Contains("not valid", actual[0].Message, StringComparison.CurrentCultureIgnoreCase);
            Assert.Contains("year", actual[0].Message, StringComparison.CurrentCultureIgnoreCase);
        }
Esempio n. 30
0
        public void WhenAddVehicleActionExecutedWithValidVehicle_ThenVehicleIsCreated()
        {
            var vehicleForm = new VehicleFormModel();

            MockVehicleList();
            MockDefaultYearMakeModel();

            MockHandlerFor <CanAddVehicle>();
            var handler = MockHandlerFor <CreateVehicle>(
                x => x.Setup(h => h.Execute(defaultUser.UserId, vehicleForm, null))
                .Verifiable("handler not invoked"));

            var controller = GetTestableVehicleController();

            controller.Add(vehicleForm, null, "Save");

            handler.Verify();
        }