Example #1
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // grab the scheduled flight parameter
            ScheduledFlight sf = e.Parameter as ScheduledFlight;

            // display some header text
            HeaderText.Text = $"Flight: {sf.Flight.FlightNumber} from {sf.Flight.Origin.City} to {sf.Flight.Destination.City} on {sf.DepartureTime.ToShortDateString()}";
            // and a base for the passengers list
            PassengersText.Text = "Passengers:";

            using var db = new AirContext();
            // grab all the trips in the db, making sure to include their tickets and scheduled flights
            var trips = db.Trips.Include(trip => trip.Tickets)
                        .ThenInclude(ticket => ticket.Flight);

            // loop through every trip
            foreach (Trip trip in trips)
            {
                // grab the user that is associated with this trip's customer info
                CustomerInfo customer = db.Users.Include(user => user.CustInfo)
                                        .Single(user => user.CustInfo.CustomerInfoId == trip.CustomerInfoId).CustInfo;
                foreach (Ticket ticket in trip.Tickets)
                {
                    // loop through every ticket in the trip
                    // if the ticket isn't canceled
                    // and the scheduled flight associated with it is
                    // the one we are looking to display the manifest for
                    if (!ticket.IsCanceled && ticket.Flight.ScheduledFlightId == sf.ScheduledFlightId)
                    {
                        // if they match, then add them to the passengers display
                        PassengersText.Text += $"\n{customer.Name}";
                    }
                }
            }
        }
Example #2
0
        public EditAccountInfoValidator(bool isRegistering)
        {
            IsRegistering = isRegistering;

            // Initialize the feedback to an empty string.
            _feedback = "";

            // If the user is not registering, we need to fill
            // all the fields with the current customer data.
            if (!IsRegistering)
            {
                // Fetch the user session service.
                var userService = App.Current.Services.GetService <UserSessionService>();

                using (var db = new AirContext()) // Create a new database context
                {
                    // We fetch the customer data by the customer data ID saved in our session.
                    var customerData = db.CustomerDatas.Find(userService.CustomerDataId);

                    // We now set all fields in our validator
                    // to the customer data from the database.
                    FullName         = customerData.Name;
                    Age              = customerData.Age;
                    PhoneNumber      = customerData.PhoneNumber;
                    Address          = customerData.Address;
                    City             = customerData.City;
                    State            = customerData.State;
                    ZipCode          = customerData.ZipCode;
                    CreditCardNumber = customerData.CreditCardNumber;
                }
            }
        }
        private static List <ScheduledFlight> GenerateFlights()
        {
            // generate a list of all the scheduled flights that have departed
            using var db = new AirContext();
            List <ScheduledFlight> ScheduledFlights = db.ScheduledFlights.Include(flight => flight.Flight)
                                                      .ThenInclude(fl => fl.Origin)
                                                      .Include(flight => flight.Flight)
                                                      .ThenInclude(fl => fl.Destination)
                                                      .Include(flight => flight.Flight)
                                                      .ThenInclude(fl => fl.PlaneType)
                                                      .ToList();
            List <ScheduledFlight> toRemove = new();

            // remove any flight where the departure time is after now
            foreach (ScheduledFlight sf in ScheduledFlights)
            {
                if (sf.DepartureTime > DateTime.Now)
                {
                    toRemove.Add(sf);
                }
            }

            foreach (ScheduledFlight sf in toRemove)
            {
                ScheduledFlights.Remove(sf);
            }

            // then return the updated list
            return(ScheduledFlights);
        }
Example #4
0
        // When this page is navigated to, we need to check
        // set our pageParams to the navigation parameteres.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            pageParams = e.Parameter as Params;

            // We need to search for flights with the
            // view model so we can show the results
            // to the user.
            Task.Run(async() =>
            {
                using var db = new AirContext();

                // We first fetch the departure and destination
                // airport based on the IDs passed into the page.
                var departureAirport   = await db.Airports.FindAsync(pageParams.DepartureAirportId);
                var destinationAirport = await db.Airports.FindAsync(pageParams.DestinationAirportId);

                // If a departure flight path has already been chosen,
                // we search for return flights on the return date.
                // Otherwise, we search for departure flights on the
                // departure date.
                if (pageParams.DepartureFlightPath != null)
                {
                    await ViewModel.SearchForFlights(departureAirport, destinationAirport, (DateTime)pageParams.ReturnDate);
                }
                else
                {
                    await ViewModel.SearchForFlights(departureAirport, destinationAirport, pageParams.DepartureDate);
                }
            }).Wait();
        }
Example #5
0
        public static void HandlePurchase(FlightPath leavingPath, FlightPath?returningPath, DateTime leavingDate, DateTime?returningDate, PaymentType paymentType, bool oneWay)
        {
            List <Ticket> tickets = new();

            // make tickets for the appropriate flight paths
            if (oneWay)
            {
                tickets = CreateListOfTickets(leavingPath, paymentType, leavingDate);
            }
            else
            {
                if (returningDate != null)
                {
                    var nonNullable = (DateTime)returningDate;
                    tickets = CreateListOfTickets(leavingPath, paymentType, leavingDate);
                    tickets.AddRange(CreateListOfTickets(returningPath, paymentType, nonNullable));
                }
            }

            // determine the total cost by whether or not the trip is one way
            int totalCost = oneWay ? leavingPath.IntPrice : leavingPath.IntPrice + returningPath.IntPrice;



            // add the trip to the db table, and to the customer in the db
            using (var db = new AirContext())
            {
                var custInfo = db.Users.Include(user => user.CustInfo).Single(dbuser => dbuser.UserId == UserSession.userId).CustInfo;
                // make a new trip with the appropriate info
                Trip trip = new()
                {
                    OriginAirportId      = leavingPath.flights[0].Origin.AirportId,
                    DestinationAirportId = leavingPath.flights[^ 1].Destination.AirportId,
Example #6
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
        {
            // when the app is launched, migrate the database (which includes making it)
            using (var db = new AirContext())
            {
                db.Database.Migrate();
            }
            m_window = new MainWindow();

            // fill the main window's content with a frame
            Frame frame = m_window.Content as Frame;

            if (frame == null)
            {
                frame            = new Frame();
                m_window.Content = frame;
            }

            // and navigate to the main page
            if (frame.Content == null)
            {
                frame.Navigate(typeof(MainPage));
            }

            m_window.Activate();
        }
        // send the user back to their appropriate page
        private void UserInfoControl_OnNavigateParentReady(object source, EventArgs e)
        {
            var db   = new AirContext();
            var user = db.Users.Include(dbuser => dbuser.CustInfo).Single(dbuser => dbuser.UserId == UserSession.userId);

            if (user.UserRole == Role.CUSTOMER)
            {
                Frame.Navigate(typeof(MainPage));
            }
            else if (user.UserRole == Role.LOAD_ENGINEER)
            {
                Frame.Navigate(typeof(LoadEngineerPage));
            }
            else if (user.UserRole == Role.MARKETING_MANAGER)
            {
                Frame.Navigate(typeof(MarketingManagerPage));
            }
            else if (user.UserRole == Role.ACCOUNTING_MANAGER)
            {
                Frame.Navigate(typeof(AccountingManagerPage));
            }
            else
            {
                Frame.Navigate(typeof(FlightManagerPage));
            }
        }
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateSearchParameters())
            {
                // Bring up list of flights for Origin Airport
                using var db = new AirContext();
                // valid search params, so actually search
                string originCode    = StripAirportCode(originPicker.Text);
                var    originAirport = db.Airports.Single(airport => airport.AirportCode == originCode);


                var depDate = departurePicker.Date.Value.Date; // this gets only the date portion of the departure pickers chosen date
                LEManageFlightsPage.LEParameters passIn;

                passIn = new LEManageFlightsPage.LEParameters(originAirport, depDate);

                // send them to the manage flights page
                Frame.Navigate(typeof(LEManageFlightsPage), passIn);
            }
            else
            {
                OutputInfoTop.Title    = "Invalid Input!";
                OutputInfoTop.Severity = InfoBarSeverity.Error;
                OutputInfoTop.IsOpen   = true;
            }
        }
Example #9
0
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateSearchParameters())
            {
                using var db = new AirContext();
                // valid search params, so actually search
                // grab the airports
                string originCode    = StripAirportCode(originPicker.Text);
                var    originAirport = db.Airports.Single(airport => airport.AirportCode == originCode);
                string destCode      = StripAirportCode(destPicker.Text);
                var    destAirport   = db.Airports.Single(airport => airport.AirportCode == destCode);

                var depDate = departurePicker.Date.Value.Date; // this gets only the date portion of the departure pickers chosen date
                FlightDisplayPage.Parameters passIn;
                // navigate to the flight display page with the appropriate parameters
                if (returnPicker.Date != null)
                {
                    passIn = new FlightDisplayPage.Parameters(originAirport, destAirport, depDate, returnPicker.Date.Value.Date);
                }
                else
                {
                    passIn = new FlightDisplayPage.Parameters(originAirport, destAirport, depDate);
                }

                Frame.Navigate(typeof(FlightDisplayPage), passIn);
            }
            else
            {
                // otherwise display an error because they messed up in search params
                OutputInfo.Title    = "Invalid Input!";
                OutputInfo.Severity = InfoBarSeverity.Error;
                OutputInfo.IsOpen   = true;
            }
        }
Example #10
0
        // This method finds all flight paths with zero, one, or two connections,
        // completely ignoring any date or timing of the scheduled flights - it
        // purely looks at the recurring flight and not scheduled flight.
        public static async Task <List <FlightPath> > FindFlightPaths(int DepartureAirportId, int ArrivalAirportId)
        {
            // This method finds all flight paths with zero, one, or two connections.
            // This method will always return flight paths with the least possible amount
            // of connections, because it terminates after at least a single flight path has
            // zero, one, or two connections.
            //
            // This method does not guarantee any order, and will not return the best path
            // a customer could take, but instead all possible paths within the least connections
            // possible, so it is up to the caller to sort the routes however they want,
            // potentially based on price and/or duration.
            using var db = new AirContext();

            // This query grabs all direct flights that have not been canceled going from
            // the departure airport to the arrival airport.
            var directFlights = await db.Flights
                                .Include(flight => flight.OriginAirport)
                                .Include(flight => flight.DestinationAirport)
                                .Where(flight => !flight.IsCanceled && flight.OriginAirportId == DepartureAirportId && flight.DestinationAirportId == ArrivalAirportId).ToListAsync();

            // If at least one direct flight exists, just return flight paths for
            // the direct flights immediately.
            if (directFlights.Count != 0)
            {
                return(directFlights.Select(flight => new FlightPath(flight)).ToList());
            }

            // Setup a query to return all non-canceled flights in the DB, including their origin and destination airport.
            var flights = db.Flights.Include(flight => flight.OriginAirport).Include(flight => flight.DestinationAirport).Where(flight => !flight.IsCanceled);

            // Let's now take a look for flight paths with one connecting flight.
            var query = from flight in flights                                    // For each flight in the flight query,
                        where flight.OriginAirportId == DepartureAirportId        // where the origin airport matches the departure airport,
                                                                                  // and joining each connection in the flights query where the connection's detination equals the connection's origin,
                        join connection in flights on flight.DestinationAirportId equals connection.OriginAirportId
                        where connection.DestinationAirportId == ArrivalAirportId // and the connection's destination equals the arrival airport,
                        select new FlightPath(flight, connection);                // construct a flight path made up of the original flight and the connection.

            var possiblePaths = await query.ToListAsync();                        // Turn the results into a list,

            if (possiblePaths.Count != 0)
            {
                return(possiblePaths); // and return them if we found any results.
            }

            // Since we couldn't find any direct flights or two legged flights,
            // now we look for three legged flights.
            var doubleConnectedQuery = from flight in flights                                            // FOr each flight in the flight query,
                                       where flight.OriginAirportId == DepartureAirportId                // where the origin airport matches the departure airport,
                                                                                                         // and joining each connection where the origin airport of the connection matches the flight's destination airport,
                                       join firstConnection in flights on flight.DestinationAirportId equals firstConnection.OriginAirportId
                                                                                                         // and the first connection's destination airport equals the second connection's origin airport,
                                       join secondConnection in flights on firstConnection.DestinationAirportId equals secondConnection.OriginAirportId
                                                                                                         // and finally making sure the second connection's destination equals where we want to arrive,
                                       where secondConnection.DestinationAirportId == ArrivalAirportId
                                       select new FlightPath(flight, firstConnection, secondConnection); // construct a flight path made up of the original flight and two connections.

            return(await doubleConnectedQuery.ToListAsync());                                            //  and return them as a list.
        }
Example #11
0
 public DbInitializer(UserManager <IdentityUser> userManager,
                      RoleManager <IdentityRole> roleManager, ApplicationDbContext applicationDbContext, AirContext airContext)
 {
     this.userManager          = userManager;
     this.roleManager          = roleManager;
     this.applicationDbContext = applicationDbContext;
     this.airContext           = airContext;
 }
Example #12
0
        override protected void OnNavigatedTo(NavigationEventArgs e)
        {
            if (isCustomer)
            {
                // if we have a customer we need to load a bunch of info
                var db   = new AirContext();
                var user = db.Users.Include(dbuser => dbuser.CustInfo)
                           .ThenInclude(custInfo => custInfo.Trips)
                           .ThenInclude(trip => trip.Origin)
                           .Include(user => user.CustInfo)
                           .ThenInclude(custInfo => custInfo.Trips)
                           .ThenInclude(trip => trip.Destination)
                           .Include(user => user.CustInfo)
                           .ThenInclude(custInfo => custInfo.Trips)
                           .ThenInclude(trip => trip.Tickets)
                           .ThenInclude(ticket => ticket.Flight)
                           .ThenInclude(scheduledFlight => scheduledFlight.Flight)
                           .ThenInclude(flight => flight.Origin)
                           .Include(user => user.CustInfo)
                           .ThenInclude(custInfo => custInfo.Trips)
                           .ThenInclude(trip => trip.Tickets)
                           .ThenInclude(ticket => ticket.Flight)
                           .ThenInclude(scheduledFlight => scheduledFlight.Flight)
                           .ThenInclude(flight => flight.Destination)
                           .Single(dbuser => dbuser.UserId == UserSession.userId);
                CustomerInfo customerInfo = user.CustInfo;
                // award points for any trips that have departed & were not yet claimed
                int newPoints = 0;
                // loop through all of their trips
                foreach (Trip trip in customerInfo.Trips)
                {
                    // check if the trip has departed
                    if (trip.GetFormattedDeparted() == "Trip has departed!")
                    {
                        // make sure they haven't claimed the points already
                        if (!trip.PointsClaimed)
                        {
                            // Award the appropriate points to the user
                            UserUtilities.AwardPoints(user, (trip.TotalCost / 100) * 10);
                            newPoints          = trip.TotalCost / 100; // keep track of this for the ui
                            trip.PointsClaimed = true;                 // set the points claimed to true
                            var dbtrip = db.Trips.Single(dbtripinterior => dbtripinterior.TripId == trip.TripId);
                            dbtrip.PointsClaimed = true;               // and update the db as well
                            db.SaveChanges();
                        }
                    }
                }

                // Display basic info about the user
                WelcomeText.Text       = $"Welcome back {customerInfo.Name}!";
                PointsText.Text        = $"You currently have {customerInfo.PointsAvailable + newPoints} points available, and overall you have used {customerInfo.PointsUsed} points.";
                CreditText.Text        = $"You currently have a credit balance of ${customerInfo.CreditBalance / 100} with us.";
                TicketSummaryText.Text = $"You have booked {customerInfo.Trips.ToArray().Length} trips with us.";

                // and fill our list view with the customers trips
                TripList.ItemsSource = customerInfo.Trips;
            }
        }
Example #13
0
        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            //get user input
            string userIdInput       = userID.Text.ToString();
            string userPasswordInput = passwordBox.Password.ToString();
            // hash the password
            string hashed = PasswordHandler.HashPassword(userPasswordInput);
            // and check if its correct
            bool accountCorrect = PasswordHandler.CompareHashedToStored(userIdInput, hashed);

            if (!accountCorrect)
            {
                // For security reasons, we always display the same message
                // so that users cannot brute force to determine login ids
                outputInfo.Title    = "Bad Login";
                outputInfo.Message  = "The UserID or Password you entered is incorrect!";
                outputInfo.Severity = InfoBarSeverity.Error;
                outputInfo.IsOpen   = true;
            }
            else
            {
                using (var db = new AirContext())
                {
                    // grab the user and update the session
                    var user = db.Users.Include(user => user.CustInfo)
                               .Where(dbuser => dbuser.LoginId == userIdInput).FirstOrDefault();
                    UserSession.userId       = user.UserId;
                    UserSession.userLoggedIn = true;

                    // then send them to the appropriate page
                    if (user.UserRole == Role.MARKETING_MANAGER)
                    {
                        Frame.Navigate(typeof(MarketingManagerPage));
                    }
                    else if (user.UserRole == Role.LOAD_ENGINEER)
                    {
                        Frame.Navigate(typeof(LoadEngineerPage));
                    }
                    else if (user.UserRole == Role.FLIGHT_MANAGER)
                    {
                        Frame.Navigate(typeof(FlightManagerPage));
                    }
                    else if (user.UserRole == Role.ACCOUNTING_MANAGER)
                    {
                        Frame.Navigate(typeof(AccountingManagerPage));
                    }
                    else
                    {
                        Frame.Navigate(typeof(MainPage), null, new SlideNavigationTransitionInfo()
                        {
                            Effect = SlideNavigationTransitionEffect.FromRight
                        });
                    }
                }
            }
        }
Example #14
0
        public ChangePasswordViewModel()
        {
            using (var db = new AirContext())
            {
                // TODO: Make async?
                var user = db.Users.Single(user => user.UserId == userSessionService.UserId);

                currentPasswordHash = user.PasswordHash;
            }
        }
Example #15
0
        // subtracts the specified amount of credit from the specified user
        public static void UseCredit(User user, int amount)
        {
            using var db = new AirContext();
            var customerInfo = db.Users.Include(user => user.CustInfo).Where(dbuser => dbuser.UserId == user.UserId).FirstOrDefault().CustInfo;

            if (customerInfo != null)
            {
                customerInfo.CreditBalance -= amount;
            }
            db.SaveChanges();
        }
Example #16
0
        // adds the specified amount of points to the specified user
        public static void AwardPoints(User user, int amount)
        {
            using var db = new AirContext();
            var customerInfo = db.Users.Include(user => user.CustInfo).Where(dbuser => dbuser.UserId == user.UserId).FirstOrDefault().CustInfo;

            if (customerInfo != null)
            {
                customerInfo.PointsAvailable += amount;
            }
            db.SaveChanges();
        }
        public UserInfoControl()
        {
            this.InitializeComponent();

            // After the component is loaded, we need to do a few things
            this.Loaded += (sender, e) =>
            {
                // Change some text depending on whether or not its a register box
                if (IsRegister)
                {
                    TitleText.Text        = "Register";
                    confirmButton.Content = "Create Account";
                }
                else
                {
                    TitleText.Text        = "Update Account Info";
                    confirmButton.Content = "Update Information";
                    // If theres a user logged in, we need to adjust some things
                    if (UserSession.userLoggedIn)
                    {
                        var db   = new AirContext();
                        var user = db.Users.Include(dbuser => dbuser.CustInfo).Single(dbuser => dbuser.UserId == UserSession.userId);
                        // grab the user thats logged in from the db ^
                        if (user.UserRole != Role.CUSTOMER)
                        {
                            // only show password fields if they aren't a customer
                            NameInput.Visibility       = Visibility.Collapsed;
                            AddressInput.Visibility    = Visibility.Collapsed;
                            CityInput.Visibility       = Visibility.Collapsed;
                            StateInput.Visibility      = Visibility.Collapsed;
                            ZipInput.Visibility        = Visibility.Collapsed;
                            PhoneInput.Visibility      = Visibility.Collapsed;
                            AgeInput.Visibility        = Visibility.Collapsed;
                            CreditCardInput.Visibility = Visibility.Collapsed;
                            return;
                        }

                        // if they are a customer & logged in, fill out their info
                        // so they can update it easily
                        CustomerInfo customerInfo = user.CustInfo;
                        NameInput.Text                       = customerInfo.Name;
                        AddressInput.Text                    = customerInfo.Address;
                        CityInput.Text                       = customerInfo.City;
                        StateInput.Text                      = customerInfo.State;
                        ZipInput.Text                        = customerInfo.Zip;
                        PhoneInput.Text                      = customerInfo.PhoneNumber;
                        AgeInput.Text                        = customerInfo.Age.ToString();
                        CreditCardInput.Text                 = customerInfo.CreditCardNumber;
                        PasswordInput.PlaceholderText        = "Update Password";
                        ConfirmPasswordInput.PlaceholderText = "Confirm Updated Password";
                    }
                }
            };
        }
Example #18
0
        public BoardingPass()
        {
            this.InitializeComponent();
            // grab the user for the current session to display boarding passes for
            var db   = new AirContext();
            var user = db.Users.Include(dbuser => dbuser.CustInfo)
                       .ThenInclude(custInfo => custInfo.Trips)
                       .Single(dbuser => dbuser.UserId == UserSession.userId);

            BPuser = user;
        }
Example #19
0
 // checks if a specified login id exists in the db
 public static bool LoginIDExists(string loginId)
 {
     using (var db = new AirContext())
     {
         var user = db.Users.SingleOrDefault(dbuser => dbuser.LoginId == loginId);
         if (user != null)
         {
             return(true);
         }
     }
     return(false);
 }
Example #20
0
        public static List <Ticket> CreateListOfTickets(FlightPath path, PaymentType paymentType, DateTime date)
        {
            var scheduledFlights = new List <ScheduledFlight>();

            using var db = new AirContext();
            foreach (Flight flight in path.flights)
            {
                // see if a scheduled flight exists for this flight on this day already
                var sf = db.ScheduledFlights.Include(sf => sf.Flight).ThenInclude(fl => fl.PlaneType).Where(sf => sf.Flight.FlightId == flight.FlightId).SingleOrDefault(sf => sf.DepartureTime.Date == date);
                if (sf != null)
                {
                    // If a flight exists already, simply add it to our list of scheduled flights
                    scheduledFlights.Add(sf);
                }
                else
                {
                    // Otherwise, we need to make a scheduled flight for it
                    var sfNew = new ScheduledFlight
                    {
                        FlightId         = flight.FlightId,
                        DepartureTime    = date.Add(flight.DepartureTime),
                        TicketsPurchased = 1
                    };
                    // add it to our list
                    scheduledFlights.Add(sfNew);
                    // and the db
                    db.ScheduledFlights.Add(sfNew);
                    db.SaveChanges();
                }
            }

            var tickets = new List <Ticket>();

            foreach (ScheduledFlight sf in scheduledFlights)
            {
                // Now we need to make a ticket for each scheduled flight
                var ticket = new Ticket
                {
                    Flight      = sf,
                    PaymentType = paymentType
                };
                // Increment the amount of tickets purchased
                sf.TicketsPurchased++;
                // add it to our list to return
                tickets.Add(ticket);
                // and add it to the db
                db.Tickets.Add(ticket);
                db.SaveChanges();
            }

            // return the tickets we made
            return(tickets);
        }
        private void HandleUpdateAccount()
        {
            // validate input
            if (ValidateInput())
            {
                User         currentUser = null;
                CustomerInfo custInfo    = null;
                if (UserSession.userLoggedIn)
                {
                    var db   = new AirContext();
                    var user = db.Users.Include(dbuser => dbuser.CustInfo).Single(dbuser => dbuser.UserId == UserSession.userId);
                    currentUser = user;
                    // if the current user is a customer, then update their information from the fields
                    if (user.UserRole == Role.CUSTOMER)
                    {
                        custInfo                  = currentUser.CustInfo;
                        custInfo.Name             = NameInput.Text;
                        custInfo.Address          = AddressInput.Text;
                        custInfo.City             = CityInput.Text;
                        custInfo.State            = StateInput.Text;
                        custInfo.Zip              = ZipInput.Text;
                        custInfo.PhoneNumber      = PhoneInput.Text;
                        custInfo.Age              = (int)AgeInput.Value;
                        custInfo.CreditCardNumber = CreditCardInput.Text;
                    }
                }

                // if they are updating their password then we need to update their hashed password
                if (!string.IsNullOrWhiteSpace(PasswordInput.Password) && !string.IsNullOrWhiteSpace(ConfirmPasswordInput.Password))
                {
                    currentUser.HashedPass = PasswordHandler.HashPassword(PasswordInput.Password);
                }

                using (var db = new AirContext())
                {
                    // save the updated customer info in the database
                    var dbuser = db.Users.Single(user => user.LoginId == currentUser.LoginId);
                    if (custInfo != null)
                    {
                        dbuser.CustInfo = custInfo;
                    }
                    dbuser.HashedPass = currentUser.HashedPass;
                    db.SaveChanges();
                }

                // display to the user that we updated their info successfull
                outputInfo.Title    = "Account Information Updated!";
                outputInfo.Message  = "Your Account Information was updated successfully!";
                outputInfo.Severity = InfoBarSeverity.Success;
                outputInfo.IsOpen   = true;
            }
        }
        private void EditDepartButton_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateEditParameters())
            {
                // Ready to change time.
                using var db = new AirContext();
                // grab object that was selected from list
                var editFlight = DepartList.SelectedItem as FlightPath;

                // check if the flight has already been scheduled
                var existingFlights = db.ScheduledFlights.Include(sf => sf.Flight)
                                      .Where(sf => sf.Flight.FlightId == editFlight.flights[0].FlightId)
                                      .ToList();
                // if the flight has been scheduled you can't edit it
                if (existingFlights.Count > 0)
                {
                    OutputInfo.Title    = "You cannot edit this flight!";
                    OutputInfo.Message  = "This flight has already been scheduled at least once so it cannot be edited!";
                    OutputInfo.Severity = InfoBarSeverity.Error;
                    OutputInfo.IsOpen   = true;
                    return;
                }

                // check that something was selected
                if (editFlight != null)
                {
                    // get time from time picker
                    TimeSpan selectedTime = (TimeSpan)timePickerAdd.SelectedTime;

                    // get plane from db to delete from list
                    db.Flights.Single(flight => flight.FlightId == editFlight.flights[0].FlightId).DepartureTime = selectedTime;
                    db.SaveChanges();

                    // refresh list
                    Frame.Navigate(typeof(LEManageFlightsPage), passedLEParams);
                }
                else
                {
                    OutputInfo.Title    = "Invalid Input!";
                    OutputInfo.Message  = "You must select a flight first.";
                    OutputInfo.Severity = InfoBarSeverity.Error;
                    OutputInfo.IsOpen   = true;
                }
            }
            else
            {
                OutputInfo.Title    = "Invalid Input!";
                OutputInfo.Severity = InfoBarSeverity.Error;
                OutputInfo.IsOpen   = true;
            }
        }
Example #23
0
        public AccountPage()
        {
            this.InitializeComponent();
            // after we initialize the page, determine whether we have a customer or staff account member
            var db   = new AirContext();
            var user = db.Users.Include(dbuser => dbuser.CustInfo)
                       .ThenInclude(custInfo => custInfo.Trips)
                       .Single(dbuser => dbuser.UserId == UserSession.userId);

            if (user.CustInfo != null)
            {
                isCustomer = true;
            }
        }
        private static List <FlightPath> GenerateFlights(Airport originAirport)
        {
            using var db = new AirContext();
            //query database for flights with correct origin and departure date
            var LEFlights = db.Flights
                            .Include(flight => flight.Origin)
                            .Include(flight => flight.Destination)
                            .Where(flight => !flight.IsCanceled &&
                                   flight.Origin == originAirport)
                            .OrderBy(flight => flight.Destination)
                            .ToList();

            return(LEFlights.Select(flight => new FlightPath(flight)).ToList());
        }
        private static List <ScheduledFlight> GenerateFlights()
        {
            using var db = new AirContext();
            // grab all the scheduled flights that have taken off
            List <ScheduledFlight> SchedFlights = db.ScheduledFlights.Include(flight => flight.Flight)
                                                  .ThenInclude(fl => fl.Origin)
                                                  .Include(flight => flight.Flight)
                                                  .ThenInclude(fl => fl.Destination)
                                                  .Include(flight => flight.Flight)
                                                  .ThenInclude(fl => fl.PlaneType)
                                                  .Where(flight => flight.DepartureTime.CompareTo(DateTime.Now) < 0)
                                                  .ToList();

            return(SchedFlights);
        }
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateAddParameters())
            {
                // get data from GUI and add flight
                using var db = new AirContext();

                string   originCode    = StripAirportCode(originPickerAdd.Text);
                string   destCode      = StripAirportCode(destPickerAdd.Text);
                var      originAirport = db.Airports.Single(Airport => Airport.AirportCode == originCode);
                var      destAirport   = db.Airports.Single(Airport => Airport.AirportCode == destCode);
                TimeSpan selectedTime  = (TimeSpan)timePickerAdd.SelectedTime;

                // Make sure that this isn't a new route
                if (EnsureExistingRoute(originAirport, destAirport))
                {
                    // Add new flight
                    // plane type defaults to 737
                    Flight flight = new()
                    {
                        Origin        = originAirport,
                        Destination   = destAirport,
                        PlaneType     = db.Planes.Single(plane => plane.PlaneId == 1),
                        DepartureTime = selectedTime
                    };
                    db.Flights.Add(flight);
                    db.SaveChanges();

                    OutputInfo.Title    = "Success!";
                    OutputInfo.Message  = $"Flight was successfully added!";
                    OutputInfo.Severity = InfoBarSeverity.Success;
                    OutputInfo.IsOpen   = true;
                }
                else
                {
                    OutputInfo.Title    = "Route Doesn't Exist!";
                    OutputInfo.Message  = $"Talk to your manager if you really think we should add a brand new route.";
                    OutputInfo.Severity = InfoBarSeverity.Error;
                    OutputInfo.IsOpen   = true;
                }
            }
            else
            {
                OutputInfo.Title    = "Invalid Input!";
                OutputInfo.Severity = InfoBarSeverity.Error;
                OutputInfo.IsOpen   = true;
            }
        }
Example #27
0
        private void CancelTrip_Click(object sender, RoutedEventArgs e)
        {
            if (cancelTrip.Flyout is Flyout f)
            {
                f.Hide();
            }

            // Can only see this button if a trip is selected, so don't need
            // to check
            var db           = new AirContext();
            var user         = db.Users.Include(dbuser => dbuser.CustInfo).Single(dbuser => dbuser.UserId == UserSession.userId);
            var SelectedTrip = TripList.SelectedItem as Trip;
            // If a flight has taken off already or will do so in less than an hour
            // we need to stop the cancellation
            DateTime inOneHour = DateTime.Now.AddHours(1);
            bool     takenOff  = false;

            foreach (Ticket ticket in SelectedTrip.Tickets)
            {
                var      sf            = ticket.Flight;
                DateTime departureTime = sf.DepartureTime;
                if (departureTime < inOneHour)
                {
                    // This flight has already taken off or will in the next hour
                    takenOff = true;
                }
            }

            if (takenOff || SelectedTrip.IsCanceled)
            {
                // Not allowed to cancel, so display an error
                OutputInfo.Title    = "No cancellation possible";
                OutputInfo.Message  = "One or more of your flights has already taken off, or will in less than an hour, so you cannot cancel this trip";
                OutputInfo.Severity = InfoBarSeverity.Error;
                OutputInfo.IsOpen   = true;
                // and return
                return;
            }

            // cancel the trip
            TicketUtilities.CancelTrip(SelectedTrip, user);
            // and display a message saying we did to the user
            OutputInfo.Title    = "Flight Cancelled!";
            OutputInfo.Message  = "Your trip was successfully cancelled!";
            OutputInfo.Severity = InfoBarSeverity.Success;
            OutputInfo.IsOpen   = true;
        }
Example #28
0
        public static bool CompareHashedToStored(string loginID, string hashedPassword)
        {
            using (var db = new AirContext())
            {
                // grab the user with this loginid
                var user = db.Users.Where(user => user.LoginId == loginID).FirstOrDefault();
                if (user == null)
                {
                    // if there isn't a user return false
                    // because we don't have anything to compare
                    return(false);
                }

                // return whether or not the hashed password matches the password in the db
                return(user.HashedPass == hashedPassword);
            }
        }
Example #29
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            // Right before we show the main window,
            // we migrate the database. This will ensure
            // that if the database is not created, it will
            // be created. Afterwards, all migrations will
            // be ran so the schema is up to date.
            using (var db = new AirContext())
            {
                db.Database.Migrate();
            }

            // We then construct our main window
            // and activate it which shows it to
            // the user.
            m_window = new MainWindow();
            m_window.Activate();
        }
        private static bool EnsureExistingRoute(Airport originAirport, Airport destinationAirport)
        {
            using var db = new AirContext();
            // This query grabs all direct flights, comments follow inline
            var direct = db.Flights                             // on the entire flights table of the db
                         .Include(flight => flight.Origin)      // ensure that we have access to the origin airports info later
                         .Include(flight => flight.Destination) // ensure that we have access to the destination airports info later
                         .Where(flight => !flight.IsCanceled && // only take flights that are not canceled (by staff member)
                                flight.Origin == originAirport && // the origin of the flight should match the origin airport passed in
                                flight.Destination == destinationAirport) // and the destination airports should match
                         .ToList();                                       // then turn it into a list

            // If there are flights at this point, they are existing routes.
            // This makes them safe to add new flights.
            if (direct.Count > 0)
            {
                return(true);
            }
            return(false);
        }