示例#1
0
 public static Vehicle MapToVehicle(this UpdateVehicle command) => new Vehicle
 {
     LicenseNumber = command.LicenseNumber,
     Brand         = command.Brand,
     Type          = command.Type,
     OwnerId       = command.OwnerId
 };
示例#2
0
        public VehicleControllerTesting()
        {
            //mock setup
            vehicleMock  = new Mock <IVehicle>();
            vehiclesMock = new List <IVehicle> {
                vehicleMock.Object
            };
            addVehicleMock    = new Mock <IAddVehicle>();
            updateVehicleMock = new Mock <IUpdateVehicle>();
            vehicle           = new Vehicle();
            vehicles          = new List <Vehicle>();

            //view models mock setup
            vehicleViewModelMock  = new Mock <IVehicleViewModel>();
            vehiclesViewModelMock = new List <IVehicleViewModel>();

            //sample models
            addVehicle = new AddVehicle {
                Latitude = 10, Longitude = 10, VehicleHumidity = 10, VehicleTemp = 10
            };
            updateVehicle = new UpdateVehicle {
                Latitude = 999, Longitude = 999, VehicleHumidity = 60, VehicleTemp = 80
            };

            //controller setup
            _logger   = new Mock <ILogger <VehicleController> >();
            repoMock  = new Mock <IRepositoryWrapper>();
            alertMock = new Mock <IAlert>();
            var allVehicles = GetVehicles();
            var onevehicle  = GetVehicle();

            vehicleController = new VehicleController(_logger.Object, repoMock.Object);
        }
示例#3
0
        public async void UpdateButton_Click(object sender, RoutedEventArgs e)
        {
            VehicleViewModel vView     = new VehicleViewModel();
            string           vehicleID = UpdateIDBox.Text;
            Uri route = new Uri(path + "status/" + vehicleID);
            HttpResponseMessage response = await client.GetAsync(route);

            if (response.IsSuccessStatusCode)
            {
                vView = response.Content.ReadAsAsync <VehicleViewModel>().Result;
            }

            route = new Uri(path + "update/" + vView.Vehicle.VehicleID);
            vView.Vehicle.VehicleHumidity = float.Parse(UpdateHumidityBox.Text);
            vView.Vehicle.VehicleTemp     = float.Parse(UpdateTemperatureBox.Text);

            UpdateVehicle updateVehicle = new UpdateVehicle()
            {
                VehicleHumidity = vView.Vehicle.VehicleHumidity,
                VehicleTemp     = vView.Vehicle.VehicleTemp,
                Latitude        = vView.Vehicle.Latitude,
                Longitude       = vView.Vehicle.Longitude
            };
            HttpResponseMessage UpdateResponse = await client.PutAsJsonAsync(route, updateVehicle);
        }
示例#4
0
        public async void UpdateVehicle(
            EStatusCode expectedStatus,
            UpdateVehicle mutation,
            bool?withModel = false
            )
        {
            if (expectedStatus != EStatusCode.NotFound)
            {
                EntitiesFactory.NewVehicle(id: mutation.Id).Save();
            }
            if (withModel.Value)
            {
                EntitiesFactory.NewModel(id: mutation.ModelId).Save();
            }

            var result = await MutationsHandler.Handle(mutation);

            Assert.Equal(expectedStatus, result.Status);
            if (expectedStatus == EStatusCode.Success)
            {
                var vehicleDb = await MutationsDbContext.Vehicles
                                .Where(v => v.Id == mutation.Id)
                                .FirstOrDefaultAsync();

                Assert.NotNull(vehicleDb);
                Assert.Equal(mutation.Year, vehicleDb.Year);
                Assert.Equal(mutation.Board, vehicleDb.Board);
                Assert.Equal(mutation.ColorId, vehicleDb.Color);
                Assert.Equal(mutation.FuelId, vehicleDb.Fuel);
                Assert.Equal(mutation.ModelId, vehicleDb.Model.Id);
            }
        }
示例#5
0
        public async Task <IActionResult> UpdateVehicle(UpdateVehicle command, int id)
        {
            try
            {
                _logger.LogInformation("UpdateVehicle method fired on {date}", DateTime.Now);

                if (id != command.VehicleId)
                {
                    _logger.LogError("UpdateVehicle method error. Id not found... on {date}", DateTime.Now);

                    return(BadRequest());
                }

                var result = await _mediator.Send(command);

                _logger.LogInformation("UpdateVehicle  method task finished on {date}", DateTime.Now);
                return(Ok(result));
            }
            catch (Exception e)
            {
                _logger.LogInformation("UpdateVehicle  method task finished on {date}", DateTime.Now);
                _logger.LogError($"Error in UpdateVehicle  method: {e.Message}");
                return(StatusCode(StatusCodes.Status500InternalServerError,
                                  "Error in UpdateVehicle  method"));
            }
        }
示例#6
0
 public static VehicleUpdated MapToVehicleUpdated(UpdateVehicle command)
 {
     return(new VehicleUpdated(
                Guid.NewGuid(),
                command.LicenseNumber,
                command.Brand,
                command.Type,
                command.OwnerId
                ));
 }
        public IActionResult PutVehicle(Guid vehicleId, [FromBody] PutUpdateVehicle model)
        {
            if (ModelState.IsValid)
            {
                var command = new UpdateVehicle(vehicleId, model.ProductionYear, model.EngineId);
                commandBus.AddCommand(command);
                commandBus.InvokeCommandsQueue();

                return(GetVehicle(command.Id));
            }

            return(BadRequest());
        }
        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());
        }
        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));
        }
示例#10
0
        internal async static Task <Vehicle> UpdateVehicle(UpdateVehicle VehicleUpdateModel, int id)
        {
            var updateVehicleUrl = $"{BaseUrl}/{id}";

            using (HttpClient httpClient = new HttpClient())
            {
                // var url = new Uri(updateVehicleUrl);
                string jsonTranport          = JsonConvert.SerializeObject(VehicleUpdateModel);
                var    jsonPayload           = new StringContent(jsonTranport, Encoding.UTF8, "application/json");
                var    updateVehicleResponse = await httpClient.PutAsync(updateVehicleUrl, jsonPayload);

                var responseContent = await updateVehicleResponse.Content.ReadAsStringAsync();

                var updatedVehicle = JsonConvert.DeserializeObject <Vehicle>(responseContent);
                return(updatedVehicle);
            }
        }
示例#11
0
        private async void Update_Button(object sender, RoutedEventArgs e)
        {
            var selectedVehicle = int.Parse(IdUpdate.Text);
            var vehicleUpdate   = new UpdateVehicle
            {
                temp     = int.Parse(TempUpdate.Text),
                humidity = int.Parse(HumidUpdate.Text),
            };
            var carUpdateResponse = await VehicleService.UpdateVehicle(vehicleUpdate, selectedVehicle);

            if (carUpdateResponse != null)
            {
                GetAllVehiclesTemp();
                GetAllVehiclesHumid();
                GetAllVehiclesLocation();
            }
        }
示例#12
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);
        }
示例#13
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));
        }
示例#14
0
        public void CommandValid_EngineUpdated()
        {
            var vehicleId            = InsertVehicleToDatabase();
            var engineId             = InsertEngineToDatabase();
            var updateVehicleCommand = new UpdateVehicle(vehicleId, 2010, engineId);

            A.CallTo(() => updateVehicleValidator.Validate(updateVehicleCommand)).DoesNothing();

            updateVehicleHandler.Handle(updateVehicleCommand);

            context.SaveChanges();
            var result = context.Vehicle.FirstOrDefault(v => v.Id == updateVehicleCommand.Id);

            A.CallTo(() => updateVehicleValidator.Validate(updateVehicleCommand)).MustHaveHappened(Repeated.Exactly.Once);
            Assert.NotNull(result);
            Assert.Equal(result.Id, updateVehicleCommand.Id);
            Assert.Equal(result.ProductionYear, updateVehicleCommand.ProductionYear);
            Assert.Equal(result.EngineId, updateVehicleCommand.EngineId);
        }
示例#15
0
        public void ValidatorThrowsException_HandlerThrowsException()
        {
            var previousEngineGuid   = Guid.NewGuid();
            var engineId             = InsertEngineToDatabase();
            var vehicleId            = InsertVehicleToDatabase(engineId: previousEngineGuid);
            var updateVehicleCommand = new UpdateVehicle(vehicleId, 2010, engineId);

            A.CallTo(() => updateVehicleValidator.Validate(updateVehicleCommand)).Throws <Exception>();

            Assert.ThrowsAny <Exception>(() => updateVehicleHandler.Handle(updateVehicleCommand));
            A.CallTo(() => updateVehicleValidator.Validate(updateVehicleCommand)).MustHaveHappened(Repeated.Exactly.Once);

            context.SaveChanges();
            var result = context.Vehicle.FirstOrDefault(v => v.Id == updateVehicleCommand.Id);

            Assert.NotNull(result);
            Assert.Equal(vehicleId, result.Id);
            Assert.Equal(expectedVehicleProductionYear, result.ProductionYear);
            Assert.Equal(previousEngineGuid, result.EngineId);
        }
示例#16
0
        public void WihtNewPhoto_ThenDelegatesToPhotoRepositoryAddNewPhoto()
        {
            var vehicleForm = new VehicleFormModel {
                VehicleId = DefaultVehicleId
            };

            _vehicleRepo
            .Setup(r => r.GetVehicle(UserId, DefaultVehicleId))
            .Returns(new Vehicle {
                VehicleId = DefaultVehicleId
            });

            var newPhotoFile = Mock.MockPhotoStream().Object;

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

            handler.Execute(UserId, vehicleForm, newPhotoFile);

            _photoRepo.Verify(r => r.Create(DefaultVehicleId, It.IsAny <VehiclePhoto>()), Times.Once());
        }
示例#17
0
        public void WithExistingPhoto_ThenDelegatesToPhotoRepositoryToDeleteOldPhoto()
        {
            const int vehiclePhotoId = 300;
            var       vehicleForm    = new VehicleFormModel {
                VehicleId = DefaultVehicleId
            };

            _vehicleRepo
            .Setup(vr => vr.GetVehicle(UserId, DefaultVehicleId))
            .Returns(new Vehicle {
                VehicleId = DefaultVehicleId, PhotoId = vehiclePhotoId
            });

            var newPhotoFile = Mock.MockPhotoStream().Object;

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

            handler.Execute(UserId, vehicleForm, newPhotoFile);

            _photoRepo.Verify(r => r.Delete(vehiclePhotoId), Times.Once());
        }
示例#18
0
        public ActionResult <VehicleViewModel> Put(int vehicleId, [FromBody] UpdateVehicle vehicle)
        {
            var vehicleToUpdate = repository.Vehicles.FindByCondition(c => c.vehicleId == vehicleId).FirstOrDefault();

            if (vehicleToUpdate == null)
            {
                _logger.LogWarning($"Vehicle with vehicleId {vehicleId} not found.");
                return(NotFound($"Vehicle with vehicleId {vehicleId} not found."));
            }

            vehicleToUpdate.temp     = vehicle.temp;
            vehicleToUpdate.humidity = vehicle.humidity;
            var updatedVehicle = repository.Vehicles.Update(vehicleToUpdate);

            repository.Save();

            var vehicleFoundViewModel = new VehicleViewModel {
                Vehicle = vehicleToUpdate
            };

            return(vehicleFoundViewModel);
        }
示例#19
0
        public VehicleControllerTest()
        {
            //mock setup
            vehicleMock  = new Mock <IVehicle>();
            vehiclesMock = new List <IVehicle> {
                vehicleMock.Object
            };
            addVehicleMock    = new Mock <IAddVehicle>();
            updateVehicleMock = new Mock <IUpdateVehicle>();
            vehicle           = new Vehicle();
            vehicles          = new List <Vehicle>();
            //viewmodels mock setup
            vehicleViewModelMock  = new Mock <IVehicleViewModel>();
            vehiclesViewModelMock = new List <IVehicleViewModel>();

            //sample models
            addVehicle = new AddVehicle {
                temp = 22, humidity = 58
            };
            addExistingVehicle = new AddVehicle {
                temp = 22, humidity = 58
            };
            updateVehicle = new UpdateVehicle {
                temp = 34, humidity = 67
            };


            //controller setup

            _logger = new Mock <ILogger <VehicleController> >();

            mockRepo = new Mock <IRepositoryWrapper>();

            var allVehicles = GetVehicles();

            vehicleController = new VehicleController(_logger.Object, mockRepo.Object);
        }
示例#20
0
 public async Task <ActionResult <MutationResult> > UpdateAsync(string id, [FromBody] UpdateVehicle mutation)
 {
     mutation.Id = id;
     return(GetResult(await _mutationsHanlder.Handle(mutation)));
 }
示例#21
0
 public async Task UpdateVehicle([AliasAs("licenseNumber")] string licenseNumber, UpdateVehicle command)
 {
     await _restClient.UpdateVehicle(licenseNumber, command);
 }
示例#22
0
 public PutVehicleController(UpdateVehicle updateVehicle)
 {
     this.updateVehicle = updateVehicle;
 }
        public async Task <IActionResult> UpdateAsync([FromRoute] string licenseNumber, [FromBody] UpdateVehicle command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var existingVehicle = await _dbContext.Vehicles
                                          .FirstOrDefaultAsync(o => o.LicenseNumber == licenseNumber);

                    if (existingVehicle == null)
                    {
                        return(NotFound());
                    }

                    existingVehicle.LicenseNumber = command.LicenseNumber;
                    existingVehicle.Brand         = command.Brand;
                    existingVehicle.Type          = command.Type;
                    existingVehicle.OwnerId       = command.OwnerId;

                    try
                    {
                        _dbContext.Vehicles.Update(existingVehicle);
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("", "Unable to save changes. " +
                                                 "Try again, and if the problem persists " +
                                                 "see your system administrator.");
                        return(StatusCode(StatusCodes.Status500InternalServerError));
                    }

                    await _dbContext.SaveChangesAsync();

                    var e = Mappers.MapToVehicleUpdated(command);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    return(Ok());
                }
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));

                throw;
            }
        }
示例#24
0
        public async Task <ActionResult <VehicleViewModel> > UpdateVehicleStatus(Guid id, [FromBody] UpdateVehicle updateVehicle)
        {
            try
            {
                var findVehicle = repository.Vehicle.FindByCondition(v => v.VehicleID == id).FirstOrDefault();
                findVehicle.Latitude        = updateVehicle.Latitude;
                findVehicle.Longitude       = updateVehicle.Longitude;
                findVehicle.VehicleHumidity = updateVehicle.VehicleHumidity;
                findVehicle.VehicleTemp     = updateVehicle.VehicleTemp;
                repository.Vehicle.Update(findVehicle);
                await alertU.PassAlert(findVehicle);

                repository.Save();
                _logger.LogInformation($"Vehicle id: {id} has updated information");
                return(Ok($"Vehicle id: {id} has updated information"));
            }
            catch
            {
                _logger.LogError($"No vehicle with {id} has been found. Please recheck input.");
                return(NotFound($"No Vehicle with {id} has been found. Please recheck input."));
            }
        }