// перегрузка оператора +
        public static AirDirection operator +(AirDirection ad, float fp)
        {
            AirDirection adNew = new AirDirection();

            adNew.Price = ad.Price + fp;
            return(adNew);
        }
Exemple #2
0
        // регистрация пассажира
        internal void InsertToPassengers()
        {
            string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LocalDBAirPortApp.mdf;Integrated Security=True";

            Console.WriteLine();

            // выбор направления
            Console.WriteLine("> СПИСОК ДЕЙСТВУЮЩИХ НАПРАВЛЕНИЙ");
            AirDirection ad = new AirDirection();

            ad.ShowAllDiretions();

            Console.WriteLine("> Введите номер рейса:");
            int idDir = Convert.ToInt32(Console.ReadLine()); // здесь отловить исключение

            Console.Clear();

            Console.WriteLine(">> Регистрируем нового пассажира на рейс:");

            Console.WriteLine("> Введите дату рейса [ГГГГ.ММ.ДД]");

            DateTime dateTrip = DateTime.ParseExact(Console.ReadLine(), "yyyy.MM.dd", CultureInfo.InvariantCulture);

            Console.WriteLine("====== {0}", dateTrip);

            Console.WriteLine("> Введите [ИМЯ]:");
            FirstName = Console.ReadLine().ToUpper();

            Console.WriteLine("> Введите [ФАМИЛИЮ]:");
            LastName = Console.ReadLine().ToUpper();

            Console.WriteLine("> Введите [НОМЕР ПАСПОРТА]:");
            IdNumber = Console.ReadLine().ToUpper();

            Console.WriteLine("> Введите [ВОЗРАСТ]:");
            Age = Console.ReadLine();

            Console.WriteLine("> Введите [ПОЛ]:");
            Gender = Console.ReadLine().ToUpper();

            // запрос, существует ли такой пассажир в базе регистрировавшихся пассажиров
            bool   flagInsert = false;
            string sqlExp     = @"SELECT * FROM TablePassengers 
            WHERE 
            FirstName=@FirstName 
            and LastName = @LastName
            and IdNumber = @IdNumber
            and Age = @Age
            and Gender = @Gender";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sqlExp, connection);
                command.Parameters.AddWithValue("@FirstName", FirstName);
                command.Parameters.AddWithValue("@LastName", LastName);
                command.Parameters.AddWithValue("@IdNumber", IdNumber);
                command.Parameters.AddWithValue("@Age", Age);
                command.Parameters.AddWithValue("@Gender", Gender);

                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows) // если есть данные
                {
                    Console.WriteLine("> Такой ПАССАЖИР уже добавлен в БД регистрации!");
                }
                else
                {
                    flagInsert = true; // если пассажир первый раз регистрируется
                }
                reader.Close();
            }

            // если пассажир регистрируется первый раз, то добавляю его данные в таблицу Пассажиры
            if (flagInsert)
            {
                string sqlExpression = "INSERT INTO TablePassengers VALUES (@FirstName, @LastName, @IdNumber, @Age, @Gender)";

                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand(sqlExpression, connection);
                    command.Parameters.AddWithValue("@FirstName", FirstName);
                    command.Parameters.AddWithValue("@LastName", LastName);
                    command.Parameters.AddWithValue("@IdNumber", IdNumber);
                    command.Parameters.AddWithValue("@Age", Age);
                    command.Parameters.AddWithValue("@Gender", Gender);

                    command.ExecuteNonQuery();
                }
                Console.WriteLine(">> Данные пассажира внесены в БД!");
                Console.WriteLine();
            }

            // получаем массив данных на рейс (цена, класс, направление)
            ArrayList dpc = new ArrayList();

            dpc.AddRange(ad.SelectDPC(idDir));
            //Console.WriteLine("====> {0} {1} {2}", dpc[1], dpc[2], dpc[3]);


            // проверка новый или постоянный пассажир для расчета скидки
            bool   flagPas = SelectPass(FirstName, LastName, IdNumber);
            double discount;
            double priceDisc;

            // true = постоянный, false = первый раз
            if (flagPas)
            {
                discount  = 0.1; // скидка 10%
                priceDisc = Math.Round((Convert.ToDouble(dpc[2]) - (Convert.ToDouble(dpc[2]) * discount)), 2);
            }
            else
            {
                priceDisc = Convert.ToDouble(dpc[2]) - 2; // фиксированная скидка -2у.е.
                if (priceDisc <= 0)
                {
                    Console.WriteLine("> Внимание! Цена с учетом скидки не может быть меньше 0! Цена билета принята без скидки!");
                    priceDisc += 2;
                    discount   = 0;
                }
                else
                {
                    discount = Math.Round(2 / Convert.ToDouble(dpc[2]), 2);
                }
            }

            //Console.WriteLine("====//////////////////////////====");
            // оформление билета


            string sqlExpression2 = @"INSERT INTO TableTickets 
               VALUES (@Direction, @Name, @LName, @IdNumber, @PriceDirection,
               @Discount, @PriceWithDiscount, @RegDate, @Class)";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sqlExpression2, connection);
                command.Parameters.AddWithValue("@Direction", dpc[1]);
                command.Parameters.AddWithValue("@Name", FirstName);
                command.Parameters.AddWithValue("@LName", LastName);
                command.Parameters.AddWithValue("@IdNumber", IdNumber);
                command.Parameters.AddWithValue("@PriceDirection", dpc[2]);
                command.Parameters.AddWithValue("@Discount", discount);
                command.Parameters.AddWithValue("@PriceWithDiscount", priceDisc);
                command.Parameters.AddWithValue("@RegDate", dateTrip);
                command.Parameters.AddWithValue("@Class", dpc[3]);

                command.ExecuteNonQuery();
            }
            Console.WriteLine(">> Данные добавлены!");
            Console.WriteLine();

            // выбираю данные по билетам:
            string sqlExp2 = "SELECT * FROM TableTickets";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand    command = new SqlCommand(sqlExp2, connection);
                SqlDataReader reader  = command.ExecuteReader();

                if (reader.HasRows) // если есть данные
                {
                    // выводим названия столбцов
                    Console.WriteLine("{0, 5}{1, 20}{2, 10}{3, 10}{4, 10}{5, 10}{6, 10}{7, 10}{8, 13}{9, 13}", reader.GetName(0), reader.GetName(1), reader.GetName(2), reader.GetName(3), reader.GetName(4), "Price", reader.GetName(6), "Price-%", reader.GetName(8), reader.GetName(9));
                    Console.WriteLine("---------------------------------------------------------------------");

                    while (reader.Read()) // построчно считываем данные
                    {
                        //object id = reader.GetValue(1);
                        //object name = reader.GetValue(2);
                        //object age = reader.GetValue(3);
                        //Console.WriteLine("****************{0}", reader.GetValue(9).ToString().Length);
                        //Console.WriteLine("****************{0}", reader.GetDateTime(8).ToShortDateString());

                        Console.WriteLine("{0, 5}{1, 20}{2, 10}{3, 10}{4, 10}{5, 10}{6, 10}{7, 10}{8, 13}{9, 13}", reader.GetValue(0), reader.GetValue(1), reader.GetValue(2), reader.GetValue(3), reader.GetValue(4), reader.GetValue(5), reader.GetValue(6), reader.GetValue(7), reader.GetDateTime(8).ToShortDateString(), reader.GetValue(9));
                    }
                }
                reader.Close();
            }
        }
        // поиск перелета для изменения
        internal AirDirection FindToChangeDPC()
        {
            AirDirection adToReturn = new AirDirection();
            // повтор кода - вынести в отдельный метод
            // контроль длины полей направление не менее 3 символов
            bool   exLeng     = false;
            string DirectionА = null; // пустая строка
            string DirectionB = null;

            for (; exLeng == false;)
            {
                Console.WriteLine("> Введите [направление] Пункт А:");
                DirectionА = Console.ReadLine().ToUpper();
                if (DirectionА.Length >= 3)
                {
                    exLeng = true;
                }
                else
                {
                    Console.WriteLine("> Наименование [направление] должно содержать не меньше 3 символов. Повторите ввод!:");
                }
            }
            exLeng = false;
            for (; exLeng == false;)
            {
                Console.WriteLine("> Введите [направление] Пункт B:");
                DirectionB = Console.ReadLine().ToUpper();
                if (DirectionB.Length >= 3)
                {
                    exLeng = true;
                }
                else
                {
                    Console.WriteLine("> Наименование [направление] должно содержать не меньше 3 символов. Повторите ввод!:");
                }
            }


            Direction = DirectionА + " - " + DirectionB;

            Console.WriteLine("> Введите [класс] (А->B):");
            PlaceClass = Console.ReadLine().ToUpper();

            // выборка направления по направлению

            string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LocalDBAirPortApp.mdf;Integrated Security=True";

            string sqlExp = @"SELECT Id, AirDirection, Price, PlaceClass
            FROM TableDirection
            WHERE AirDirection = @Direction AND PlaceClass = @PlaceClass
            ";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sqlExp, connection);
                command.Parameters.AddWithValue("@Direction", Direction);
                command.Parameters.AddWithValue("@PlaceClass", PlaceClass);

                SqlDataReader reader = command.ExecuteReader();

                // если есть данные
                if (reader.HasRows)
                {
                    // построчно считываем данные
                    while (reader.Read())
                    {
                        adToReturn.Id         = reader.GetInt32(0);
                        adToReturn.Direction  = reader.GetString(1);
                        adToReturn.Price      = (float)reader.GetDouble(2);
                        adToReturn.PlaceClass = reader.GetString(3);
                    }
                    reader.Close();
                }
                else
                {
                    Console.WriteLine("> Указанное направление и класс не зарегистрированы в Системе!");
                    return(new AirDirection()); // возвращаю пустой объект
                }
                return(adToReturn);
            }
        }
Exemple #4
0
        static void SecondMenu()
        {
            Console.Clear();
            Console.WriteLine("============ Программа касса Аэропорта ============");
            Console.WriteLine("== Обзор и изменение направления авиаперелетов. ==");

            Console.WriteLine();

            Console.WriteLine("[Меню]");
            Console.WriteLine("[0] Вывести на экран все направления и тарифы");
            Console.WriteLine("[1] Ввод нового тарифа");
            Console.WriteLine("[2] Изменение цена тарифа");
            Console.WriteLine("[3] Возврат в Основное меню");
            Console.WriteLine("[4] ВЫХОД из системы");

            // выбор пункта меню
            string chois = Console.ReadLine();

            // ветвление
            switch (chois)
            {
            case "0":
                Console.Clear();
                AirDirection ad1 = new AirDirection();
                ad1.ShowAllDiretions();
                Console.WriteLine(">> Нажмите ENTER TO CONTINUE");
                Console.ReadLine();
                Console.Clear();
                SecondMenu();
                break;

            case "1":
                Console.Clear();
                AirDirection ad2 = new AirDirection();
                ad2.InsertToDirection();
                Console.WriteLine(">> Нажмите ENTER TO CONTINUE");
                Console.ReadLine();
                Console.Clear();
                SecondMenu();
                break;

            case "2":
                // изменение цены перелета
                Console.Clear();
                AirDirection ad3 = new AirDirection();
                ad3 = ad3.FindToChangeDPC(); // заполняю пустой объект данными из базы данных
                // если объект пустой то нельзя изменить запись возврат в меню
                //Thread.Sleep(2000);

                if (ad3.Direction == null)
                {
                    Console.WriteLine(">> Нажмите ENTER TO CONTINUE");
                    Console.ReadLine();
                    SecondMenu();
                    break;
                }
                else
                {
                    ad3.ChangePriceDirection();
                    //Thread.Sleep(2000);
                    Console.WriteLine(">> Нажмите ENTER TO CONTINUE");
                    Console.ReadLine();
                    SecondMenu();
                    break;
                }

            case "3":
                FirstMenu();
                break;

            case "4":
                Console.WriteLine(">> Работа с Системой завершена. Досвидания!");
                break;

            default:
                Console.WriteLine("Не верный выбор пункта меню.");
                break;
            }
        }