public void Post([FromBody] FlightDTO value)
 {
     if (ModelState.IsValid)
     {
         Service.Create(value);
     }
 }
Example #2
0
        public void UpdateEntity_Should_Update_Flight_in_db()
        {
            // Arrange
            var       flight    = dispatcherContext.Flights.FirstOrDefault(f => f.Number == 1111 && f.PointOfDeparture == "TestDeparture1");
            FlightDTO flightDTO = new FlightDTO
            {
                Number           = 1111,
                PointOfDeparture = "TestDeparture1",
                Destination      = "Paris",
                DepartureTime    = new DateTime(2018, 07, 12),
                DestinationTime  = new DateTime(2018, 07, 12)
            };

            flight = new Flight
            {
                Id               = flight.Id,
                Number           = 1111,
                PointOfDeparture = "TestDeparture1",
                Destination      = "Paris",
                DepartureTime    = new DateTime(2018, 07, 12),
                DestinationTime  = new DateTime(2018, 07, 12)
            };

            // Act

            _flightService.UpdateEntity(flight.Id, flightDTO);
            var flightResult = _flightRepository.Get(flight.Id);

            // Assert
            Assert.AreEqual(flight, flightResult);
        }
        /// <summary>
        /// The flight object creation request method
        /// </summary>
        /// <param name="req">the request from the user side</param>
        /// <returns>the response to the user side</returns>
        public ResponseFlightObject CreateFlightObject(RequestFlightObject req)
        {
            int       flightSerial = default(int);
            FlightDTO flight       = null;

            try
            {
                //gets a random serial
                flightSerial = arrivalSim.CreateFlightSerial();
                //creates a flight object in DB with a serial property only.
                //flight 'isAlive' prperty set to false
                flight = ctRepo.CreateFlightObject(flightSerial);
            }
            catch (Exception e)
            {
                throw new Exception($"Flight serial OR Flight object could not bet created. {e.Message}");
            }

            return(new ResponseFlightObject
            {
                Flight = flight,
                IsSuccess = true,
                Message = $"Flight #{flight.FlightSerial} has been created."
            });
        }
Example #4
0
        private void Create_Click(object sender, RoutedEventArgs e)
        {
            var        turple          = RenderCreate();
            Button     btnCreate       = turple.Item1;
            TextBox    number          = turple.Item2;
            TextBox    StartPoint      = turple.Item3;
            TextBox    FinishPoint     = turple.Item4;
            TimePicker StarTime        = turple.Item5;
            TimePicker FinishTime      = turple.Item6;
            ComboBox   SelectedTickets = turple.Item7;

            btnCreate.Click += async(object sen, RoutedEventArgs evArgs) =>
            {
                var flight = new FlightDTO()
                {
                    Number      = number.Text,
                    StartPoint  = StartPoint.Text,
                    FinishPoint = FinishPoint.Text,
                    StartTime   = (new DateTime(2018, 2, 2) + StarTime.Time).ToString(),
                    FinishTime  = (new DateTime(2018, 2, 2) + FinishTime.Time).ToString(),
                    TicketIds   = selectedTickets
                };
                try
                {
                    await service.CreateAsync(flight);
                }
                catch (Exception) { }

                flightsList.Add(flight);
                UpdateList();
                SingleItem.Children.Clear();
            };
        }
        public async Task UpdateEntityAsync(int id, FlightDTO flightDTO)
        {
            var flight = await flightRepository.GetAsync(id);

            if (flight == null)
            {
                throw new ValidationException($"Flight with this id {id} not found");
            }

            if (flightDTO.Number > 0)
            {
                flight.Number = flightDTO.Number;
            }
            if (flightDTO.PointOfDeparture != null)
            {
                flight.PointOfDeparture = flightDTO.PointOfDeparture;
            }
            if (flightDTO.Destination != null)
            {
                flight.Destination = flightDTO.Destination;
            }
            if (flightDTO.DepartureTime != DateTime.MinValue)
            {
                flight.DepartureTime = flightDTO.DepartureTime;
            }
            if (flightDTO.DestinationTime != DateTime.MinValue)
            {
                flight.DestinationTime = flightDTO.DestinationTime;
            }

            await flightRepository.UpdateAsync(flight).ConfigureAwait(false);
        }
Example #6
0
        [Test] // behaviour test
        public void Create_When_entity_is_created_Then_it_makes_calls_to_repository_and_unit_of_work()
        {
            // Arrange
            var flightDTOToCreate = new FlightDTO()
            {
                Number         = "AABBCC",
                DeparturePlace = "from place",
                DepartureTime  = new DateTime(1, 1, 1, 12, 0, 0),
                ArrivalPlace   = "to place",
                ArrivalTime    = new DateTime(1, 1, 1, 18, 0, 0)
            };

            var flightRepositoryFake = A.Fake <IFlightRepository>();

            var unitOfWorkFake = A.Fake <IUnitOfWork>();

            A.CallTo(() => unitOfWorkFake.Set <Flight>()).Returns(flightRepositoryFake);

            var flightService = new FlightService(unitOfWorkFake, AlwaysValidValidator);

            // Act
            var result = flightService.Create(flightDTOToCreate);

            // Assert. Just behaviour
            A.CallTo(() => flightRepositoryFake.Create(A <Flight> ._)).MustHaveHappenedOnceExactly();
            A.CallTo(() => unitOfWorkFake.Set <Flight>()).MustHaveHappenedOnceExactly();
            A.CallTo(() => unitOfWorkFake.SaveChanges()).MustHaveHappenedOnceExactly();
        }
Example #7
0
        [Test] //behavior test
        public void Update_When_entity_is_invalid_Then_it_makes_no_calls_to_repository_and_unit_of_work()
        {
            // Arrange
            var flightDTOToUpdate = new FlightDTO()
            {
                Id             = 3,
                Number         = "AABBCC",
                DeparturePlace = "from place",
                DepartureTime  = new DateTime(1, 1, 1, 12, 0, 0),
                ArrivalPlace   = "to place",
                ArrivalTime    = new DateTime(1, 1, 1, 18, 0, 0)
            };

            var flightRepositoryFake = A.Fake <IFlightRepository>();
            var unitOfWorkFake       = A.Fake <IUnitOfWork>();
            var flightService        = new FlightService(unitOfWorkFake, AlwaysInValidValidator);

            // Act + Assert
            var exception = Assert.Throws <BadRequestException>(() => flightService.Update(flightDTOToUpdate));

            A.CallTo(() => flightRepositoryFake.Update(A <Flight> ._)).MustNotHaveHappened();
            A.CallTo(() => unitOfWorkFake.FlightRepository).MustNotHaveHappened();
            A.CallTo(() => unitOfWorkFake.Set <Flight>()).MustNotHaveHappened();
            A.CallTo(() => unitOfWorkFake.SaveChanges()).MustNotHaveHappened();
        }
Example #8
0
        public void CreateEntity_Should_Create_flight_typeof_Flight()
        {
            // Arrange
            FlightDTO flightDTO = new FlightDTO
            {
                Id               = 1,
                Number           = 1111,
                PointOfDeparture = "Lviv",
                Destination      = "London",
                DepartureTime    = new DateTime(2018, 07, 12),
                DestinationTime  = new DateTime(2018, 07, 12)
            };
            Flight flight = new Flight
            {
                Id               = 1,
                Number           = 1111,
                PointOfDeparture = "Lviv",
                Destination      = "London",
                DepartureTime    = new DateTime(2018, 07, 12),
                DestinationTime  = new DateTime(2018, 07, 12)
            };

            var flightRepository = new FakeRepository <Flight>();
            var flightService    = new FlightService(flightRepository);

            // Act
            flightService.CreateEntity(flightDTO);
            var result = flightRepository.Get(1);

            // Assert
            Assert.AreEqual(flight, result);
        }
 public ActionResult <Entity> Post([FromBody] Flight flight)
 {
     // Console.WriteLine("entro al try");
     try
     {
         var validator = new FlightValidator(flight);
         validator.Validate();
         FlightMapper     _flightMapper     = MapperFactory.createFlightMapper();
         FlightDTO        _flight           = _flightMapper.CreateDTO(flight);
         AddFlightCommand _addFlightCommand = CommandFactory.AddFlightCommand(_flight);
         _addFlightCommand.Execute();
         return(Ok(new { Message = "¡Vuelo creado con éxito!" }));
     }
     catch (ValidationErrorException ex)
     {
         return(BadRequest(new { ex.Message }));
     }
     catch (DbErrorException ex)
     {
         return(BadRequest(new { ex.Message }));
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
         return(null);
     }
 }
Example #10
0
        /// <summary>Agrega vuelo a la DB</summary>
        /// <param name="entity">Entidad con vuelo a agregar a la DB</param>
        public int Add(FlightDTO flight)
        {
            try
            {
                var table = PgConnection.Instance.ExecuteFunction(
                    ADD_FLIGHT, flight.plane.Id, flight.price, flight.departure, flight.arrival, flight.loc_departure.Id, flight.loc_arrival.Id
                    );

                if (table.Rows.Count > 0)
                {
                    return(Convert.ToInt32(table.Rows[0][0]));
                }

                return(0);
            }
            catch (DatabaseException ex)
            {
                Console.WriteLine(ex.ToString());
                Console.WriteLine(ex.Message);
                throw new DbErrorException("¡Ups! Hubo un error con la Base de Datos", ex);
            }
            finally
            {
            }
        }
 public void Put(int id, [FromBody] FlightDTO flight)
 {
     if (ModelState.IsValid)
     {
         service.Update(id, flight);
     }
 }
Example #12
0
        public void UpdateFlight_WhenDataIsCorrect_CheckResult()
        {
            TestEnvironmentManager.DeleteFlightTest(FlightService, FlightDTO.Name);

            if (FlightController.CreateFlight(FlightDTO).Result.GetType().Name.Equals("OkNegotiatedContentResult`1"))
            {
                FlightDTO = DistributedServicesAutoMapper.Map <FlightDTO>(FlightService.GetFlight(new Domain.BO.Flights.FlightDTO {
                    Name = FlightDTO.Name
                }));

                FlightDTO.Name += "_Updated";
                FlightDTO.DepartureAirport.AirportId   = 17;
                FlightDTO.DepartureAirport.Name        = "Málaga (AGP)";
                FlightDTO.DestinationAirport.AirportId = 18;
                FlightDTO.DestinationAirport.Name      = "Sevilla (SEV)";
                var response = FlightController.UpdateFlight(FlightDTO);
                Assert.IsNotNull(response);

                TestEnvironmentManager.DeleteFlightTest(FlightService, FlightDTO.Name);
            }
            else
            {
                Assert.Fail();
            }
        }
 public void Post([FromBody] FlightDTO flight)
 {
     if (ModelState.IsValid)
     {
         service.Create(flight);
     }
 }
Example #14
0
        public async Task <IHttpActionResult> CreateFlight(FlightDTO model)
        {
            var resultMessage = string.Empty;

            try
            {
                //TraceManager.StartMethodTrace(Traces.IndexStackFrameAsynController, "model: " + JsonConvert.SerializeObject(model));

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var request = DistributedServicesAutoMapper.Map <Domain.BO.Flights.FlightDTO>(model);

                FlightServices.CreateFlight(request);

                resultMessage = SharedLanguage.REQUEST_SUCCESSFUL;

                return(Ok(resultMessage));
            }
            catch (Exception ex)
            {
                resultMessage = ""; //TraceManager.ExceptionErrorTrace(ex, Traces.IndexStackFrameAsynController);
                return(ResponseMessage(HttpHelper.GetHttpResponseErrorMessage(resultMessage)));
            }
            finally
            {
                //TraceManager.FinishMethodTrace(Traces.IndexStackFrameAsynController, "resultMessage: " + resultMessage);
            }
        }
        public async Task <IActionResult> Update(int id, [FromBody] FlightDTO item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                item.Id = id;
                await service.GetById(id);

                await service.Update(item);

                await service.SaveChanges();

                return(Ok(item));
            }
            catch (NotFoundException e)
            {
                return(NotFound(e.Message));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Example #16
0
        public void UpdateFlight(FlightDTO dto)
        {
            var flight = _db.Flights
                         .Include(x => x.Airplane)
                         .Include(x => x.City)
                         .FirstOrDefault(x => x.Id == dto.Id);

            var city = _db.Cities.FirstOrDefault(x => x.Id == dto.CityId);

            var currentCityName = ConfigurationManager.AppSettings["CurrentCityName"];

            DateTime.TryParseExact(dto.Time, "H:mm", null, System.Globalization.DateTimeStyles.None, out var time);

            flight.FlightNumber = dto.FlightNumber;
            flight.Time         = time;
            flight.Tittle       = flight.IsArrival
                    ? $"{city.Name} - {currentCityName}"
                    : $"{currentCityName} - {city.Name}";
            flight.CityId            = dto.CityId;
            flight.AirplaneId        = dto.AirplaneId;
            flight.SoldTicketsAmount = dto.SoldTicketsAmount;

            _db.Update(flight);
            _db.SaveChanges();
        }
Example #17
0
        public IHttpActionResult GetFlight(int id, bool showAll = true)
        {
            Flight flight = db.Flights.Find(id);

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

            FlightDTO flightInfo = new FlightDTO
            {
                Id         = flight.FlightId,
                CityFrom   = flight.CityFrom.CityName,
                CityTo     = flight.CityTo.CityName,
                FlightTime = flight.FlightTime
            };

            if (flight.FlightsPass != null)
            {
                var passengerQuery = flight.FlightsPass.AsQueryable();
                if (!showAll)
                {
                    passengerQuery = passengerQuery.Where(p => !p.IsCheckedIn);
                }

                flightInfo.passengerInfos = passengerQuery.Select(p => new PassengerInfoDTO {
                    Id        = p.PassengerId,
                    FirstName = p.Passenger.FirstName,
                    LastName  = p.Passenger.LastName,
                    IsChecked = p.IsCheckedIn
                }).ToList();
            }

            return(Ok(flightInfo));
        }
Example #18
0
        public FlightDTO AddFlight(FlightDTO flight)
        {
            Validation(flight);
            Flight modelFlight = mapper.Map <FlightDTO, Flight>(flight);

            return(mapper.Map <Flight, FlightDTO>(unitOfWork.Flights.Create(modelFlight)));
        }
        /// <summary>
        /// Determines the terminal checkpoints's state
        /// </summary>
        /// <param name="flight">the current flight in check</param>
        /// <returns>the terminal state represented in bool value</returns>
        protected bool EvaluateTerminalState(FlightDTO flight)
        {
            bool isBoarding = default(bool);

            if (FlightInTerminal1.FlightSerial == flight.FlightSerial)
            {
                if (Terminal1State == $"{TerminalState.Unloading}...")
                {
                    isBoarding = false;
                }
                else if (Terminal1State == $"...{TerminalState.Boarding}")
                {
                    isBoarding = true;
                }
            }
            else if (FlightInTerminal2.FlightSerial == flight.FlightSerial)
            {
                if (Terminal2State == $"{TerminalState.Unloading}...")
                {
                    isBoarding = false;
                }
                else if (Terminal2State == $"...{TerminalState.Boarding}")
                {
                    isBoarding = true;
                }
            }
            return(isBoarding);
        }
        /// <summary>
        /// the current flight's promotion timer event
        /// </summary>
        /// <param name="sender">the timer caller</param>
        /// <param name="e">the event arguments of the event</param>
        void PromotionTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //the promotion timer pauses until the current promotion evaluation finishes
            simProxy.flightsTimers.Values.FirstOrDefault(t => t == sender as Timer).Stop();

            FlightDTO flight = null;

            //the flight that the timer belongs to is retreived from the simproxy flight_timer
            foreach (FlightDTO fdto in simProxy.flightsTimers.Keys)
            {
                //the sender timer's hash code is compared
                if (simProxy.flightsTimers[fdto].GetHashCode() == sender.GetHashCode())
                {
                    //the proxy raises the onpromotion event
                    simProxy.OnPromotion(fdto);
                    //all additional data is retreived to the flight object
                    flight = simProxy.GetFlight(fdto.FlightSerial);
                    break;
                }
            }
            //after the last checkpoint, the flight & timer are disposed, so no need to unpause the promotion timer
            if (flight != null)
            {
                simProxy.flightsTimers.FirstOrDefault(pair => pair.Key.FlightSerial == flight.FlightSerial).Value.Start();
            }
        }
Example #21
0
        public FlightDTO GetFlight(FlightDTO request)
        {
            var flightEntity = DomainAutoMapper.Map <Flight>(request);
            var flight       = FlightRepository.GetFlights(flightEntity).FirstOrDefault();

            return(DomainAutoMapper.Map <FlightDTO>(flight));
        }
        public async Task <ActionResult <List <FlightDTO> > > GetAllFlights()
        {
            AirlineCompanyProfile profile = new AirlineCompanyProfile();

            AuthenticateAndGetTokenAndGetFacade(out LoginToken <AirlineCompany>
                                                token_airline, out LoggedInAirlineFacade facade);

            List <FlightDTO> result = null;

            try
            {
                List <Flight> list = await Task.Run(() => facade.GetAllFlights()) as List <Flight>;

                List <FlightDTO> flightDTOList = new List <FlightDTO>();

                foreach (Flight flight in list)
                {
                    //added our own m_mapper
                    FlightDTO flightDTO = m_mapper.Map <Flight, FlightDTO>(flight);
                    flightDTOList.Add(flightDTO);
                }
                result = flightDTOList;
            }
            catch (Exception ex)
            {
                return(StatusCode(400, $"{{ error: can't get all flights \"{ex.Message}\" }}"));
            }
            if (result == null)
            {
                return(StatusCode(204, "{The list is empty.}"));
            }
            return(Ok(result));
        }
Example #23
0
        private void AddFlightButton_Click(object sender, EventArgs e)
        {
            var selectedCity     = (CityDTO)FlightCityComboBox.SelectedItem;
            var selectedAirplane = (AirplaneDTO)FlightAirplaneComboBox.SelectedItem;
            var currentCityName  = ConfigurationManager.AppSettings["CurrentCityName"];

            if (IsValidForm())
            {
                FlightDTO = new FlightDTO
                {
                    AirplaneId        = selectedAirplane.Id,
                    CityId            = selectedCity.Id,
                    FlightNumber      = FlightNumberTextBox.Text,
                    IsArrival         = !IsDepartureCheckBox.Checked,
                    RegistryNumber    = (int)RegistryNumberComboBox.SelectedItem,
                    SoldTicketsAmount = (int)SoldTicketsAmountNumeric.Value,
                    Time   = FlightTimePicker.Value.ToString("H:mm"),
                    Tittle = IsDepartureCheckBox.Checked
                    ? $"{currentCityName} - {selectedCity.Name}"
                    : $"{selectedCity.Name} - {currentCityName}"
                };

                DialogResult = DialogResult.OK;
            }
            else
            {
                var errorTextBuilder = new StringBuilder();
                errorTextBuilder.AppendJoin("\n", _errorMessagesList).ToString();
                errorTextBuilder.AppendLine("\n\nПроверьте вводимые значения и попробуйте еще раз.");
                var errorText = errorTextBuilder.ToString();
                MessageBox.Show(errorText, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _errorMessagesList = new List <string>();
            }
        }
        private FlightDTO CreateFlightDTO(List <Flight> flights, bool isReturnFlight)
        {
            var result = new FlightDTO();

            flights = flights.OrderBy(f => f.DepartureDateTime).ToList();

            result.Aircraft = string.Join(",",
                                          flights.Select(f => f.Aircraft.Model).Distinct());
            result.ArrivalAirport = flights.Last().DestinationAirport.IataCode;
            result.ArrivalTime    = flights.Last().ArrivalDateTime;
            result.Carrier        = string.Join(",",
                                                flights.Select(f => f.Carrier.Name).Distinct());
            result.DepartureAirport = flights.First().OriginAirport.IataCode;
            result.DepartureTime    = flights.First().DepartureDateTime;
            result.FlightDuration   = (result.ArrivalTime - result.DepartureTime).ToString();
            result.IsAmadeusFlight  = false;
            result.IsFlightDirect   = flights.Count == 1;
            result.IsReturnFlight   = isReturnFlight;
            result.Prices           = flights
                                      .SelectMany(f => f.Prices)
                                      .GroupBy(fp => (fp.TravelClass, fp.TravelerType), fp => fp.Price)
                                      .Select(g => new FlightPriceDTO()
            {
                TravelClass  = g.Key.TravelClass,
                TravelerType = g.Key.TravelerType,
                Price        = g.Sum()
            })
                                      .ToList();;
            result.Stops = createFlightStops(flights);

            return(result);
        }
        public ActionResult <HttpResponseDTO> Post([Required, FromBody] FlightDTO flight)
        {
            Flight dbModel = FlightDTO.ToDBModel(flight);

            try
            {
                airportService.HandleNewFlightArrivedAsync(dbModel);
                HttpResponseDTO response = new()
                {
                    ResponseType = Constants.RESPONSE_TYPE_SUCCESS,
                    Message      = "Generated flight successfully.",
                };
                return(StatusCode(StatusCodes.Status201Created, response));
            }
            catch (Exception e)
            {
                HttpResponseDTO response = new()
                {
                    ResponseType  = Constants.RESPONSE_TYPE_FAILURE,
                    Message       = Constants.UNKNOWN_ERROR_MSG,
                    FailureReason = e.Message
                };
                return(StatusCode(StatusCodes.Status500InternalServerError, response));
            }
        }
    }
Example #26
0
        public void AddFlight(FlightDTO dto)
        {
            var city = _db.Cities.FirstOrDefault(x => x.Id == dto.CityId);

            var currentCityName = ConfigurationManager.AppSettings["CurrentCityName"];

            DateTime.TryParseExact(dto.Time, "H:mm", null, System.Globalization.DateTimeStyles.None, out var time);

            var flight = new Flight
            {
                FlightNumber = dto.FlightNumber,
                IsArrival    = dto.IsArrival,
                Tittle       = dto.IsArrival
                    ? $"{city.Name} - {currentCityName}"
                    : $"{currentCityName} - {city.Name}",
                Time              = time,
                RegistryNumber    = dto.RegistryNumber,
                CityId            = dto.CityId,
                AirplaneId        = dto.AirplaneId,
                SoldTicketsAmount = dto.SoldTicketsAmount
            };

            _db.Flights.Add(flight);
            _db.SaveChanges();
        }
        public async Task Update(int id, FlightDTO modelDTO)
        {
            var source = uow.Flights.Get(id);
            var dest   = mapper.Map <FlightDTO, Flight>(modelDTO);
            await uow.Flights.Update(dest);

            await uow.SaveAsync();
        }
Example #28
0
 public void FlightAdd(FlightDTO flightDTO)
 {
     if (ListsInitialized)
     {
         FutureFlights.Add(flightDTO);
         UpdateFutureFlights();
     }
 }
Example #29
0
 public void Create(FlightDTO flightDTO)
 {
     if (flightDTO != null)
     {
         var flight = _mapper.Map <Flight>(flightDTO);
         _unitOfWork.FlightRepository.Create(flight);
     }
 }
Example #30
0
        private string TicketsId(FlightDTO flight)
        {
            var result = "count : " + flight.TicketsId.Count + " (";

            flight.TicketsId.ToList().ForEach(x => result += " Id:" + x.ToString());
            result += " )";
            return(result);
        }