Exemplo n.º 1
0
        public void Execute(CarDTO carDto)
        {
            using (_context)
            {
                var model          = _context.Models.Where(x => x.Name == carDto.Model).FirstOrDefault();
                var brand          = _context.Brands.Where(x => x.Name == carDto.Brand).FirstOrDefault();
                var owner          = _context.Owners.Where(x => x.Name == carDto.OwnerName).FirstOrDefault();
                var productionYear = _context.ProductionYear.Where(x => x.Year == carDto.Year).FirstOrDefault();
                var engine         = _context.Engines.FirstOrDefault(x => x.Brand.BrandID == carDto.BrandId && x.Model.ModelID == carDto.ModelId && x.Name == carDto.Engine);

                var updatedCar = _context.Cars.Where(x => x.CarID == carDto.Id).FirstOrDefault();
                updatedCar.Name             = !string.IsNullOrEmpty(carDto.Name) ? carDto.Name : updatedCar.Name;
                updatedCar.Brand            = brand != null ? brand : updatedCar.Brand;
                updatedCar.Model            = model != null ? model : updatedCar.Model;
                updatedCar.ProductionYear   = productionYear != null ? productionYear : updatedCar.ProductionYear;
                updatedCar.Owner            = owner != null ? owner :updatedCar.Owner;
                updatedCar.HorsePower       = !string.IsNullOrEmpty(carDto.HorsePower) ? carDto.HorsePower : updatedCar.HorsePower;
                updatedCar.PlateNumber      = !string.IsNullOrEmpty(carDto.PlateNumber) ? carDto.PlateNumber : updatedCar.PlateNumber;
                updatedCar.KilometerCounter = updatedCar.KilometerCounter;
                updatedCar.Phone            = !string.IsNullOrEmpty(carDto.Phone) ? carDto.Phone : updatedCar.Phone;
                updatedCar.TechnicalCheck   = carDto.TechnicalCheck != null ? carDto.TechnicalCheck : updatedCar.TechnicalCheck;
                updatedCar.Engine           = engine;
                _context.Save();
            }
        }
        public void UpdateCarInfo(CarDTO carDTO)
        {
            Car updatedCar = Mapper.Map <CarDTO, Car>(carDTO);

            Database.Cars.Update(updatedCar);
            Database.Save();
        }
        public void IdentityBasicOperatorTest()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            // programatic mix in of claims rule and rule against the DTO user
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual");
            var claimRule = new Rule("@User", "S-1-5-21-2493390151-660934664-2262481224-513", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid");
            var re = new IdentityRuleEngine();
            // Compile the rules as a seperate step
            Expression<Func<CarDTO, IClaimsPrincipal, bool>> carRule1Expression = re.GetExpression<CarDTO>(carRule1);
            Expression<Func<CarDTO, IClaimsPrincipal, bool>> claimRuleExpression = re.GetExpression<CarDTO>(claimRule);
            Expression<Func<CarDTO, IClaimsPrincipal, bool>> compositeRule = carRule1Expression.Or(claimRuleExpression);

            // invoke the rules as a third step
            IClaimsPrincipal id = new ClaimsPrincipal(System.Threading.Thread.CurrentPrincipal);
            Assert.AreEqual(true,compositeRule.Compile()(car,id));
        }
        public void TuplesLoadFromFile()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            var salesperson = new SalesPersonDTO
            {
                State = "PA",
                IsManager = true,
                MaximumDiscount = 1000.0000m
            };

            // Load all rules applied to the user type.
            var re = new TupleRuleEngine();
            var xd = new XmlDocument();
            xd.Load(@"C:\development\RuleEngine\TinyTuleEngineUnitTest\TupleRuleEngineTest\RuleSetTuple.xml");
            re.LoadRulesFromElementList<CarDTO,SalesPersonDTO>(xd, "/rules/rule");

            Func<CarDTO, SalesPersonDTO, bool> fordSaleApproverWithSalesPersonInfo = re.GetRule<CarDTO,SalesPersonDTO>("FordSaleApproverWithSalesPersonInfo").Compile();
            Assert.AreEqual(true, fordSaleApproverWithSalesPersonInfo(car, salesperson));
        }
Exemplo n.º 5
0
        public CarDTO GetCar(int id)
        {
            var carEntity = _carOwnerContext.Cars.Find(id);
            var carDto    = new CarDTO()
            {
                IdCar       = carEntity.IdCar,
                Model       = carEntity.Model,
                Price       = carEntity.Price,
                YearRelease = carEntity.YearRelease,
                TypeCar     = (TypeCar)carEntity.TypeCar,
                СarMake     = carEntity.СarMake,
            };

            foreach (var owner in carEntity.OwnerEntities)
            {
                carDto.OwnerList.Add(new OwnerDTO()
                {
                    Name    = owner.Name,
                    Surname = owner.Surname
                });
            }
            carDto.DescriptionCar.ImageData = carEntity.DescriptionCar.ImageData;
            //carDto.DescriptionCar.ImageMineType = carEntity.DescriptionCar.ImageMineType;
            carDto.DescriptionCar.Description = carEntity.DescriptionCar.Description;
            return(carDto);
        }
Exemplo n.º 6
0
        public void AddOrUpdateCar(CarDTO car)
        {
            var carEntity = new CarEntity();

            if (car.IdCar != 0)
            {
                carEntity = _carOwnerContext.Cars.Find(car.IdCar);
                carEntity.DescriptionCar.Description = car.DescriptionCar.Description;
            }
            else
            {
                carEntity.DescriptionCar = new DescriptionCarEntity()
                {
                    Description   = car.DescriptionCar.Description,
                    ImageData     = car.DescriptionCar.ImageData,
                    ImageMineType = car.DescriptionCar.ImageMineType
                };
            }

            if (car.DescriptionCar.ImageData != null)
            {
                carEntity.DescriptionCar.ImageData     = car.DescriptionCar.ImageData;
                carEntity.DescriptionCar.ImageMineType = car.DescriptionCar.ImageMineType;
            }

            carEntity.IdCar       = car.IdCar;
            carEntity.Model       = car.Model;
            carEntity.Price       = car.Price;
            carEntity.YearRelease = car.YearRelease;
            carEntity.TypeCar     = (byte)car.TypeCar;
            carEntity.СarMake     = car.СarMake;

            _carOwnerContext.Cars.AddOrUpdate(carEntity);
        }
Exemplo n.º 7
0
        public bool UpdateQuantity(CarDTO dto, int quantity)
        {
            bool   result = false;
            string SQL    = "UPDATE Cars SET Quantity = Quantity - @Quantity " +
                            "WHERE ID = @ID";

            SqlConnection cnn = DBUtils.GetConnection();
            SqlCommand    cmd = new SqlCommand(SQL, cnn);

            cmd.Parameters.AddWithValue("@Quantity", quantity);
            cmd.Parameters.AddWithValue("@ID", dto.ID);

            try
            {
                if (cnn.State == ConnectionState.Closed)
                {
                    cnn.Open();
                }
                result = cmd.ExecuteNonQuery() > 0;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (cnn.State == ConnectionState.Open)
                {
                    cnn.Close();
                }
            }

            return(result);
        }
        public void CarDTO_Test()
        {
            // Setup

            // Act
            CarDTO carDTO  = Mapper.Map <CarDTO>(car);
            Car    testCar = Mapper.Map <Car>(carDTO);

            Car missingBestLapCar = new Car();

            car.Id        = carId;
            car.TrackId   = trackId;
            car.ImageName = imageName;
            car.Name      = name;
            car.Track     = new Track();
            CarDTO missingBestLapCarDTO = Mapper.Map <CarDTO>(missingBestLapCar);

            // Assert
            Assert.AreEqual(car.Id, carDTO.Id);
            Assert.AreEqual(car.ImageName, carDTO.ImageName);
            Assert.AreEqual(car.Name, carDTO.Name);
            Assert.AreEqual(car.BestLapTime.ApplicationUser.UserName, carDTO.RecordHolder);
            Assert.AreEqual(car.BestLapTime.LapTime.Time, carDTO.TrackRecord);

            Assert.AreEqual(car.Id, testCar.Id);
            Assert.AreEqual(car.ImageName, testCar.ImageName);
            Assert.AreEqual(car.Name, testCar.Name);

            Assert.AreEqual(new System.TimeSpan(0, 0, 59), missingBestLapCarDTO.TrackRecord);
            Assert.AreEqual("No Record set", missingBestLapCarDTO.RecordHolder);
        }
Exemplo n.º 9
0
        public async Task <bool> AddAsync(CarDTO carDto)
        {
            var car    = _mapper.Map <CarDTO, Car>(carDto);
            var result = await _carRepository.Add(car);

            return(result);
        }
Exemplo n.º 10
0
        public ActionResult Checkout(int id = 0)
        {
            if (id == 0)
            {
                return(HttpNotFound());
            }
            CarDTO          car    = DatAcessService.FindCar(id);
            List <OrderDTO> orders = DatAcessService.GetCarOrders(id);
            List <string>   dates  = new List <string>();

            foreach (var ord in orders)
            {
                for (DateTime i = ord.StartTime.Date; DateTime.Compare(i, ord.EndTime) <= 0; i = i.AddDays(1))
                {
                    dates.Add(i.ToString("MM/dd/yyyy"));
                }
            }


            if (car == null)
            {
                return(HttpNotFound());
            }
            OrderDTO order = new OrderDTO();

            order.Car                 = car;
            order.CarId               = car.Id;
            order.User_Id             = User.Identity.GetUserId();
            order.DriverLicenceNumber = DatAcessService.Users.FirstOrDefault(u => u.Id == order.User_Id).DriverLinenceNumber;
            ViewBag.FullOrdered       = dates;

            return(View(order));
        }
Exemplo n.º 11
0
        public CarViewModel(CarDTO carDTO)
        {
            CarId       = carDTO.CarId;
            Model       = carDTO.Model;
            ReleaseYear = carDTO.ReleaseYear;
            HorsePower  = carDTO.HorsePower;
            MakeId      = carDTO.MakeId;
            TypeId      = carDTO.TypeId;
            Make        = carDTO.Make;
            Type        = carDTO.Type;

            Makes = makeManagement.Get();
            Types = typeManagement.Get();

            /*
             * MakeViewModel makeVM = new MakeViewModel();
             * {
             *  makeVM.MakeId = carDTO.Make.MakeId;
             *  makeVM.Name = carDTO.Make.Name;
             *  makeVM.Description = carDTO.Make.Description;
             *  makeVM.Country = carDTO.Make.Country;
             * }
             *
             * TypeViewModel typeVM = new TypeViewModel();
             * {
             *  typeVM.TypeId = carDTO.Type.TypeId;
             *  typeVM.Name = carDTO.Type.Name;
             *  typeVM.Description = carDTO.Type.Description;
             * }
             */
        }
Exemplo n.º 12
0
        public Guid CreateCar(string registration)
        {
            Guid carId = Guid.NewGuid();

            var startingPosition = new PositionDTO()
            {
                XPosition = 0,
                YPosition = 0,
                Unit      = DistanceUnitDTO.Kilometers
            };

            var startingDistance = new DistanceDTO()
            {
                Unit  = DistanceUnitDTO.Kilometers,
                Value = 0
            };

            var carDto = new CarDTO()
            {
                CurrentDistance = startingDistance,
                CurrentPosition = startingPosition,
                Id = carId,
                RegistrationNumber = registration,
                Status             = CarStatusDTO.Free,
                TotalDistance      = startingDistance
            };

            _carService.CreateCar(carDto);

            return(carId);
        }
Exemplo n.º 13
0
        public void ShouldThrowExceptionWhenReturningCarWithEarlierStopTimeThanStartTime()
        {
            var driver = new DriverDTO
            {
                Id            = new Guid(),
                FirstName     = "Mikołaj",
                LastName      = "Fitowski",
                LicenseNumber = "CDJ813"
            };

            TestContainer.DriverService.CreateDriver(driver);

            var rentalArea = Helper.CreateRentalAreaDTO();

            TestContainer.RentalAreaService.CreateRentalArea(rentalArea);

            var car = new CarDTO
            {
                Id = new Guid(),
                RegistrationNumber = "KR12345",
                RentalAreaId       = rentalArea.Id,
                CurrentLatitude    = 50.057236,
                CurrentLongitude   = 19.945147
            };

            TestContainer.CarService.CreateCar(car);

            var rentalId  = new Guid();
            var startTime = new DateTime(2020, 04, 19);

            TestContainer.RentalService.TakeCar(rentalId, car.Id, driver.Id, startTime);
            var stopTime = new DateTime(2020, 04, 18);

            Assert.Throws <Exception>(() => TestContainer.RentalService.ReturnCar(rentalId, stopTime));
        }
        public async Task CanCreateAsync(CarDTO carDTO)
        {
            var modelTask = IsModelUnique(carDTO.CarModel);
            var descrTask = IsDescriptionUnique(carDTO.Description);

            await Task.WhenAll(modelTask, descrTask);
        }
Exemplo n.º 15
0
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.CarDetailsView);

            // Create your application here
            _httpClientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }
            };

            _httpClient = new HttpClient(_httpClientHandler);
            var uri = new Uri(string.Format("https://10.0.2.2:5001/api/car/1"));


            //_httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("applicatioj/json"));
            _dataTask = await _httpClient.GetAsync(uri);

            if (_dataTask.IsSuccessStatusCode)
            {
                _car = _dataTask.Content.ReadAsAsync <CarDTO>().Result;
            }

            FindViews();
            BindData();
        }
Exemplo n.º 16
0
        public async Task <IActionResult> PutCar(int id, CarDTO car)
        {
            if (id != car.id)
            {
                return(BadRequest());
            }

            _context.Entry(car).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CarExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemplo n.º 17
0
 public ActionResult AddCar(CarDTO carDTO)
 {
     try
     {
         if (!ModelState.IsValid)
         {
             var modelErrors = new List <string>();
             foreach (var value in ModelState.Values)
             {
                 foreach (var modelError in value.Errors)
                 {
                     modelErrors.Add(modelError.ErrorMessage);
                 }
             }
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, string.Join(",", modelErrors)));
         }
         var isAlreadyCreated = _getCarByPlateNumber.Execute(carDTO.PlateNumber) == null ?  false : true;
         if (isAlreadyCreated)
         {
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Car with this plate number already exist"));
         }
         _createCarCommand.Execute(carDTO);
         return(new HttpStatusCodeResult(HttpStatusCode.Created));
     }
     catch (Exception e)
     {
         return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
     }
 }
Exemplo n.º 18
0
        public ActionResult UpdateCar(int id, CarModel carModel)
        {
            if (carModel.Id != id)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var car = _getCarByIdCommand.Execute(id);

            if (car == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
            }
            CarDTO carDto = new CarDTO();

            carDto.Id               = carModel.Id;
            carDto.Name             = carModel.Name;
            carDto.BrandId          = carModel.BrandId;
            carDto.Brand            = carModel.Brand;
            carDto.ModelId          = carModel.ModelId;
            carDto.Model            = carModel.Model;
            carDto.OwnerId          = carModel.OwnerId;
            carDto.OwnerName        = carModel.OwnerName;
            carDto.Phone            = carModel.Phone;
            carDto.Year             = carModel.Year;
            carDto.HorsePower       = carModel.HorsePower;
            carDto.Engine           = carModel.Engine;
            carDto.EngineId         = carModel.EngineId;
            carDto.PlateNumber      = carModel.PlateNumber;
            carDto.KilometerCounter = carModel.KilometerCounter;


            carDto.TechnicalCheck = !string.IsNullOrEmpty(carModel.TechnicalCheck)? (DateTime?)DateTime.Parse(carModel.TechnicalCheck) : null;
            _updateCar.Execute(carDto);
            return(new HttpStatusCodeResult(HttpStatusCode.NoContent));
        }
Exemplo n.º 19
0
        public IHttpActionResult UpdateCar(int id, CarDTO carDTO)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var carFromDb = _carService.GetById(id);

            if (carFromDb == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            carFromDb.HasAirCondition = carDTO.HasAirCondition;
            carFromDb.HasEnsurance    = carDTO.HasEnsurance;
            carFromDb.HasNavigation   = carDTO.HasNavigation;
            carFromDb.IsAvailable     = true;
            carFromDb.PricePerDay     = carDTO.PricePerDay;
            carFromDb.NavigationPrice = carDTO.NavigationPrice;
            carFromDb.EnsurancePrice  = carDTO.EnsurancePrice;

            _uow.Save();
            return(Ok());
        }
Exemplo n.º 20
0
        public void UpdateCarShouldUpdateCarDTO()
        {
            //Arrange
            UnitOfWorkMock.Setup(u => u.Cars.GetByBrand(It.IsAny <string>())).Returns(new Car {
                CarsUsers = new List <CarUser>()
            });
            UnitOfWorkMock.Setup(u => u.Chassiss.GetByCodeNumber(It.IsAny <string>())).Returns(new Chassis());
            UnitOfWorkMock.Setup(u => u.Engines.GetByCylindersNumber(It.IsAny <int>())).Returns(new Engine());
            UnitOfWorkMock.Setup(u => u.Users.GetByName(It.IsAny <string>())).Returns(new User());
            UnitOfWorkMock.Setup(u => u.CarsUsers.GetByCarIdAndUserId(It.IsAny <Guid>(), It.IsAny <Guid>())).Returns(new CarUser());
            var carService = new CarService(UnitOfWorkMock.Object, MapperMock.Object);
            var carDTO     = new CarDTO
            {
                Brand     = "AAA",
                UsersName = new List <string> {
                    "John"
                }
            };
            Exception exception = null;

            //Act
            try
            {
                carService.UpdateCar(carDTO);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            //Assert
            Assert.IsNull(exception);
        }
Exemplo n.º 21
0
        private void BtnKaydet_Click(object sender, EventArgs e)
        {
            var dto = new CarDTO()
            {
                Id                   = Guid.NewGuid(),
                Plate                = txtPlate.Text,
                CarClassEnum         = (CarClassEnum)cmbCarClass.SelectedItem,
                EngineCapacity       = txtSilindirHac.Text,
                CylindeerVolume      = txtSilindirHac.Text,
                DailyPrice           = txtDailyPrice.Text,
                DriverLicenceType    = (DriverLicenceTypeEnum)cmbLicenceType.SelectedItem,
                InsuranceExpiryDate  = dtpsigorta.Value,
                InspectionExpiryDate = dtpkasko.Value,
                CarColorEnum         = (CarColorEnum)cmbColor.SelectedItem,
                DateOfPurchase       = dtpSatinAlmaTar.Value,
                FuelType             = (FuelTypeEnum)cmbFuelType.SelectedItem,
                IsRented             = false,
                ModelId              = (Guid)cmbModel.SelectedValue
            };
            var result = _cc.CarAdd(dto);

            result.NotificationShow();
            if (result.State == ResultState.Success)
            {
                txtPlate.Text         = "";
                dtpkasko.Value        = DateTime.Today;
                dtpSatinAlmaTar.Value = DateTime.Today;
                dtpsigorta.Value      = DateTime.Today;
            }
        }
Exemplo n.º 22
0
        public void UpdateCarShouldThrowExceptionOnNullEngineOfCarDTO()
        {
            //Arrange
            UnitOfWorkMock.Setup(u => u.Cars.GetByBrand(It.IsAny <string>())).Returns(new Car());
            UnitOfWorkMock.Setup(u => u.Chassiss.GetByCodeNumber(It.IsAny <string>())).Returns(new Chassis());
            UnitOfWorkMock.Setup(u => u.Engines.GetByCylindersNumber(It.IsAny <int>())).Returns(null as Engine);
            var carService = new CarService(UnitOfWorkMock.Object, MapperMock.Object);
            var carDTO     = new CarDTO
            {
                Brand = "AAA"
            };
            Exception exception = null;

            //Act
            try
            {
                carService.UpdateCar(carDTO);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            //Assert
            Assert.IsNotNull(exception);
        }
Exemplo n.º 23
0
        public ActionResult CreateCar(CreateCarViewModel item)
        {
            var model = _carModelService.GetCarModels().ToList().FirstOrDefault(it => it.Name == item.ModelName);

            if (model == null)
            {
                ModelState.AddModelError("ModelName", "Выберите модель авто!");
            }
            if (ModelState.IsValid)
            {
                var carDto = new CarDTO {
                    CarModelId = model.Id, RentalCenterId = 1
                };

                _carService.CreateCar(carDto);
            }

            var ModelsNames = new List <string>();

            foreach (var it in _carModelService.GetCarModels())
            {
                ModelsNames.Add(it.Name);
            }
            ViewBag.CarModel = ModelsNames;
            return(RedirectToAction("CreateCar"));
        }
Exemplo n.º 24
0
        private ConditionValidateDTO ValidateSecondConditionWithPlateAndIdentity(CarDTO carReturn, InfoCustomerDTO inforReturn, CheckInforCollectionDTO collectionInfo, CollectionCarDetailDTO detailInsurance)
        {
            CollectionCar sheetCar = _collectionCarRepository.FindAll().OrderByDescending(x => x.CreatedDate)
                                     .FirstOrDefault(x => x.CollectionSheet.InfoCustomerId == inforReturn.Id);

            if (sheetCar == null)
            {
                return(new ConditionValidateDTO(StatusCondition.ACCEPT_RE_NEW_BRIEF_INFOCUSTOMER_AND_CAR, inforReturn, carReturn, detailInsurance));
            }

            DateTime currentDate = DateTime.Now;

            if ((currentDate.Year - sheetCar.CollectionSheet.TransactionDate.Value.Year) <= 3)
            {
                return(new ConditionValidateDTO(StatusCondition.DENIED));
            }
            else
            {
                if (detailInsurance == null)
                {
                    return(new ConditionValidateDTO(StatusCondition.ACCEPT_RE_NEW_BRIEF_INFOCUSTOMER_AND_CAR, inforReturn, carReturn));
                }

                return(new ConditionValidateDTO(StatusCondition.ACCEPT_RE_NEW_BRIEF_INFOCUSTOMER_AND_CAR, inforReturn, carReturn, detailInsurance));
            }
        }
Exemplo n.º 25
0
        public bool Update()
        {
            var brands     = BrandFactoryDAL.GetCollectionDAL().GetAll();
            var carClasses = CarClassFactoryDAL.GetCollectionDAL().GetAll();
            var fuels      = FuelFactoryDAL.GetCollectionDAL().GetAll();

            CarDTO carDTO = new CarDTO
            {
                Id              = this.Id,
                BrandId         = brands[brands.FindIndex(item => item.Name == this.Brand)].Id,
                Model           = this.Model,
                Year            = this.Year,
                Price           = this.Price,
                Horsepower      = this.Horsepower,
                Torque          = this.Torque,
                Acceleration    = this.Acceleration,
                Topspeed        = this.Topspeed,
                CarClassId      = carClasses[carClasses.FindIndex(item => item.Name == this.CarClass)].Id,
                FuelId          = fuels[fuels.FindIndex(item => item.Name == this.Fuel)].Id,
                FuelConsumption = this.FuelConsumption,
                MadeByUser      = this.MadeByUser
            };

            return(CarFactoryDAL.GetDAL().Update(carDTO));
        }
Exemplo n.º 26
0
        public void CreateCar(CarDTO carDTO)
        {
            Expression <Func <Car, bool> > expressionPredicate = c => c.RegistrationNumber == carDTO.RegistrationNumber;
            var car = this._uoW.CarRepository.Find(expressionPredicate).FirstOrDefault();

            if (car != null)
            {
                throw new Exception($"Car with this registration number: {carDTO.RegistrationNumber} already exists");
            }

            var totalDistance   = new Distance(carDTO.TotalDistance.Value, (DistanceUnit)carDTO.TotalDistance.Unit);
            var currentDistance = new Distance(carDTO.CurrentDistance.Value, (DistanceUnit)carDTO.CurrentDistance.Unit);

            var position = new Position(carDTO.CurrentPosition.XPosition, carDTO.CurrentPosition.YPosition, (DistanceUnit)carDTO.CurrentPosition.Unit);

            car = new Car(
                carDTO.Id,
                carDTO.RegistrationNumber,
                (Status)carDTO.Status,
                position,
                currentDistance,
                totalDistance,
                _domainEventPublisher
                );

            this._uoW.CarRepository.Insert(car);
            this._uoW.Commit();
        }
        public void DriverDTO_Test()
        {
            // Act
            DriverDTO driverDTO = Mapper.Map <DriverDTO>(driver);
            CarDTO    carDTO    = Mapper.Map <CarDTO>(driver.Car);

            Driver testDriver = Mapper.Map <Driver>(driverDTO);
            Car    testCar    = Mapper.Map <Car>(driverDTO.SelectedCar);

            //Assert
            Assert.AreEqual(driver.Id, driverDTO.UserId);
            Assert.AreEqual(driver.ControllerId, driverDTO.ControllerId);
            Assert.AreEqual(driver.ApplicationUser.ImageName, driverDTO.ImageName);
            Assert.AreEqual(driver.ApplicationUser.UserName, driverDTO.UserName);


            Assert.AreEqual(carDTO.Id, driverDTO.SelectedCar.Id);
            Assert.AreEqual(carDTO.RecordHolder, driverDTO.SelectedCar.RecordHolder);
            Assert.AreEqual(carDTO.ImageName, driverDTO.SelectedCar.ImageName);
            Assert.AreEqual(carDTO.TrackRecord, driverDTO.SelectedCar.TrackRecord);

            Assert.AreEqual(driver.ControllerId, testDriver.ControllerId);
            Assert.AreEqual(driver.ApplicationUser.ImageName, testDriver.ApplicationUser.ImageName);
            Assert.AreEqual(carDTO.Id, testDriver.Car.Id);
//            Assert.AreEqual(carDTO.RecordHolder, testDriver.Car.BestLapTime.ApplicationUser.UserName);
            Assert.AreEqual(carDTO.ImageName, testDriver.Car.ImageName);
//            Assert.AreEqual(carDTO.TrackRecord, testDriver.Car.BestLapTime.LapTime.Time);
            Assert.AreEqual(driver.ApplicationUser.UserName, testDriver.ApplicationUser.UserName);
        }
Exemplo n.º 28
0
        public void AddCar(CarDTO car, IFormFileCollection fileCollection, string defaultWebPath)
        {
            CarDTO findCar = _mapper.Map <CarDTO>(Database.CarsRepository.GetCarsByPredicate(
                                                      c => c.Name == car.Name &&
                                                      c.Color == car.Color &&
                                                      c.YearCreate == car.YearCreate)
                                                  );

            RepeatException ex;

            if (findCar != null)
            {
                ex = new RepeatException("Данный продукт уже имеется на складе.", "Желаете ли сложить количество продуктов?", false);
                throw ex;
            }

            if (fileCollection == null)
            {
                throw new ValidationException("Коллекция фото пуста, пожалуйста добавьте фото!", "");
            }

            string path = defaultWebPath + @"\Images\Companies\" + findCar.CompanyName + @"\Cars\" + findCar.CarClassName + @"\" + findCar.Name;

            IEnumerable <ImageDTO> images = ImagesControl.AddImages(path, fileCollection);

            Database.CarsRepository.Add(_mapper.Map <CarEntity>(car));
            Database.ImagesRepository.Add(_mapper.Map <IEnumerable <ImageEntity> >(images));

            Database.Save();
        }
Exemplo n.º 29
0
        public CarDTO Map(RentalAreaViewModel selectedRentalArea, CarViewModel carViewModel,
                          bool provideCustomPosition = false)
        {
            var dto = new CarDTO
            {
                Id                 = carViewModel.Id,
                Status             = carViewModel.CarStatus,
                CurrentDistance    = double.Parse(carViewModel.CurrentDistance),
                PricePerMinute     = decimal.Parse(carViewModel.PricePerMinute),
                RegistrationNumber = carViewModel.RegistrationNumber,
                RentalAreaId       = selectedRentalArea.Id,
                RentalAreaName     = selectedRentalArea.Name,
                TotalDistance      = double.Parse(carViewModel.TotalDistance)
            };

            if (provideCustomPosition)
            {
                dto.CurrentLatitude  = double.Parse(carViewModel.CurrentLatitude);
                dto.CurrentLongitude = double.Parse(carViewModel.CurrentLongitude);
            }
            else
            {
                var positionDto = _positionVewModelMapper.Map(selectedRentalArea.CarStartingPosition);
                dto.CurrentLatitude  = positionDto.Latitude;
                dto.CurrentLongitude = positionDto.Longitude;
            }

            return(dto);
        }
        public void CreateCar(CarDTO carDTO)
        {
            Car createdCar = Mapper.Map <CarDTO, Car>(carDTO);

            Database.Cars.Create(createdCar);
            Database.Save();
        }
        public async void Post_CreateCar_ShouldWork()
        {
            var expected         = new CarDTO();
            var createCarRequest = new CreateCarRequest()
            {
                Make         = "Make",
                Model        = "Model",
                Registration = "Reg",
                Year         = 2000
            };
            var mediatorMock = new Mock <IMediator>();

            mediatorMock.Setup(t => t.Send(It.IsAny <CreateCarCommand>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(expected));
            var logger = new Mock <ILogger <CarController> >();

            var controller = new CarController(mediatorMock.Object, logger.Object);


            ValidateModelState(createCarRequest, controller);
            var response = await controller.Post(createCarRequest);

            var okResult = Assert.IsType <CreatedResult>(response);
            var car      = Assert.IsAssignableFrom <CarDTO>(okResult.Value);

            Assert.Equal(expected, car);
        }
        public void TuplesBasicOperatorTest()
        {
            // rule DTO  #1
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            // rule DTO  #2
            var salesperson = new SalesPersonDTO
            {
                State = "PA",
                IsManager = true,
                MaximumDiscount = 1000.0000m
            };

            // programatic mix in of claims rule and rule against the DTO user
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual","CarDTO");
            var salePersonRule1 = new Rule("State", "PA", "Equals", "SalesPersonDTO");
            var salePersonRule2 = new Rule("IsManager", "true", "Equals", "SalesPersonDTO");
            var re = new TupleRuleEngine();

            // Compile the rules as a seperate step
            Expression<Func<CarDTO, SalesPersonDTO, bool>> carRule1Expression = re.GetExpression<CarDTO, SalesPersonDTO>(carRule1);
            Expression<Func<CarDTO, SalesPersonDTO, bool>> salePersonRuleExpression1 = re.GetExpression<CarDTO, SalesPersonDTO>(salePersonRule1);
            Expression<Func<CarDTO, SalesPersonDTO, bool>> salePersonRuleExpression2 = re.GetExpression<CarDTO, SalesPersonDTO>(salePersonRule2);
            Expression<Func<CarDTO, SalesPersonDTO, bool>> compositeRule
                = carRule1Expression.Or(salePersonRuleExpression1).Or(salePersonRuleExpression2);

            Assert.AreEqual(true, compositeRule.Compile()(car, salesperson));
        }
Exemplo n.º 33
0
        public async void AddNewCar_ShouldAddNewCar()
        {
            IEnumerable <CarRowDTO> carsOnBegining = await GetCars();

            carsOnBegining.Count().Should().Be(0);

            await AddCar("BMW", 2000);

            IEnumerable <CarRowDTO> carsAfterNewCarAddedBmw = await GetCars();

            carsAfterNewCarAddedBmw.Count().Should().Be(1);
            carsAfterNewCarAddedBmw.ElementAt(0).Brand.Should().Be("BMW");
            carsAfterNewCarAddedBmw.ElementAt(0).YearOfProduction.Should().Be(2000);

            CarDTO car = await GetCar(carsAfterNewCarAddedBmw.ElementAt(0).Id);

            car.Brand.Should().Be("BMW");
            car.YearOfProduction.Should().Be(2000);

            await AddCar("Audi", 2009);

            IEnumerable <CarRowDTO> carsAfterNewCarAddedAudi = await GetCars();

            carsAfterNewCarAddedAudi.Count().Should().Be(2);
        }
Exemplo n.º 34
0
        public void BasicOperatorTest()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year=2010,
                Model="Expedition",
                AskingPrice=10000.0000m,
                SellingPrice=9000.0000m
            };

            // build up some rules
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual");
            var carRule2 = new Rule("AskingPrice", "10000.0000", "LessThanOrEqual");
            var carRule3= new Rule("Make", "Ford", "Equals");
            var carRule4 = new Rule("Model", "Ex", "StartsWith");  //gets the excursion, explorer, expedition -gass guzzlers

            var re = new RuleEngine();

            // Compile the rules as a seperate step
            Func<CarDTO, bool> carRule1Compiled = re.Compile<CarDTO>(carRule1);
            Func<CarDTO, bool> carRule2Compiled = re.Compile<CarDTO>(carRule2);
            Func<CarDTO, bool> carRule3Compiled = re.Compile<CarDTO>(carRule3);
            Func<CarDTO, bool> carRule4Compiled = re.Compile<CarDTO>(carRule4);

            Assert.AreEqual(true,carRule1Compiled(car));
            Assert.AreEqual(true,carRule2Compiled(car));
            Assert.AreEqual(true,carRule3Compiled(car));
            Assert.AreEqual(true,carRule4Compiled(car));
        }
Exemplo n.º 35
0
 public void LoadFromFile()
 {
     // rule DTO
     var car = new CarDTO
     {
         Make = "Ford",
         Year = 2010,
         Model = "Expedition",
         AskingPrice = 10000.0000m,
         SellingPrice = 9000.0000m
     };
     var re = new RuleEngine();
     var xd = new XmlDocument();
     xd.Load(@"C:\development\RuleEngine\TinyTuleEngineUnitTest\RuleEngineTest\RuleSetBasic.xml");
     re.LoadRulesFromElementList<CarDTO>(xd,"/rules/rule");
     Func<CarDTO, bool> isGasGuzzler = re.GetRule<CarDTO>("IsGasGuzzler").Compile();
     Assert.AreEqual(isGasGuzzler(car),true);
 }
 public void LiteralMathLoadFromFile()
 {
     // rule DTO
     var car = new CarDTO
     {
         Make = "Ford",
         Year = 2010,
         Model = "Expedition",
         AskingPrice = 10000.0000m,
         SellingPrice = 9000.0000m,
         AverageSellingPrice = 9500.000m,
         FixedComission = 100
     };
     var math = new SimpleMathEngine();
     var xd = new XmlDocument();
     xd.Load(@"C:\development\RuleEngine\TinyTuleEngineUnitTest\SimpleMath\SimpleMath.xml");
     math.LoadRulesFromElementList<CarDTO>(xd, "/mathexps/mathexp");
     Func<CarDTO, double> check = math.GetRule<CarDTO>("literal").Compile();
     var result = check(car);
 }
        public void IdentityTupleBasicOperatorTest()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            var salesperson = new SalesPersonDTO
            {
                State = "PA",
                IsManager = true,
                MaximumDiscount = 1000.0000m
            };

            // programatic mix in of claims rule and rule against the DTO for Car and SalesPerson
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual","CarDTO");
            var claimRule = new Rule("@User", "S-1-5-21-2493390151-660934664-2262481224-513", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid");
            var salePersonRule1 = new Rule("State", "PA", "Equals","SalesPersonDTO");
            var salePersonRule2 = new Rule("IsManager", "true", "Equals", "SalesPersonDTO");

            var re = new IdentityTupleRuleEngine();

            // build Some Expressions
            Expression<Func<CarDTO, SalesPersonDTO,IClaimsPrincipal, bool>> carRule1Expression = re.GetExpression<CarDTO,SalesPersonDTO>(carRule1);
            Expression<Func<CarDTO, SalesPersonDTO, IClaimsPrincipal, bool>> claimRuleExpression = re.GetExpression<CarDTO, SalesPersonDTO>(claimRule);
            Expression<Func<CarDTO, SalesPersonDTO, IClaimsPrincipal, bool>> sp1Expression = re.GetExpression<CarDTO, SalesPersonDTO>(salePersonRule1);
            Expression<Func<CarDTO, SalesPersonDTO, IClaimsPrincipal, bool>> sp2Expression = re.GetExpression<CarDTO, SalesPersonDTO>(salePersonRule2);

            Expression<Func<CarDTO, SalesPersonDTO, IClaimsPrincipal, bool>> coumpoundExpr =
                carRule1Expression.Or(claimRuleExpression).Or(sp1Expression).Or(sp2Expression);

            IClaimsPrincipal id = new ClaimsPrincipal(System.Threading.Thread.CurrentPrincipal);
            Assert.AreEqual(true, coumpoundExpr.Compile()(car,salesperson,id));
        }
        public void IdentityLoadFromFile()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            var re = new IdentityRuleEngine();

            // Load all rules applied to the user type.
            XmlDocument xd = new XmlDocument();
            xd.Load(@"C:\development\RuleEngine\TinyTuleEngineUnitTest\IdentityRuleEngineTest\RuleSetBasicIdentity.xml");
            re.LoadRulesFromElementList<CarDTO>(xd, "/rules/rule");

            Func<CarDTO, IClaimsPrincipal, bool> fordSaleApprover = re.GetRule<CarDTO>("FordSaleApprover").Compile();
            IClaimsPrincipal id = new ClaimsPrincipal(System.Threading.Thread.CurrentPrincipal);
            Assert.AreEqual(true, fordSaleApprover(car, id));
        }
Exemplo n.º 39
0
        public void StoreSomeRules()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            // build up some rules
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual");

            var re = new RuleEngine();

            // Get the rule expressions
            Expression<Func<CarDTO, bool>> carRule1Exp =re.GetExpression<CarDTO>(carRule1);

            // Save a rule Expression to the the list
            re.LoadRule("carrule", carRule1Exp);
            Assert.AreEqual(true, (re.GetRule<CarDTO>("carrule").Compile()(car)),
                "This car is greater than or equal to year 2010 but failed to rule as such");
        }
Exemplo n.º 40
0
        public void PredicatesTest()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            // build up some rules
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual");
            var carRule2 = new Rule("AskingPrice", "10000.0000", "LessThanOrEqual");
            var carRule3 = new Rule("Make", "Ford", "Equals");
            var carRule4 = new Rule("Model", "Ex", "StartsWith");  //gets the excursion, explorer, expedition -gas guzzlers

            var re = new RuleEngine();

            // Compile the rules as a seperate step
            Expression<Func<CarDTO, bool>> carRule1Exp = re.GetExpression<CarDTO>(carRule1);
            Expression<Func<CarDTO, bool>> carRule2Exp = re.GetExpression<CarDTO>(carRule2);
            Expression<Func<CarDTO, bool>> carRule3Exp = re.GetExpression<CarDTO>(carRule3);
            Expression<Func<CarDTO, bool>> carRule4Exp = re.GetExpression<CarDTO>(carRule4);

            // join the rules with fluent syntax ala predicate builder
            Expression<Func<CarDTO, bool>> compundedRule = carRule1Exp.Or(carRule2Exp).Or(carRule3Exp).Or(carRule4Exp);
            Func<CarDTO, bool> compiledRule = compundedRule.Compile();
            Assert.AreEqual(true, compiledRule(car), "car");
        }