Esempio n. 1
0
        private bool CreateVehicle()
        {
            VehicleDTO expectedVehicle = new VehicleDTO();

            expectedVehicle.Brand  = "Chevrolet";
            expectedVehicle.Model  = "Onyx";
            expectedVehicle.Year   = 2016;
            expectedVehicle.Color  = "Gris";
            expectedVehicle.Type   = "Auto";
            expectedVehicle.Vin    = "TEST1234";
            expectedVehicle.Id     = Guid.NewGuid();
            expectedVehicle.Status = StatusCode.InPort;
            VehicleDAO vehicleDAO   = new VehicleDAOImpl();
            VehicleDTO vehicleExist = vehicleDAO.FindVehicleByVin(expectedVehicle.Vin);
            bool       isAssigned   = false;

            if (vehicleExist == null)
            {
                vehicleDAO.AddVehicle(expectedVehicle);
            }
            else
            {
                isAssigned = vehicleDAO.IsAssigned("TEST1234");
            }
            return(isAssigned);
        }
Esempio n. 2
0
        public async Task <ActionResult> Update(VehicleInsertViewModel viewModel)
        {
            Response response = new Response();

            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <VehicleInsertViewModel, VehicleDTO>();
            });

            IMapper    mapper = configuration.CreateMapper();
            VehicleDTO dto    = mapper.Map <VehicleDTO>(viewModel);

            response = await _service.Update(dto);

            //Se funcionou, redireciona pra página inicial
            if (response.Success)
            {
                return(RedirectToAction("Index", "Vehicle"));
            }
            else
            {
                ViewBag.ErrorMessage = response.Errors;
                return(this.View());
            }
        }
        public async Task PostAsync([FromBody] VehicleDTO vehicleDTO, CancellationToken cancellationToken)
        {
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (vehicleDTO.VehicleID == Guid.Empty)
                {
                    throw new ArgumentNullException(paramName: nameof(vehicleDTO), $"VehicleDTO ID is null");
                }

                bool result = await _vehicleAPILogic.AddVehicle(vehicleDTO, cancellationToken);

                if (result)
                {
                    _logger.LogInformation($"Vehicle : {vehicleDTO.VehicleID} was successful added");
                }
                else
                {
                    _logger.LogError($"Error while adding Vehicle : {vehicleDTO.VehicleID}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                throw;
            }
        }
Esempio n. 4
0
        public string InsertOrUpdate(VehicleDTO vehicle)
        {
            try
            {
                var validate = Validate(vehicle);
                if (!string.IsNullOrEmpty(validate))
                {
                    return(validate);
                }

                if (ObjectExists(vehicle))
                {
                    return(GenericMessages.DatabaseErrorRecordAlreadyExists + Environment.NewLine +
                           "With the same Name/Tin No. Exists");
                }

                _vehicleRepository.InsertUpdate(vehicle);
                _unitOfWork.Commit();
                return(string.Empty);
            }
            catch (Exception exception)
            {
                return(exception.Message);
            }
        }
Esempio n. 5
0
        public bool ObjectExists(VehicleDTO vehicle)
        {
            var objectExists = false;
            var iDbContext   = DbContextUtil.GetDbContextInstance();

            try
            {
                var catRepository = new Repository <VehicleDTO>(iDbContext);
                var catExists     = catRepository.Query()
                                    .Filter(bp => (bp.PlateNumber == vehicle.PlateNumber) && bp.Id != vehicle.Id)
                                    .Get()
                                    .FirstOrDefault();


                if (catExists != null)
                {
                    objectExists = true;
                }
            }
            finally
            {
                iDbContext.Dispose();
            }

            return(objectExists);
        }
Esempio n. 6
0
        public int AddVehicle(VehicleDTO dto)
        {
            int id = 0;

            try
            {
                log.Debug(VehicleDTO.FormatVehicleDTO(dto));

                R_Vehicle t = VehicleDTO.ConvertDTOtoEntity(dto);

                // add
                id            = Repository.AddVehicle(t);
                dto.VehicleId = id;

                log.Debug("result: 'success', id: " + id);
            }
            catch (System.Exception e)
            {
                // error
                log.Error(e.ToString());

                throw;
            }

            return(id);
        }
Esempio n. 7
0
        public VehicleDTO GetVehicle(int vehicleId)
        {
            try
            {
                //Requires.NotNegative("vehicleId", vehicleId);

                log.Debug("vehicleId: " + vehicleId + " ");

                // get
                R_Vehicle t = Repository.GetVehicle(vehicleId);

                VehicleDTO dto = new VehicleDTO(t);

                log.Debug(VehicleDTO.FormatVehicleDTO(dto));

                return(dto);
            }
            catch (System.Exception e)
            {
                // error
                log.Error(e.ToString());

                throw;
            }
        }
        public bool Update(VehicleDTO pVehicle, int OfferId)
        {
            bool flag = false;

            // pVehicle.Capacity = VehicleCapacity[pVehicle.Type];
            // if (pVehicle.Capacity <= pVehicle.MaxOffer)
            //     return false;
            //     using (var context = new CarPoolContext())
            // {
            //     if (context.Offerrings.Find(pVehicle.Id).EndTime == DateTime.MinValue)
            //     {
            //         Offerring offer = context.Offerrings.Single(e => e.Id == OfferId);
            //          int count = context.Bookings.Where(e => e.OfferId == OfferId && e.Active && (e.BookingStatus==BookingStatus.REQUESTED||e.BookingStatus==BookingStatus.ACCEPTED)).Count();
            //         if (pVehicle.MaxOffer >= offer.SeatsOffered && count <= pVehicle.Capacity )
            //         {
            //                 Vechicles vechicles = context.Vechicles.Find(pVehicle.Id);
            //                 vechicles.NumberPlate = pVehicle.NumberPlate;
            //                 vechicles.Type =(int) Enum.Parse(typeof(VehicleType), pVehicle.Type);
            //                 vechicles.Capacity = VehicleCapacity[vechicles.Type];
            //         }
            //             offer.SeatsOffered = pVehicle.MaxOffer;

            //         context.SaveChanges();
            //         flag = true;

            //         }
            //         else
            //             flag = false;
            //     }
            return(flag);
        }
Esempio n. 9
0
        public async Task <IActionResult> CreateVehicle(VehicleModel vehModel)
        {
            if (vehModel == null || vehModel.licenceNum == null)
            {
                return(RedirectToAction("Index"));
            }

            //Get makes
            IEnumerable <MakeModel> makeList = MakeModel.CreateModelNumerable(await _beService.GetMakesAsync());

            VehicleDTO searchdto = await _beService.GetVehicleAsync(vehModel.licenceNum);

            if (searchdto != null)
            {
                //Add to dropdown
                ViewBag.selList = makeList;
                return(View("VehicleCreate", vehModel));
            }

            vehModel.state = "In";


            VehicleDTO dto = VehicleDTO.CreateDTO(vehModel);

            string response = await _beService.InsertVehicleAsync(dto);

            return(RedirectToAction("Index"));
        }
Esempio n. 10
0
        /// <summary>
        /// Resolves a damage history case that is open.
        /// </summary>
        /// <param name="damageModel">Damage model from user selection</param>
        /// <returns></returns>
        public async Task <IActionResult> ResolveDamages(DamageHistoryModel damageModel)
        {
            //Flip resolved to true so in future will only be viewable
            damageModel.resolved = true;

            //Update the db
            string response = await _beService.UpdateDamageHistoryAsync(DamageHistoryDTO.CreateDTO(damageModel));

            if (response != "Success")
            {
                return(RedirectToAction("ViewDamageImages", damageModel));
            }

            //Set the vehicle state to in so can be used again
            VehicleDTO veh = await _beService.GetVehicleAsync(damageModel.lplateNum);

            veh.state = "In";
            response  = await _beService.UpdateVehicleAsync(veh);

            if (response != "Success")
            {
                return(RedirectToAction("Index"));
            }

            return(RedirectToAction("Details", damageModel.lplateNum));
        }
Esempio n. 11
0
        public static void GeneratePopertyIds(this VehicleDTO vehicleDTO)
        {
            ObjectId objectId;

            vehicleDTO.Id = ObjectId.TryParse(vehicleDTO.Id, out objectId) ? objectId.ToString() : ObjectId.GenerateNewId().ToString();
            vehicleDTO.VehicleTechSpecification.Id = ObjectId.TryParse(vehicleDTO.VehicleTechSpecification.Id, out objectId) ? objectId.ToString() : ObjectId.GenerateNewId().ToString();
        }
        public async Task <Response> Update(VehicleDTO vehicle)
        {
            Response         response = new Response();
            VehicleValidator validate = new VehicleValidator();
            ValidationResult result   = validate.Validate(vehicle);

            if (!result.IsValid)
            {
                foreach (var failure in result.Errors)
                {
                    response.Errors.Add("Property " + failure.PropertyName + " failed validation. Error was: " + "(" + failure.ErrorMessage + ")");
                }

                return(response);
            }
            else
            {
                try
                {
                    return(response = await _iVehicleRepository.Update(vehicle));
                }
                catch (Exception ex)
                {
                    _log.Error(ex + "\nStackTrace: " + ex.StackTrace);
                    response.Errors.Add("DataBase error, contact the system owner");
                    return(response);
                }
            }
        }
Esempio n. 13
0
        public void SellVehicle(VehicleDTO vehicle)
        {
            if (vehicle.Price <= 0 || vehicle.Vin == null || vehicle.Vin == "")
            {
                throw new VehicleNullAttributesException("Se necesita un precio mayor a 0, y un vin para poder vender el vehiculo");
            }

            VehicleDTO realVehicle = this.vehicleDAO.FindVehicleByVin(vehicle.Vin);

            if (vehicle == null)
            {
                throw new VehicleNotFoundException("El vehiculo con vin: " + vehicle.Vin + " no esta registrado en el sistema.");
            }


            if (realVehicle.Status == StatusCode.ReadyToSell)
            {
                realVehicle.Price  = vehicle.Price;
                realVehicle.Status = StatusCode.Sold;

                this.vehicleDAO.UpdateVehicle(realVehicle);
            }
            else
            {
                throw new FlowStepOrderException("El vehiculo no se puede vender ya que no se encuentra listo para la venta.");
            }
        }
Esempio n. 14
0
        private VehicleDTO Create(VehicleViewModel viewModel)
        {
            try
            {
                log.Debug(VehicleViewModel.FormatVehicleViewModel(viewModel));

                VehicleDTO vehicle = new VehicleDTO();

                // copy values
                viewModel.UpdateDTO(vehicle, null); //RequestContext.Principal.Identity.GetUserId());

                // audit
                vehicle.CreateBy = null; //RequestContext.Principal.Identity.GetUserId();
                vehicle.CreateOn = DateTime.UtcNow;

                // add
                log.Debug("_vehicleService.AddVehicle - " + VehicleDTO.FormatVehicleDTO(vehicle));

                int id = _vehicleService.AddVehicle(vehicle);

                vehicle.VehicleId = id;

                log.Debug("result: 'success', id: " + id);

                return(vehicle);
            }
            catch (Exception e)
            {
                // error
                log.Error(e.ToString());

                throw;
            }
        }
Esempio n. 15
0
        public void StartTransportTest()
        {
            VehicleDTO        vehicleDTO = new VehicleDTO();
            List <Guid>       batches    = new List <Guid>();
            List <VehicleDTO> vehicles   = this.CreateVehicles();
            UserDTO           userDTO    = this.CreateUser();

            var mockInspectionService = new Mock <InspectionService>();

            mockInspectionService.Setup(vs => vs.ExistVehicleInspection("123")).Returns(true);
            var mockVehicleService = new Mock <VehicleService>();

            mockVehicleService.Setup(v => v.FindVehicleByVin("TEST1234")).Returns(vehicleDTO);
            mockVehicleService.Setup(v => v.UpdateVehicle(vehicleDTO));
            var mockTransportDAO = new Mock <TransportDAO>();
            var mockBatchService = new Mock <BatchService>();

            var transportService = new TransportServiceImpl(mockTransportDAO.Object, mockInspectionService.Object, mockBatchService.Object, mockVehicleService.Object);

            transportService.StartTransport(batches, userDTO);

            foreach (VehicleDTO vehicle in vehicles)
            {
                Assert.AreEqual(vehicle.Status, StatusCode.InTransit);
            }
        }
Esempio n. 16
0
        public void CreateInspectionTest()
        {
            List <DamageDTO> damages = this.CreateDamages();
            UserDTO          user    = this.CreateUser();
            VehicleDTO       vehicle = this.CreateVehicle();

            InspectionDTO inspection = new InspectionDTO();

            inspection.Damages         = damages;
            inspection.CreatorUserName = user.UserName;
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Puerto 1";
            inspection.IdVehicle       = vehicle.Vin;

            UserDTO userDTO = this.CreateUser();
            Guid    token   = Guid.NewGuid();

            var mockInspectionService = new Mock <InspectionService>();

            mockInspectionService.Setup(b => b.CreateInspection(inspection)).Verifiable();
            var mockUserService = new Mock <UserService>();

            mockUserService.Setup(us => us.GetUserLoggedIn(token)).Returns(userDTO);

            InspectionController inspectionController = new InspectionController(mockInspectionService.Object, mockUserService.Object);

            inspectionController.Request = createInspectionControllerRequest();
            this.addTokenHeaderToRequest(inspectionController.Request, token);

            ResponseMessageResult response = (ResponseMessageResult)inspectionController.Post(inspection);

            Assert.AreEqual(HttpStatusCode.OK, response.Response.StatusCode);
        }
Esempio n. 17
0
        /// <summary>
        /// <see cref="IDgtAppService"/>
        /// </summary>
        /// <returns><see cref="IDgtAppService"/></returns>
        public VehicleDTO AddNewVehicle(VehicleDTO vehicleDTO)
        {
            if (vehicleDTO == null)
            {
                throw new ArgumentNullException("vehicleDTO");
            }

            // Check vehicle license is unique
            var licenseSpec            = VehicleSpecifications.WithLicense(vehicleDTO.License);
            var repeatedLicenseVehicle = _vehicleRepository.AllMatching(licenseSpec);

            if (repeatedLicenseVehicle != null && repeatedLicenseVehicle.Any())
            {
                throw new InvalidOperationException(String.Format(CommonMessages.exception_ItemAlreadyExistsWithProperty, Names.Vehicle, Names.License, vehicleDTO.License));
            }

            // Cast dto to vehicle and save
            var vehicle = MaterializeVehicleFromDto(vehicleDTO);

            vehicle.GenerateNewIdentity();
            vehicle.CreatedDate = DateTime.Now;

            // Add habitual driver
            var driver = _driverRepository.Get(vehicleDTO.DriverId);

            if (driver == null)
            {
                throw new InvalidOperationException(String.Format(CommonMessages.exception_EntityWithIdNotExists,
                                                                  Names.Driver, vehicleDTO.DriverId));
            }

            // Check driver vehicles
            var driverVehicles = _vehicleDriverRepository.GetFiltered(vd => vd.DriverId == driver.Id);

            if (driverVehicles.Count() > 10)
            {
                throw new InvalidOperationException(String.Format(CommonMessages.exception_DriverMaxVehicles,
                                                                  driver.Identifier, 10));
            }

            // Add VehicleDriver item
            var vehicleDriver = new VehicleDriver()
            {
                VehicleId = vehicle.Id, DriverId = driver.Id
            };

            vehicleDriver.GenerateNewIdentity();
            vehicleDriver.CreatedDate = DateTime.Now;

            // Validate items and save
            vehicle.Validate();
            vehicleDriver.Validate();

            _vehicleRepository.Add(vehicle);
            _vehicleRepository.UnitOfWork.Commit();
            _vehicleDriverRepository.Add(vehicleDriver);
            _vehicleDriverRepository.UnitOfWork.Commit();

            return(vehicle.ProjectedAs <VehicleDTO>());
        }
        public async Task <(ResultInfo ResultInfo, VehicleDTO Result)> GetVehicleStatistics(int id)
        {
            try
            {
                var vehicle = await context.Vehicles.FirstOrDefaultAsync(x => x.Id == id);

                if (vehicle == null)
                {
                    return(ResultInfo.Fail(ErrorType.ValidationException, "Invalid VehicleID"), default(VehicleDTO));
                }

                var newResult = new VehicleDTO()
                {
                    Millage = vehicle.Millage,
                    NumberOfLightMalfunction = vehicle.NumberOfLightMalfunction,
                    ModifiedAt = vehicle.ModifiedAt,
                    IsDNF      = vehicle.IsDNF,
                    FinishedAt = vehicle.FinishedAt
                };

                return(ResultInfo.Ok(), newResult);
            }
            catch (Exception ex)
            {
                Serilog.Log.Error(ex.Message);
                return(ResultInfo.Fail(ErrorType.UnhandledException, ex.Message), default(VehicleDTO));
            }
        }
        public async Task <(ResultInfo ResultInfo, bool Result)> UpdateVehicle(VehicleDTO model)
        {
            try
            {
                var vehicle = await context.Vehicles.FirstOrDefaultAsync(x => x.Id == model.Id && x.Race.Status == RaceStatus.Pennding);

                if (vehicle == null)
                {
                    return(ResultInfo.Fail(ErrorType.ValidationException, "Invalid VehicleID"), default(bool));
                }

                vehicle.ManufacturingDate = model.ManufacturingDate;
                vehicle.Model             = model.Model;
                vehicle.TeamName          = model.TeamName;
                vehicle.Type    = model.Type;
                vehicle.SubType = model.SubType;

                context.Update(vehicle);
                await context.SaveChangesAsync();

                return(ResultInfo.Ok(), true);
            }
            catch (Exception ex)
            {
                Serilog.Log.Error(ex.Message);
                return(ResultInfo.Fail(ErrorType.UnhandledException, ex.Message), default(bool));
            }
        }
Esempio n. 20
0
        public static VehicleModel DomainToWeb(VehicleDTO vehicle)
        {
            VehicleModel ret = new VehicleModel()
            {
                VehicleId    = vehicle.VehicleId,
                DealershipId = vehicle.DealershipId,
                Make         = vehicle.Make,
                Model        = vehicle.Model,
                Year         = vehicle.Year,
                Color        = vehicle.Color,
                Condition    = vehicle.Condition,
                Type         = vehicle.Type,
                Price        = vehicle.Price,
                Mileage      = vehicle.Mileage,
                Latitude     = vehicle.Latitude,
                Longitude    = vehicle.Longitude,
                Address      = vehicle.Address,
                City         = vehicle.City,
                State        = vehicle.State,
                Zip          = vehicle.Zip,
                Phone        = vehicle.Phone,
                Name         = vehicle.Name,
                PriceMin     = vehicle.PriceMin,
                PriceMax     = vehicle.PriceMax
            };

            return(ret);
        }
Esempio n. 21
0
        public void CreateVehicle(VehicleDTO vehicleDto, int companyId)
        {
            using (var uow = UnitOfWorkProvider.Create())
            {
                var query = vehicleListQuery;
                query.ClearSortCriterias();
                query.Filter = new VehicleFilter {
                    LicencePlate = vehicleDto.LicencePlate
                };
                query.AddSortCriteria("LicencePlate", SortDirection.Ascending);
                query.Skip = 0;
                if (query.Execute().SingleOrDefault() != null)
                {
                    throw new ArgumentException("Vehicle service - CreateVehicle(...) vehicle with this licence plate already exists");
                }
                var vehicle = Mapper.Map <Vehicle>(vehicleDto);

                var company = companyRepository.GetById(companyId);
                if (company == null)
                {
                    throw new NullReferenceException("Vehicle service - CreateVehicle(...) company cant be null");
                }
                vehicle.Company = company;
                vehicle.Seats   = new List <Seat>();
                for (int i = 1; i <= vehicleDto.SeatCount; i++)
                {
                    var newSeat = CreateSeat(vehicle, i);
                    vehicle.Seats.Add(newSeat);
                    seatRepository.Insert(newSeat);
                }

                vehicleRepository.Insert(vehicle);
                uow.Commit();
            }
        }
        public async Task <ActionResult> ClockVehicle(ClockModel model)
        {
            try
            {
                //Check liscence plate belongs to active vehicle
                VehicleDTO dto = await _vehicleService.GetVehicleAsync(model.vehicle.licenceNum);

                //If not found
                if (dto == null)
                {
                    //Reutn error
                    ModelState.AddModelError("vehicle.licenceNum", "Vehicle not found.");
                    return(View(model));
                }
                //If there are any currently unresolved damage cases on the vehicle
                else if (dto.state == "Under Investigation")
                {
                    //Return error
                    ModelState.AddModelError("vehicle.licenceNum", "Vehicle currently unavailable due to potential damages. Please contact a member of staff.");
                    return(View(model));
                }

                //Create model from the DTO
                ClockModel newModel = ClockModel.CreateModel(dto);
                //Return view with the update model
                return(View(newModel));
            }
            catch
            {
                //Redirect tohe main blank page
                return(RedirectToAction("ClockVehicle"));
            }
        }
Esempio n. 23
0
        public static VehicleDTO Delete()
        {
            Console.Clear();
            Console.WriteLine("DELETE VEHICLE");

            Console.WriteLine("Insert a Chassis Series: (Example: XXX)");
            string chassisSeries = Console.ReadLine().ToUpper();

            Console.WriteLine("Insert a Chassis ID: (Example: 12345678)");
            if (!int.TryParse(Console.ReadLine(), out int chassisNumber))
            {
                Console.WriteLine("Chassis number must be numerical");
                Console.ReadLine();
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Are you sure you want to delete?    <Y> - YES | <N> - NO");

            string confirm = Console.ReadLine().ToUpper();

            if (confirm == "Y")
            {
                VehicleDTO objVehicle = new VehicleDTO();
                objVehicle.ChassisSeries = chassisSeries;
                objVehicle.ChassisNumber = chassisNumber;
                return(objVehicle);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 24
0
        public async Task <IHttpActionResult> PostRegisterVehicle(VehicleDTO vehicle)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                bool result = await _vehicleService.RegisterVehicleAsync(vehicle);

                if (result)
                {
                    return(StatusCode(HttpStatusCode.Created));
                }
                else
                {
                    return(StatusCode(HttpStatusCode.BadRequest));
                }
            }
            catch (Exception)
            {
                return(StatusCode(HttpStatusCode.ExpectationFailed));
            }
        }
Esempio n. 25
0
 public VehicleViewModel(VehicleDTO t)
 {
     VehicleId            = t.VehicleId;
     Make                 = t.Make;
     Model                = t.Model;
     Owner                = t.Owner;
     OwnerId              = t.OwnerId;
     NucleoId             = t.NucleoId;
     VehicleTypeId        = t.VehicleTypeId;
     EnergySourceId       = t.EnergySourceId;
     AverageSpeed         = t.AverageSpeed;
     HorsePower           = t.HorsePower;
     FuelConsumption      = t.FuelConsumption;
     FuelAutonomyDistance = t.FuelAutonomyDistance;
     RechargeTime         = t.RechargeTime;
     LicensePlate         = t.LicensePlate;
     Color                = t.Color;
     NumberSeats          = t.NumberSeats;
     CargoVolumeCapacity  = t.CargoVolumeCapacity;
     Active               = t.Active;
     IsDeleted            = t.IsDeleted;
     CreateBy             = t.CreateBy;
     CreateOn             = t.CreateOn;
     UpdateBy             = t.UpdateBy;
     UpdateOn             = t.UpdateOn;
 }
Esempio n. 26
0
        void UpdateVehicle()
        {
            VehicleDTO newVehicle = NewDTO();

            GetRepository().UpdateVehicle(newVehicle);
            FillAllVehicles();
        }
        public void AddNewVehicle(List <VehicleDTO> ListVehicle)
        {
            var vehicle = new VehicleDTO();

            Console.WriteLine();
            Console.WriteLine("******************| Insert new Vehicle |***********************");
            Console.WriteLine();
            while (vehicle.ChassisNumber == string.Empty || vehicle.ChassisNumber == null)
            {
                Console.WriteLine("Enter a Chassi Number: ");
                vehicle.ChassisNumber = (Console.ReadLine());
            }
            //Check if there is already the item informed
            if (!ListVehicle.Any(a => a.ChassisNumber.Contains(vehicle.ChassisNumber)))
            {
                bool correctType = false;
                var  type        = string.Empty;
                Console.WriteLine(typeStr);
                type = Console.ReadLine();
                while (!correctType)
                {
                    switch (type)
                    {
                    case "1":
                        vehicle.Type = VehicleType.Bus;
                        correctType  = true;
                        break;

                    case "2":
                        vehicle.Type = VehicleType.Truck;
                        correctType  = true;
                        break;

                    default:
                        Console.WriteLine(typeStr);
                        type = Console.ReadLine();
                        break;
                    }
                }

                while (vehicle.Color == string.Empty || vehicle.Color == null)
                {
                    Console.WriteLine("Type vehicle color: ");
                    vehicle.Color = Console.ReadLine();
                }

                ListVehicle.Add(vehicle);
                Logging("Vehicle with chassi number " + vehicle.ChassisNumber + " inserted successfully");
                Console.WriteLine();
                Console.WriteLine("Vehicle inserted successfully");
                Console.WriteLine();
                Console.WriteLine("Press any key to continue .. ");
            }
            else
            {
                Console.WriteLine("Vehicle already exists, please insert a new chassis");
                Console.WriteLine("Press any key to continue .. ");
            }
        }
Esempio n. 28
0
        public async Task <IServiceResponse <bool> > UpateVehicle(int id, VehicleDTO vehicle)
        {
            return(await HandleApiOperationAsync(async() => {
                await _vehicleService.UpdateVehicle(id, vehicle);

                return new ServiceResponse <bool>(true);
            }));
        }
Esempio n. 29
0
        public async Task <ServiceResponse <bool> > AddVehicle(VehicleDTO vehicle)
        {
            return(await HandleApiOperationAsync(async() => {
                await _vehicleService.AddVehicle(vehicle);

                return new ServiceResponse <bool>(true);
            }));
        }
Esempio n. 30
0
        public List <VehicleDTO> ImportVehicles(string path)
        {
            List <VehicleDTO> vehicles = new List <VehicleDTO>();
            XmlDocument       xmlDoc   = new XmlDocument();

            try
            {
                xmlDoc.Load(path);
                XmlNodeList nodeList = xmlDoc.SelectNodes("/Vehiculos/Vehiculo");
                int         count    = 1;
                foreach (XmlNode node in nodeList)
                {
                    bool       isValidParsing = true;
                    VehicleDTO vehicle        = new VehicleDTO();

                    vehicle.Brand = node["Marca"].InnerText;
                    if (string.IsNullOrWhiteSpace(vehicle.Brand))
                    {
                        isValidParsing = false;
                    }
                    vehicle.Model = node["Modelo"].InnerText;
                    string yearStr = node["Año"].InnerText;
                    vehicle.Color = node["Color"].InnerText;
                    vehicle.VIN   = node["VIN"].InnerText;
                    string typeStr = node["Tipo"].InnerText;
                    int    year;
                    if (int.TryParse(yearStr, out year))
                    {
                        vehicle.Year = year;
                    }
                    else
                    {
                        isValidParsing = false;
                    }

                    int typeVehicle;
                    if (int.TryParse(typeStr, out typeVehicle))
                    {
                        vehicle.Type = typeVehicle;
                    }
                    else
                    {
                        isValidParsing = false;
                    }
                    //Si se pudo parsear todos los atributos se agrega el producto a la lista
                    if (isValidParsing)
                    {
                        vehicles.Add(vehicle);
                        count++;
                    }
                }
            }
            catch (Exception ex)
            {
                //Se produjo un error logearlo
            }
            return(vehicles);
        }
 private VehicleDTO Map(tblEquipment tbl)
 {
     var dto = new VehicleDTO
     {
         MasterId = tbl.Id,
         DateCreated = tbl.IM_DateCreated,
         DateLastUpdated = tbl.IM_DateLastUpdated,
         StatusId = tbl.IM_Status,
         Name = tbl.Name,
         Code = tbl.Code,
         Description = tbl.Description,
         EquipmentNumber = tbl.EquipmentNumber,
         EquipmentTypeId = tbl.EquipmentType,
         HubId = tbl.CostCentreId,
         Make = tbl.Make,
         Model = tbl.Model
     };
     return dto;
 }
Esempio n. 32
0
 public Vehicle Map(VehicleDTO dto)
 {
     if (dto == null) return null;
     var vehicle = Mapper.Map<VehicleDTO, Vehicle>(dto);
     vehicle.CostCentre = _hubRepository.GetById(dto.HubId) as Hub;
     return vehicle;
 }