public void OnActionExecuting(ActionExecutingContext context)
        {
            var session = context.HttpContext.Session;

            session.TryGet(out CarFilter filter);

            if (context.HttpContext.Request.HasFormContentType)
            {
                var form = context.HttpContext.Request.Form;

                filter = new CarFilter
                {
                    StateNumber = form["StateNumber"],
                    Mark        = form["Mark"],
                    ReleaseYear = int.Parse(form["ReleaseYear"])
                };

                session.Set(filter);
            }

            if (filter != null)
            {
                context.HttpContext.Items["StateNumber"] = filter.StateNumber;
                context.HttpContext.Items["Mark"]        = filter.Mark;
                context.HttpContext.Items["ReleaseYear"] = filter.ReleaseYear;
            }
        }
예제 #2
0
        private IQueryable <ViewCar> GetCarsByPrice(CarFilter filter, IQueryable <ViewCar> cars)
        {
            bool isInfinityMax = false;
            int  minPrice      = filter.priceFilter.minPrice;
            int  maxPrice      = filter.priceFilter.maxPrice;

            if (filter.priceFilter.maxPrice == 0)
            {
                isInfinityMax = true;
            }

            if (isInfinityMax && minPrice == 0)
            {
                // do nothing
            }
            else
            {
                if (minPrice < maxPrice)
                {
                    cars = cars.Where(c => c.price >= minPrice).Where(c => c.price <= maxPrice);
                }
                else
                {
                    if (isInfinityMax)
                    {
                        cars = cars.Where(c => c.price >= minPrice);
                    }
                }
            }

            return(cars);
        }
        public IActionResult Index(CarFilter filter, int page = 1, CarsSortState sortOrder = CarsSortState.StateNumberAsc)
        {
            if (!HttpContext.Session.TryGet(out IEnumerable <Car> cars, "Cars"))
            {
                cars = _context.Cars.AsQueryable();

                HttpContext.Session.Set(cars, "Cars");
            }

            ViewData["Marks"] = cars
                                .Select(c => new SelectListItem
            {
                Value    = c.Mark,
                Text     = c.Mark,
                Selected = c.Mark == ((string)HttpContext.Items["Mark"] ?? "")
            })
                                .Distinct(new SelectListItemEqualityComparer())
                                .ToList();

            cars = SortCars(cars, sortOrder);

            cars = cars
                   .Where(c => c.StateNumber.StartsWith(filter.StateNumber ?? ""))
                   .Where(c => c.Mark.StartsWith(filter.Mark ?? ""))
                   .Where(c => filter.ReleaseYear != 0 ? c.ReleaseYear == filter.ReleaseYear : true);

            var count = cars.Count();

            cars = cars.Skip((page - 1) * pageSize).Take(pageSize);

            ViewData["PageViewModel"] = new PageViewModel(count, page, pageSize);

            return(View(cars));
        }
        } // metod för att ta emot inputs för list raden och returnera det

        public void ShowPowerfulCars()
        {
            CarManager carMgr     = new CarManager();
            CarFilter  isPowerful = CarFilters.IsPowerful;

            Menus.PowerfulCarsMenu();
            carMgr.PrintWhere(isPowerful);
            Console.ReadKey();
        }
        public void ShowExpensiveCars()
        {
            CarManager carMgr      = new CarManager();
            CarFilter  isExpensive = CarFilters.IsExpensive;

            Menus.ExpensiveCarsMenu();
            carMgr.PrintWhere(isExpensive);
            Console.ReadKey();
        }
        public void ShowElectricCars()
        {
            CarManager carMgr     = new CarManager();
            CarFilter  isElectric = CarFilters.IsElectric;

            Menus.ElectricCarsMenu();
            carMgr.PrintWhere(isElectric);
            Console.ReadKey();
        }
        public void ShowNewCars()
        {
            CarManager carMgr = new CarManager();
            CarFilter  isNew  = CarFilters.IsNew;

            Menus.NewCarsMenu();
            carMgr.PrintWhere(isNew);
            Console.ReadKey();
        }
 public void PrintWhere(CarFilter filter)
 {
     foreach (var car in Cars.CarList)
     {
         if (filter(car))
         {
             Console.WriteLine("Make: {0}, Variant: {1}, Model year: {2}, Horse Power: {3}, Fuel: {4}, Price: {5}", car.Make, car.Variant, car.ModelYear, car.Power, car.Fuel, car.Price);
         }
     }
 }
예제 #9
0
        public async Task <IEnumerable <Car> > Search(CarFilter f)
        {
            IEnumerable <Car> cars = await _context.Cars.AsNoTracking().Where(
                x => x.Year >= f.YearMin &&
                x.Year <= f.YearMax &&
                (string.IsNullOrEmpty(f.Make) || x.Make == f.Make) &&
                (string.IsNullOrEmpty(f.Model) || x.Model == f.Model)
                )
                                     .ToListAsync();

            return(cars);
        }
예제 #10
0
        public HttpResponseMessage Get(int id)
        {
            var filters = new CarFilter();

            filters.CurrentPage = 1;
            filters.PageSize    = 1;
            filters.SortBy      = 1;

            var list = CarDb.GetCars(filters);

            return(CarDb.CreateJsonResponse(list));
        }
예제 #11
0
        public async Task <ActionResult> Cars([FromQuery] CarFilter carFilterParams)
        {
            try
            {
                var cars = await _carRepository.GetCarsAsync(carFilterParams);

                return(Ok(cars));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
예제 #12
0
        public async Task <ICollection <Car> > GetCarsAsync(CarFilter carFilterParams)
        {
            var filterData = carFilterParams;

            return(await _context.Cars.Include(p => p.BodyType)
                   .Include(p => p.Model)
                   .ThenInclude(p => p.Make)
                   .GetCarsByMake(filterData.MakeId)
                   .GetCarsByModel(filterData.ModelId)
                   .FilterByPrice(filterData.MinPrice, filterData.MaxPrice)
                   .GroupJoin(_context.Orders, c => c.CarId, o => o.CarId, (c, o) => c)
                   .Where(p => p.Order == null)
                   .ToListAsync());
        }
예제 #13
0
        public async Task <IHttpActionResult> Get([FromUri] CarFilter carFilter)
        {
            if (carFilter == null)
            {
                return(NotFound());
            }
            var result = await _carService.GetAll(carFilter);

            if (result == null)
            {
                return(NotFound());
            }
            return(Ok(result));
        }
예제 #14
0
        public HttpResponseMessage Search(CarFilter filters)
        {
            if (filters == null)
            {
                filters = new CarFilter();

                filters.CurrentPage = 1;
                filters.PageSize    = 10;
                filters.SortBy      = 1;
            }

            var list = CarDb.GetCars(filters);

            return(CarDb.CreateJsonResponse(list));
        }
예제 #15
0
 static public void TaskMain()
 {
     Task task = new Task(
         () =>
     {
         for (; ;)
         {
             if (CarFilter.FindKey("aa"))
             {
                 continue;
             }
             Thread.Sleep(10000);        // 每十秒做一次扫描
         }
     });
 }
예제 #16
0
        public List <CarResponse> Filter(CarFilter model)
        {
            if (model.BrandId != null && model.ModelId == null)
            {
                model.ModelId = dbContext.Models.Where(m => m.BrandId == model.BrandId).First().Id;
            }
            var cars = dbContext.Cars
                       .Where(car =>
                              car.DeletedAt == null &&
                              ((model.CostFrom == null && model.CostTo == null) || car.Cost >= model.CostFrom && car.Cost <= model.CostTo) &&
                              (model.Year == null || car.Year == model.Year) &&
                              (!model.DriverAirbag || car.DriverAirbag) &&
                              (!model.PassangerAirbag || car.PassangerAirbag) &&
                              (!model.Abs || car.Abs) &&
                              (!model.Asc || car.Asc) &&
                              (!model.Esp || car.Esp) &&
                              (!model.Climate || car.Climate) &&
                              (!model.Ac || car.Ac) &&
                              (!model.Cruise || car.Cruise) &&
                              (model.SeatsAmmount == null || car.SeatsAmmount == model.SeatsAmmount) &&
                              (model.EngineVol == null || car.EngineVol == model.EngineVol) &&
                              (model.Power == null || car.Power == model.Power) &&
                              (model.CarClassId == null || car.CarClassId == model.CarClassId) &&
                              (model.ModelId == null || car.ModelId == model.ModelId) &&
                              (model.FuelTypeId == null || car.FuelTypeId == model.FuelTypeId) &&
                              (model.BodyTypeId == null || car.BodyTypeId == model.BodyTypeId) &&
                              (model.DriveTypeId == null || car.DriveTypeId == model.DriveTypeId) &&
                              (model.GearBoxId == null || car.GearBoxId == model.GearBoxId)
                              )
                       .Include(c => c.DriveType)
                       .Include(c => c.GearBox)
                       .Include(c => c.Model).ThenInclude(m => m.Brand)
                       .Include(c => c.BodyType)
                       .OrderByDescending(c => c.Id)
                       .ToList()
                       .Sort(model.SortColumn, model.SortRule);
            var carsResponse = cars.Select(car => new CarResponse
            {
                Id        = car.Id,
                DriveType = car.DriveType.Name,
                GearBox   = car.GearBox.Name,
                Model     = car.Model.Name,
                Brand     = dbContext.Brands.Where(x => x.Id == car.Model.BrandId).First().Name,
                BodyType  = car.BodyType.Name
            }).ToList();

            return(carsResponse);
        }
        //https: //localhost:5001/api/CarAdministration?page=1&itemsPerPage=10&sortBy[]=name&sortDesc[]=false&mustSort=false&multiSort=false
        public CarDataTableModel GetCars([FromQuery] int page, [FromQuery] int itemsPerPage,
                                         [FromQuery(Name = "sortBy[]")] List <string> sortBy, [FromQuery(Name = "sortDesc[]")] List <bool> sortDesc)
        {
            var carFilter = new CarFilter()
            {
                ItemsPerPage = itemsPerPage,
                Page         = page,
                SortFilters  = sortBy.Select((s, i) => new SortFilter {
                    By = s, Descending = sortDesc[i]
                })
            };

            logger.LogInformation($"{nameof(sortBy)} {string.Concat(sortBy)}");
            logger.LogInformation($"{nameof(sortDesc)} {string.Concat(sortDesc)}");
            return(database.GetCars(carFilter));
        }
예제 #18
0
        public async Task <PagedCollection <CarDto> > GetAll(CarFilter carFilter)
        {
            if (carFilter == null)
            {
                throw new ArgumentNullException(nameof(carFilter));
            }

            var whereClause   = string.Empty;
            var orderByClause = "Order by ";

            if (!string.IsNullOrWhiteSpace(carFilter.Registration))
            {
                whereClause += whereClause.And(CarQuery.GetAllWhereRegistration);
            }
            if (carFilter.CarBrandId.HasValue)
            {
                whereClause += whereClause.And(CarQuery.GetAllWhereCarBrandId);
            }

            if (carFilter.FranchiseeId.HasValue)
            {
                whereClause += whereClause.And(CarQuery.GetAllWhereFranchiseeId);
            }
            if (carFilter.Kilometers.HasValue)
            {
                whereClause += whereClause.And(CarQuery.GetAllWhereKilometers);
            }

            if (string.IsNullOrWhiteSpace(carFilter.OrderBy))
            {
                orderByClause += "Id";
            }
            orderByClause += " " + carFilter.OrderDirection;

            var sql    = string.Format(CarQuery.GetAll, whereClause, orderByClause);
            var result = new PagedCollection <CarDto>();

            using (var reader = await ClcWorldContext.Database.Connection.QueryMultipleAsync(sql, carFilter))
            {
                result.Items = (await reader.ReadAsync <CarDto>()).ToList();
                result.Total = (await reader.ReadAsync <int>()).FirstOrDefault();
            }

            return(result);
        }
예제 #19
0
        public async void FilterWithYearMin()
        {
            var options = new DbContextOptionsBuilder <FleetDbContext>()
                          .UseInMemoryDatabase(databaseName: "Add_writes_to_database")
                          .Options;

            using (var context = new FleetDbContext(options))
            {
                context.Database.EnsureDeleted();
                ICarService carService = new CarService(context);
                context.Cars.AddRange(
                    new Car
                {
                    Id             = Guid.Parse("d9417f10-5c79-44a0-9137-4eba914a82a9"),
                    Make           = "Make 2",
                    Model          = "Malli 3",
                    Registration   = "XYZ-123",
                    Year           = 1998,
                    InspectionDate = new DateTime(2017, 3, 12),
                    EngineSize     = 2789.2,
                    EnginePower    = 235
                },
                    new Car
                {
                    Id             = Guid.NewGuid(),
                    Make           = "Make 1",
                    Model          = "Malli 2",
                    Registration   = "XYZ-124",
                    Year           = 2003,
                    InspectionDate = new DateTime(2018, 4, 11),
                    EngineSize     = 2606.2,
                    EnginePower    = 222
                });
                context.SaveChanges();

                var filter = new CarFilter {
                    YearMin = 2000, YearMax = int.MaxValue
                };
                var cars = await carService.Search(filter);

                Assert.NotNull(cars);
                Assert.Single(cars);
            }
        }
예제 #20
0
        public List <ViewCar> GetCars(CarFilter filter)
        {
            IQueryable <ViewCar> cars = db.ViewCars.Where(o => o.ordered.Equals("n"));

            /*
             * 1) производитель
             * 2) тип
             * 3) цвет
             * 4) автомат
             * 5) цена          (min > 0 and max (0 = IntMax, value => max = value & value >= min))
             * */

            cars = GetViewCars(filter.manufacturer, cars);
            cars = GetViewCarTypes(filter.type, cars);
            cars = GetViewCarColours(filter.colour, cars);
            cars = GetViewCarAutoTrans(filter.autoTrans, cars);
            cars = GetCarsByPrice(filter, cars);

            return(cars.ToList());
        }
예제 #21
0
        public async Task <IEnumerable <CarDto> > Search([FromQuery] CarFilter filter)
        {
            if (filter == null)
            {
                return((await _carService.GetAll()).Select(car => new CarDto
                {
                    Id = car.Id,
                    Make = car.Make,
                    Model = car.Model,
                    Registration = car.Registration,
                    Year = car.Year,
                    InspectionDate = car.InspectionDate,
                    EngineSize = car.EngineSize,
                    EnginePower = car.EnginePower
                }));
            }
            else
            {
                if (filter.YearMin == null)
                {
                    filter.YearMin = int.MinValue;
                }

                if (filter.YearMax == null)
                {
                    filter.YearMax = int.MaxValue;
                }

                return((await _carService.Search(filter)).Select(car => new CarDto
                {
                    Id = car.Id,
                    Make = car.Make,
                    Model = car.Model,
                    Registration = car.Registration,
                    Year = car.Year,
                    InspectionDate = car.InspectionDate,
                    EngineSize = car.EngineSize,
                    EnginePower = car.EnginePower
                }));
            }
        }
예제 #22
0
        private void initData()
        {
            carViewController = new CarViewController();
            carFilter         = new CarFilter();

            basket = new ShopBasket();

            carFormOperDTO = new CarOperationDTO();

            crud = new CarCrud(dataFormDTO.db);

            ComboBoxDataInit comboBoxData = new ComboBoxDataInit(dataFormDTO.db);

            comboBoxData.addCompanies(cbCarCompany);
            comboBoxData.addColours(cbCarColours);
            comboBoxData.addCarTypes(cbCarTypes);

            List <ViewCar> cars = dataFormDTO.db.ViewCars.Where(o => o.ordered.Equals("n")).ToList();

            dataGridView1.DataSource = cars;
        }
예제 #23
0
        public CarDataTableModel GetCars(CarFilter filter)
        {
            var resultQuery = cars;

            foreach (var sortFilter in filter.SortFilters)
            {
                resultQuery = sortFilter.By switch
                {
                    "name" => sortFilter.Descending
                                                ? resultQuery.OrderByDescending(i => i.Name)
                                                : resultQuery.OrderBy(i => i.Name),
                    "spz" => sortFilter.Descending
                                                ? resultQuery.OrderByDescending(i => i.Spz)
                                                : resultQuery.OrderBy(i => i.Spz),
                    "type" => sortFilter.Descending
                                                ? resultQuery.OrderByDescending(i => i.Type)
                                                : resultQuery.OrderBy(i => i.Spz),
                    _ => throw new ArgumentOutOfRangeException()
                };
            }

            var itemsToSkip = (filter.Page - 1) * filter.ItemsPerPage;

            resultQuery = resultQuery.Skip(itemsToSkip).Take(filter.ItemsPerPage);

            return(new CarDataTableModel
            {
                Items = resultQuery,
                ElementsMetadata =
                    new[]
                {
                    new FormElementMetadata
                    {
                        Type = "FormText", Key = "name", Label = "Nazev", ValidationRules = "alpha"
                    },
                    new FormElementMetadata
                    {
                        Type = "FormText", Key = "type", Label = "Typ", ValidationRules = "alpha"
                    },
                    new FormElementMetadata {
                        Type = "FormText", Key = "spz", Label = "Spz"
                    },
                    new FormElementMetadata {
                        Type = "FormDate", Key = "dateTime", Label = "Datum"
                    }
                },
                TotalItems = cars.Count(),
                Headers = new[]
                {
                    new CarDataTableHeader
                    {
                        Value = nameof(Car.Name).ToLower(), Text = "Nazev", Sortable = true, Type = "TableText"
                    },
                    new CarDataTableHeader
                    {
                        Value = nameof(Car.Spz).ToLower(), Text = "Spz", Sortable = true, Type = "TableText"
                    },
                    new CarDataTableHeader
                    {
                        Value = nameof(Car.Type).ToLower(),
                        Text = "Typ",
                        Sortable = true,
                        Type = "TableText"
                    },
                    new CarDataTableHeader
                    {
                        Value = "dateTime", Text = "Datum", Sortable = true, Type = "TableDate"
                    },
                    new CarDataTableHeader
                    {
                        Value = $"{nameof(Car.Administrator)}.{nameof(CarAdministrator.Name)}".ToLower(),
                        Text = "Spravce",
                        Sortable = true,
                        Type = "TableText"
                    }
                }
            });
        }
예제 #24
0
        public async Task <PagedResult <CarDto> > GetCars(CarFilter filter)
        {
            if (filter == null)
            {
                filter = new CarFilter();
            }

            if (filter?.PageSize < 0)
            {
                filter.PageSize = null;
            }
            if (filter?.PageNumber < 0)
            {
                filter.PageNumber = null;
            }

            IQueryable <Car> cars = _dbContext.Cars
                                    .Include(c => c.VehicleModel)
                                    .Include(c => c.Address);

            if (!string.IsNullOrWhiteSpace(filter?.VehicleType))
            {
                cars = cars.Where(c => c.VehicleModel.VehicleType.Contains(filter.VehicleType));
            }

            if (!string.IsNullOrEmpty(filter.PlateNumber))
            {
                cars = cars.Where(c => c.PlateNumber.Contains(filter.PlateNumber));
            }

            switch (filter.carOrder)
            {
            case CarFilter.CarOrder.PlateNumberAscending:
                cars = cars.OrderBy(c => c.PlateNumber);
                break;

            case CarFilter.CarOrder.PlateNumberDescending:
                cars = cars.OrderByDescending(c => c.PlateNumber);
                break;

            case CarFilter.CarOrder.VehicleTypeAscending:
                cars = cars.OrderBy(c => c.VehicleModel.VehicleType);
                break;

            case CarFilter.CarOrder.VehicleTypeDescending:
                cars = cars.OrderByDescending(c => c.VehicleModel.VehicleType);
                break;

            case CarFilter.CarOrder.ActiveAscending:
                cars = cars.OrderBy(c => c.Active);
                break;

            case CarFilter.CarOrder.ActiveDescending:
                cars = cars.OrderByDescending(c => c.Active);
                break;

            case CarFilter.CarOrder.AddressAscending:
                cars = cars.OrderBy(c => c.Address.ZipCode).OrderBy(c => c.Address.City).OrderBy(c => c.Address.StreetAddress);
                break;

            case CarFilter.CarOrder.AddressDescending:
                cars = cars.OrderByDescending(c => c.Address.ZipCode).OrderByDescending(c => c.Address.City).OrderByDescending(c => c.Address.StreetAddress);
                break;

            default:
                cars = cars.OrderBy(c => c.PlateNumber);
                break;
            }

            int?Total = null;

            if (((filter?.PageSize) ?? 0) != 0)
            {
                filter.PageNumber = filter.PageNumber ?? 0;
                Total             = cars.Count();
                cars = cars.Skip(filter.PageNumber.Value * filter.PageSize.Value).Take(filter.PageSize.Value);
            }

            var results = await cars
                          .Select(CarDtoSelector)
                          .ToListAsync();

            return(new PagedResult <CarDto>
            {
                Total = Total,
                PageNumber = filter.PageNumber,
                PageSize = filter.PageSize,
                Results = results
            });
        }
예제 #25
0
 public async Task <IDataResult <List <Car> > > GetAll(PageFilter pageFilter, CarFilter filter = null)
 {
     return(new SuccessPagedDataResult <List <Car> >(await _carDal.GetAllAsync(pageFilter, filter, c => c.Brand,
                                                                               c => c.Color, c => c.Company, c => c.Images)));
 }
예제 #26
0
        public async Task <IActionResult> OnGetAsync(string sortOrder, string vehicleType, string currentVehicleType, string plateNumber, string currentPlateNumber, int?pageNumber)
        {
            CarFilter filter = new CarFilter();

            CurrentSort = sortOrder;
            PlateSort   = string.IsNullOrEmpty(sortOrder) ? "plate_desc" : "";
            TypeSort    = sortOrder == "Type" ? "type_desc" : "Type";
            ActiveSort  = sortOrder == "Active" ? "active_desc" : "Active";
            AddressSort = sortOrder == "Address" ? "address_desc" : "Address";

            if (vehicleType != null || plateNumber != null)
            {
                pageNumber = 0;
            }
            else
            {
                if (string.IsNullOrEmpty(vehicleType))
                {
                    vehicleType = currentVehicleType;
                }

                if (string.IsNullOrEmpty(plateNumber))
                {
                    plateNumber = currentPlateNumber;
                }
            }

            VehicleType = vehicleType;
            PlateNumber = plateNumber;

            filter.PageNumber  = pageNumber ?? 0;
            filter.VehicleType = vehicleType;
            filter.PlateNumber = plateNumber;

            switch (sortOrder)
            {
            case "plate_desc": filter.carOrder = CarFilter.CarOrder.PlateNumberDescending;
                break;

            case "type_desc":
                filter.carOrder = CarFilter.CarOrder.VehicleTypeDescending;
                break;

            case "Type":
                filter.carOrder = CarFilter.CarOrder.VehicleTypeAscending;
                break;

            case "active_desc":
                filter.carOrder = CarFilter.CarOrder.ActiveDescending;
                break;

            case "Active":
                filter.carOrder = CarFilter.CarOrder.ActiveAscending;
                break;

            case "address_desc":
                filter.carOrder = CarFilter.CarOrder.AddressDescending;
                break;

            case "Address":
                filter.carOrder = CarFilter.CarOrder.AddressAscending;
                break;

            case "": filter.carOrder = CarFilter.CarOrder.PlateNumberAscending;
                break;

            default: filter.carOrder = CarFilter.CarOrder.PlateNumberAscending;
                break;
            }

            _logger.LogInformation(LoggingEvents.ListItems, "List Cars");
            Cars = await _carService.GetCars(filter);

            return(Page());
        }