internal string PrintReviews(string[] args)
        {
            int busCompanyId = int.Parse(args[0]);

            using (var context = new BusTicketContext())
            {
                var company = context.Companies
                              .AsNoTracking()
                              .Include(c => c.Reviews)
                              .ThenInclude(r => r.Customer)
                              .SingleOrDefault(c => c.Id == busCompanyId);

                if (company == null)
                {
                    throw new CustomException($"No such company with id '{busCompanyId}'");
                }

                var result = new StringBuilder();

                company.Reviews
                .ToList()
                .ForEach(r =>
                         result.AppendLine($"{r.Id} {r.Grade} {r.PublishDate}{Environment.NewLine}" +
                                           $"{r.Customer.FullName}{Environment.NewLine}" +
                                           $"{r.Content}{Environment.NewLine}"));

                return(result.ToString());
            }
        }
        public static void GenerateBusStations(BusTicketContext context)
        {
            var names = new string[] {
                "North Station",
                "West Station",
                "South Station",
                "East Station",
                "NorthEast Station",
                "NorthWest Station",
                "Central Station"
            };

            var townIds = context.Towns.Select(p => p.Id).ToArray();

            var validBusStations = new List <BusStation>();

            var rnd = new Random();

            for (int i = 0; i < names.Length; i++)
            {
                var townsIndex = rnd.Next(0, townIds.Length - 1);

                var busStation = new BusStation
                {
                    Name   = names[i],
                    TownId = townIds[townsIndex]
                };

                validBusStations.Add(busStation);
            }

            context.AddRange(validBusStations);
            context.SaveChanges();
        }
Пример #3
0
        //protected override void Dispose(bool disposing)
        //{
        //    if (disposing)
        //    {
        //        db.Dispose();
        //    }
        //    base.Dispose(disposing);
        //}



        public ActionResult PrintTicketMethod(int?id)
        {
            using (BusTicketContext db = new BusTicketContext())
            {
                ReportDocument rd = new ReportDocument();
                rd.Load(Path.Combine(Server.MapPath("~/PrintTicket/"), "PassengerTicket.rpt"));

                var TicketData = (from t in db.tblTicketSells
                                  join b in db.tblBus on t.BusNo equals b.Id
                                  join bc in db.tblBusCategories on t.BusCategory equals bc.Id
                                  join c in db.tblCounters on t.UpCounter equals c.Id
                                  where t.Id == id
                                  select new { t.UpCounter, t.ticketPrice, t.DownCounter, t.Address, t.BusSchedule, t.Contact, t.PassengerName, t.SeatNo, b.BusNo, bc.BusCategory, c.CounterName }
                                  ).ToList();



                rd.SetDataSource(TicketData);

                Response.Buffer = false;
                Response.ClearContent();
                Response.ClearHeaders();


                Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                stream.Seek(0, SeekOrigin.Begin);
                return(File(stream, "application/pdf", "Ticket.pdf"));
            }
        }
Пример #4
0
        public static string Execute(string[] data)
        {
            string result = string.Empty;

            int busCompanyId = int.Parse(data[1]);

            using (var db = new BusTicketContext())
            {
                var reviews = db.Reviews
                              .Include(x => x.Customer)
                              .Where(x => x.BusCompanyId == busCompanyId)
                              .ToList();

                if (reviews.Count < 1)
                {
                    throw new InvalidOperationException($"No reviews for this Bus Company.");
                }

                StringBuilder sb = new StringBuilder();

                foreach (var rev in reviews)
                {
                    string custFullName = rev.Customer.FirstName + " " + rev.Customer.LastName;

                    string dateTime = rev.PublishDate.ToString(@"yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture);

                    sb.AppendLine($"{rev.ReviewId} {rev.Grade} {dateTime}");
                    sb.AppendLine($"{custFullName}");
                    sb.AppendLine($"{rev.Content}");
                }
                result = sb.ToString().Trim();
            }

            return(result);
        }
Пример #5
0
        public AdminController(
            BusTicketContext context,
            UserManager <User> userManager
            )
        {
            _userManager = userManager;

            _context = context;
        }
        public static string Execute(string[] data)
        {
            int    customerId     = int.Parse(data[1]);
            double grade          = double.Parse(data[2]);
            string busCompanyName = data[3];
            string content        = string.Join(" ", data.Skip(4).ToArray());

            string result = string.Empty;

            using (var db = new BusTicketContext())
            {
                var customer = db.Customers
                               .Include(x => x.Reviews)
                               .Where(x => x.CustomerId == customerId)
                               .FirstOrDefault();

                var busCompany = db.BusCompanies
                                 .Where(x => x.Name.ToLower() == busCompanyName.ToLower())
                                 .FirstOrDefault();

                if (customer == null)
                {
                    throw new InvalidOperationException("No such user!");
                }

                if (busCompany == null)
                {
                    throw new InvalidOperationException("No such company!");
                }

                if (grade < 1 || grade > 10)
                {
                    throw new InvalidOperationException("Grade must be between 1 and 10");
                }

                var review = new Review()
                {
                    BusCompanyId = busCompany.BusCompanyId,
                    Content      = content,
                    CustomerId   = customerId,
                    Grade        = grade
                };

                customer.Reviews.Add(review);
                db.SaveChanges();

                string fullName = customer.FirstName + " " + customer.LastName;

                StringBuilder sb = new StringBuilder();

                sb.AppendLine($"Customer {fullName} published review for company {busCompanyName}");

                result = sb.ToString().Trim();
            }

            return(result);
        }
        //buy-ticket {customer ID} {Trip ID} {Price} {Seat}
        public static string Execute(string[] data)
        {
            int     customerId = int.Parse(data[1]);
            int     tripId     = int.Parse(data[2]);
            decimal price      = decimal.Parse(data[3]);
            int     seat       = int.Parse(data[4]);

            using (var db = new BusTicketContext())
            {
                var customer = db.Customers.Find(customerId);

                if (customer == null)
                {
                    throw new ArgumentException("No customer with given Id!");
                }

                var trip = db.Trips.Find(tripId);
                if (trip == null)
                {
                    throw new ArgumentException("No trip with given Id!");
                }

                bool isSeatFull = db.Tickets.Any(t => t.TripId == tripId && t.Seat == seat);
                if (isSeatFull)
                {
                    throw new ArgumentException("The seat is already sold! Pick another seat.");
                }

                var customerBankAccount = db.CustomersBankAccounts
                                          .Include(c => c.BankAccount)
                                          .SingleOrDefault(c => c.CustomerId == customerId);

                if (customerBankAccount == null)
                {
                    throw new ArgumentException("The customer has not got a bank account. Cannot buy ticket!");
                }

                if (customerBankAccount.BankAccount.Balance < price)
                {
                    throw new ArgumentException("Insufficient funds!");
                }
                customerBankAccount.BankAccount.Balance -= price;

                var ticket = new Ticket
                {
                    Price    = price,
                    Seat     = seat,
                    TripId   = tripId,
                    Customer = customer
                };
                db.Tickets.Add(ticket);
                db.SaveChanges();

                return("Successfully bought ticket.");
            }
        }
        private static void InitializeDb()
        {
            using (var context = new BusTicketContext())
            {
                context.Database.EnsureDeleted();
                context.Database.Migrate();

                DbInitializer.Seed(context);
            }
        }
Пример #9
0
 private static void ResetDatabase(BusTicketContext context)
 {
     context.Database.EnsureDeleted();
     context.Database.Migrate();
     //context.Database.EnsureCreated();
     Seed(context);
     Console.WriteLine($"Migrations with custom Constraints applied!");
     Console.WriteLine("Seeded Successfully!");
     Console.WriteLine("Reset Database: Success!");
 }
Пример #10
0
        private static void ResetDatabase()
        {
            using (var db = new BusTicketContext())
            {
                db.Database.EnsureDeleted();
                db.Database.Migrate();

                Seed();
            }
        }
        public static string Execute(string[] data)
        {
            int     customerId = int.Parse(data[1]);
            int     tripId     = int.Parse(data[2]);
            decimal price      = decimal.Parse(data[3]);
            string  seat       = data[4];

            string result = string.Empty;

            using (var db = new BusTicketContext())
            {
                var customer = db.Customers
                               .Include(x => x.BankAccount)
                               .Where(x => x.CustomerId == customerId)
                               .FirstOrDefault();

                if (customer == null)
                {
                    throw new InvalidOperationException($"No such user!");
                }

                if (price <= 0)
                {
                    throw new InvalidCastException("Price cannot be negative or zero.");
                }

                customer.BankAccount.Withdraw(price);

                Ticket ticket = new Ticket()
                {
                    CustomerId = customer.CustomerId,
                    Price      = price,
                    Seat       = seat,
                    TripId     = tripId,
                };

                if (db.Tickets.Any(x => x.CustomerId == customerId && x.TripId == tripId))
                {
                    string ticketUser = customer.FirstName + " " + customer.LastName;
                    throw new InvalidOperationException($"Customer {ticketUser} has ticket for this trip already!");
                }
                customer.Tickets.Add(ticket);
                db.SaveChanges();
                string fullName = customer.FirstName + " " + customer.LastName;

                StringBuilder sb = new StringBuilder();

                sb.AppendLine($"Customer {fullName} bought ticket for trip {tripId} for ${price} on seat {seat}");
                result = sb.ToString().Trim();
            }

            return(result);
        }
        public static void GenerateCustomers(BusTicketContext context)
        {
            var firstNames = new string[] {
                "Dale",
                "Laura",
                "Dominic",
                "Gordon",
                "Diane",
                "Donna",
                "Audrey",
                "Ben",
                "Marty"
            };

            var lastNames = new string[]
            {
                "Cole",
                "Cooper",
                "Hart",
                "West",
                "Bell",
                "McNulty",
                "Horne",
                "Palmer"
            };

            var validCustomers = new List <Customer>();
            var rnd            = new Random();


            for (int i = 0; i < firstNames.Length; i++)
            {
                var lastNameIndex = rnd.Next(0, lastNames.Length - 1);

                var daysToSubtract = rnd.Next(1000, 10000);

                var customer = new Customer
                {
                    FirstName = firstNames[i],
                    LastName  = lastNames[lastNameIndex],
                    BirthDate = DateTime.Now.AddDays(daysToSubtract * -1),
                    Gender    = (Gender)(i % 3)
                };


                validCustomers.Add(customer);
            }

            context.AddRange(validCustomers);
            context.SaveChanges();
        }
        internal string ChangeTripStatus(string[] args)
        {
            int    tripId    = int.Parse(args[0]);
            string newStatus = args[1];

            using (var context = new BusTicketContext())
            {
                var trip = context.Trips
                           .Include(t => t.OriginBusStation)
                           .ThenInclude(obs => obs.Town)
                           .Include(t => t.DestinationBusStation)
                           .ThenInclude(dbs => dbs.Town)
                           .Include(t => t.Tickets)
                           .SingleOrDefault(t => t.Id == tripId);

                if (trip == null)
                {
                    throw new CustomException($"Trip with Id '{tripId}' does not exist!");
                }
                if (trip.Status == Status.Arrived)
                {
                    throw new CustomException("This trip has already arrived!");
                }

                string result = $"Trip from {trip.OriginBusStation.Town.Name} to {trip.DestinationBusStation.Town.Name} " +
                                $"on {trip.DepartureTime}{Environment.NewLine}" +
                                $"Status changed from {trip.Status} to {newStatus}";

                trip.Status = Enum.Parse <Status>(newStatus);


                if (trip.Status == Status.Arrived)
                {
                    var arrivedTrip = new ArrivedTrip
                    {
                        ArrivalTime             = trip.ArrivalTime,
                        PassengersCount         = trip.Tickets.Count(),
                        OriginBusStation        = trip.OriginBusStation,
                        OriginBusStationId      = trip.OriginBusStationId,
                        DestinationBusStation   = trip.DestinationBusStation,
                        DestinationBusStationId = trip.DestinationBusStationId
                    };
                    context.ArrivedTrips.Add(arrivedTrip);
                    context.SaveChanges();

                    result += $"{Environment.NewLine}On {DateTime.Now} - {arrivedTrip.PassengersCount} passengers arrived at " +
                              $"{arrivedTrip.DestinationBusStation.Town.Name} from {arrivedTrip.DestinationBusStation.Town.Name}";
                }
                return(result);
            }
        }
Пример #14
0
        //change-trip-status {Trip Id} {New Status}
        public static string Execute(string[] data)
        {
            int    tripId    = int.Parse(data[1]);
            string newStatus = data[2];
            string result    = "";

            using (var db = new BusTicketContext())
            {
                var trip = db.Trips
                           .Include(t => t.OriginBusStation)
                           .Include(t => t.DestinationBusStation)
                           .SingleOrDefault(t => t.TripId == tripId);

                if (trip == null)
                {
                    throw new ArgumentException("No such trip.");
                }

                bool isStatus = Enum.IsDefined(typeof(TripStatus), newStatus);
                if (!isStatus)
                {
                    throw new ArgumentException("Status must be departed,arrived,delayed or cancelled");
                }

                if (trip.Status.ToString() == newStatus)
                {
                    throw new ArgumentException("The current status of the trip is the given one.");
                }
                var oldStatus = trip.Status.ToString();
                trip.Status = Enum.Parse <TripStatus>(newStatus);
                result      = $"Trip from {trip.OriginBusStation.Name} to {trip.DestinationBusStation.Name} change {oldStatus} to {newStatus}";

                if (newStatus == TripStatus.arrived.ToString())
                {
                    var passangers  = db.Tickets.Where(t => t.TripId == tripId).Count();
                    var arrivalTrip = new ArrivedTrip
                    {
                        OriginBusStationName      = trip.OriginBusStation.Name,
                        DestinationBusStationName = trip.DestinationBusStation.Name,
                        PassengerCount            = passangers
                    };
                    db.ArrivalTrips.Add(arrivalTrip);
                    result = result + Environment.NewLine + $"On {DateTime.Now} - {passangers} passengers arrived  at {trip.DestinationBusStation.Name} from {trip.OriginBusStation.Name}";
                }
                db.SaveChanges();
                return(result);
            }
        }
 public UnitOfWork(BusTicketContext context)
 {
     _context          = context;
     Vendor            = new VendorRepository(_context);
     BusDetail         = new BusDetailRepository(_context);
     Route             = new RouteRepository(_context);
     BusCategory       = new BusCategoryRepository(_context);
     Brand             = new BrandRepository(_context);
     PaymentType       = new PaymentTypeRepository(_context);
     PromoOffer        = new PromoOfferRepository(_context);
     BusReservation    = new BusReservationRepository(_context);
     SeatLayout        = new SeatLayoutRepository(_context);
     TicketReservation = new TicketReservationRepository(_context);
     VendorPayment     = new VendorPaymentRepository(_context);
     Payment           = new PaymentRepository(_context);
 }
Пример #16
0
        //print information for trips for a given bus station –  Print a list of arrivals and departures buses for given bus station id
        //print-info <busStationId>
        public static string Execute(string[] data)
        {
            int busStationId = int.Parse(data[1]);

            using (var db = new BusTicketContext())
            {
                var busStation = db.BusStations
                                 .Include(b => b.Town)
                                 .Include(b => b.TripsArrivedAt)
                                 .ThenInclude(bs => bs.OriginBusStation)
                                 .ThenInclude(obs => obs.Town)
                                 .Include(b => b.TripsGoFrom)
                                 .ThenInclude(bs => bs.DestinationBusStation)
                                 .ThenInclude(dbs => dbs.Town)
                                 .SingleOrDefault(b => b.BusStationId == busStationId);

                if (busStation == null)
                {
                    throw new ArgumentException("No BusStation with the given Id!");
                }

                var sb = new StringBuilder();
                sb.AppendLine($"{busStation.Name}, {busStation.Town.Name}");
                if (busStation.TripsArrivedAt.Count != 0)
                {
                    sb.AppendLine("Arrivals: ");
                    foreach (var trip in busStation.TripsArrivedAt)
                    {
                        string arrivalTime = trip.ArrivalTime == null ? "[no information]" : trip.ArrivalTime.Value.ToShortTimeString();
                        sb.AppendLine($"From: {trip.OriginBusStation.Name} ({trip.OriginBusStation.Town.Name}) | Arrive at: {arrivalTime} | Status: {trip.Status}");
                    }
                }

                if (busStation.TripsGoFrom.Count != 0)
                {
                    sb.AppendLine("Departures:");
                    foreach (var trip in busStation.TripsGoFrom)
                    {
                        var departureTime = trip.DepartureTime.ToShortTimeString();
                        var destStation   = trip.DestinationBusStation.Name;
                        sb.AppendLine($"To: {trip.DestinationBusStation.Name} ({trip.DestinationBusStation.Town.Name}) | Depart at: {departureTime} | Status: {trip.Status}");
                    }
                }
                return(sb.ToString().Trim());
            }
        }
        private static void ResetDatabase()
        {
            using (var db = new BusTicketContext())
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                TownGenerator.GenerateTowns(db);
                BusCompanyGenerator.GenerateCompaines(db);
                BusStationGenerator.GenerateBusStations(db);
                CustomerGenerator.GenerateCustomers(db);
                TripGenerator.GenerateTrips(db);
                BankAccountGenerator.GenerateBankAccounts(db);
                ReviewGenerator.GenerateReview(db);
                TicketGenrator.GenerateTickets(db);
            }
        }
        internal string BuyTicket(string[] args)
        {
            int     customerId = int.Parse(args[0]);
            int     tripId     = int.Parse(args[1]);
            decimal price      = decimal.Parse(args[2]);
            int     seat       = int.Parse(string.Join("", args[3].Skip(1)));

            if (price < 0)
            {
                throw new CustomException("Invalid Price");
            }

            using (var context = new BusTicketContext())
            {
                var customer = context.Customers
                               .Include(c => c.BankAccount)
                               .SingleOrDefault(c => c.Id == customerId);

                if (customer.BankAccount.Balance < price)
                {
                    throw new CustomException($"Isufficient amount of money for customer " +
                                              $"{customer.FullName} with bank account number " +
                                              $"{customer.BankAccount.AccountNumber}");
                }

                var trip   = context.Trips.Find(tripId);
                var ticket = new Ticket
                {
                    Customer   = customer,
                    CustomerId = customer.Id,
                    Trip       = trip,
                    TripId     = trip.Id,
                    Price      = price,
                    Seat       = seat
                };

                context.Tickets.Add(ticket);
                customer.BankAccount.Balance -= price;
                customer.Tickets.ToList().Add(ticket);

                context.SaveChanges();

                return($"Customer {customer.FullName} bought ticket for trip {tripId} for {price:c} on seat {seat}");
            }
        }
Пример #19
0
        public static void GenerateReview(BusTicketContext context)
        {
            var content = new string[] {
                "good",
                "bad",
                "very good",
                "very bad",
                "Excellent",
                "Appaling",
                "Shockingly bad"
            };


            var validReviews = new List <Review>();

            var companyIds  = context.BusCompanies.Select(p => p.Id).ToArray();
            var customerIds = context.Customers.Select(p => p.Id).ToArray();

            var rnd = new Random();

            for (int i = 0; i < 5; i++)
            {
                var reviewIndex   = rnd.Next(0, content.Length - 1);
                var companyIndex  = rnd.Next(0, companyIds.Length - 1);
                var customerIndex = rnd.Next(0, customerIds.Length - 1);
                var grade         = rnd.Next(0, 10) / rnd.Next(1, 5);

                var review = new Review
                {
                    Content          = content[reviewIndex],
                    Grade            = grade,
                    CustomerId       = customerIds[customerIndex],
                    DateOfPublishing = DateTime.Now,
                    BusCompanyId     = companyIds[companyIndex]
                };

                validReviews.Add(review);
            }

            context.AddRange(validReviews);
            context.SaveChanges();
        }
Пример #20
0
        public static void GenerateTickets(BusTicketContext context)
        {
            var seats = new string[] {
                "A1",
                "A2",
                "A3",
                "A4",
                "A5",
                "B1",
                "B2",
                "B3",
                "B4",
                "B5"
            };

            var customerIds = context.Customers.Select(p => p.Id).ToArray();
            var tripIds     = context.Trips.Select(p => p.Id).ToArray();

            var rnd = new Random();

            var validTickets = new List <Ticket>();

            for (int i = 0; i < seats.Length; i++)
            {
                var     customerIndex = rnd.Next(0, customerIds.Length - 1);
                var     tripIndex     = rnd.Next(0, tripIds.Length - 1);
                decimal price         = rnd.Next(10, 20) / (decimal)rnd.Next(1, 5);

                var ticket = new Ticket
                {
                    Seat       = seats[i],
                    CustomerId = customerIds[customerIndex],
                    TripId     = tripIds[tripIndex],
                    Price      = price
                };

                validTickets.Add(ticket);
            }

            context.AddRange(validTickets);
            context.SaveChanges();
        }
Пример #21
0
        //print-reviews {Bus Company ID}
        public static string Execute(string[] data)
        {
            int busCompanyId = int.Parse(data[1]);

            using (var db = new BusTicketContext())
            {
                var busCompany = db.BusCompanies.Find(busCompanyId);
                if (busCompany == null)
                {
                    throw new ArgumentException("No Bus Company with given Id!");
                }

                var reviews = db.Reviews
                              .Where(b => b.BusCompanyId == busCompanyId)
                              .Select(r => new
                {
                    Id          = r.ReviewId,
                    Grade       = r.Grade,
                    PublishedOn = r.PublishedOn,
                    Customer    = r.Customer.FirstName + " " + r.Customer.LastName,
                    content     = r.Content
                }).ToList();

                if (reviews.Count == 0)
                {
                    return("[no reviews]");
                }

                var sb = new StringBuilder();
                sb.AppendLine($"BusCompany:{busCompany.Name}");
                foreach (var rev in reviews)
                {
                    var content = rev.content == null ? "[no content]" : rev.content;
                    sb.AppendLine($"ID: {rev.Id} Grade: {rev.Grade} Date: {rev.PublishedOn}");
                    sb.AppendLine($"Customer: {rev.Customer}");
                    sb.AppendLine($"Content:{content}");
                    sb.AppendLine();
                }

                return(sb.ToString().Trim());
            }
        }
        public static void GenerateTowns(BusTicketContext context)
        {
            string[] townNames = new string[]
            {
                "Longdale",
                "StringDale",
                "SpringField",
                "Lodingdon",
                "AppleTown",
                "GeorgeTown",
                "Misty Lake"
            };


            string[] countries = new string[]
            {
                "Zemlemoria",
                "Middle Earch",
                "The green Kingdom",
                "Westeros"
            };


            var validTowns = new List <Town>();
            var rnd        = new Random();

            for (int i = 0; i < townNames.Length; i++)
            {
                int countryIndex = rnd.Next(0, countries.Length - 1);

                var town = new Town()
                {
                    Name    = townNames[i],
                    Country = countries[countryIndex]
                };

                validTowns.Add(town);
            }

            context.AddRange(validTowns);
            context.SaveChanges();
        }
Пример #23
0
        public static void GenerateCompaines(BusTicketContext context)
        {
            var busCompanyNames = new string[] {
                "UnionIvkoni",
                "UnionDimitrovi",
                "BussesAreUs",
                "DestinationFantasia"
            };


            var nationality = new string[] {
                "Bulgarian",
                "English",
                "French",
                "German",
                "Danish"
            };

            var rnd = new Random();

            var validCompanies = new List <BusCompany>();


            for (int i = 0; i < busCompanyNames.Length; i++)
            {
                var    nationalityIndex = rnd.Next(0, nationality.Length - 1);
                double rating           = rnd.Next(0, 10) / (double)rnd.Next(1, 5);

                var company = new BusCompany
                {
                    Name        = busCompanyNames[i],
                    Nationality = nationality[nationalityIndex],
                    Rating      = rating
                };

                validCompanies.Add(company);
            }

            context.AddRange(validCompanies);
            context.SaveChanges();
        }
        //publish-review {Customer ID} {Grade} {Bus Company Name} {Content}
        public static string Execute(string[] data)
        {
            int     customerId     = int.Parse(data[1]);
            decimal grade          = decimal.Parse(data[2]);
            string  busCompanyName = data[3];
            string  content        = data.Length == 5 ? data[4] : null;

            using (var db = new BusTicketContext())
            {
                var customer = db.Customers.Find(customerId);

                if (customer == null)
                {
                    throw new ArgumentException("No customer with given Id!");
                }

                var busCompany = db.BusCompanies.FirstOrDefault(b => b.Name == busCompanyName);
                if (busCompany == null)
                {
                    throw new ArgumentException("No such Bus Company");
                }

                if (grade < 1.0m || grade > 10.0m)
                {
                    throw new ArgumentException("Invalid grade value");
                }

                var review = new Review
                {
                    BusCompanyId = busCompany.BusCompanyId,
                    Content      = content,
                    CustomerId   = customerId,
                    Grade        = grade
                };
                db.Reviews.Add(review);
                db.SaveChanges();

                return("Successfully added review.");
            }
        }
Пример #25
0
        public static void GenerateTrips(BusTicketContext context)
        {
            var rnd = new Random();

            var stationIds = context.BusStations.Select(p => p.Id).ToArray();

            var companyIds = context.BusCompanies.Select(p => p.Id).ToArray();

            var validTrips = new List <Trip>();


            for (int i = 0; i < 10; i++)
            {
                int indexStation     = rnd.Next(0, stationIds.Length - 1);
                int destinationIndex = rnd.Next(0, stationIds.Length - 1);
                while (indexStation == destinationIndex)
                {
                    destinationIndex = rnd.Next(0, stationIds.Length - 1);
                }

                int companyIndex = rnd.Next(0, companyIds.Length - 1);

                int days = rnd.Next(20, 100);

                var trip = new Trip
                {
                    DepartureTime        = DateTime.Now.AddDays(days * -1),
                    ArrivalTime          = DateTime.Now.AddDays(rnd.Next(1, 20)),
                    OriginStationId      = stationIds[indexStation],
                    DestinationStationId = stationIds[destinationIndex],
                    BusCompanyId         = companyIds[companyIndex],
                    Status = (Status)(i % 4)
                };

                validTrips.Add(trip);
            }

            context.AddRange(validTrips);
            context.SaveChanges();
        }
        internal string PrintInfo(string[] args)
        {
            int busStationId = int.Parse(args[0]);

            using (var context = new BusTicketContext())
            {
                var busStation = context.BusStations
                                 .AsNoTracking()
                                 .Where(bs => bs.Id == busStationId)
                                 .Include(bs => bs.Town)
                                 .Include(bs => bs.OriginTrips)
                                 .Include(bs => bs.DestinationTrips)
                                 .SingleOrDefault();

                var result = new StringBuilder();

                result.AppendLine($"{busStation.Name}, {busStation.Town.Name}");

                result.AppendLine($"Arrivals:");
                busStation.OriginTrips
                .ToList()
                .ForEach(ot =>
                         result.AppendLine($"From: {ot.OriginBusStation.Town.Name} | " +
                                           $"Arrive at: {ot.ArrivalTime.TimeOfDay.ToString(@"hh\:mm")} | " +
                                           $"Status: {ot.Status.ToString()}"));

                result.AppendLine($"Departures:");
                busStation.DestinationTrips
                .ToList()
                .ForEach(ot =>
                         result.AppendLine($"To: {ot.DestinationBusStation.Town.Name} | " +
                                           $"Depart at: {ot.ArrivalTime.TimeOfDay.ToString(@"hh\:mm")} | " +
                                           $"Status: {ot.Status.ToString()}"));

                return(result.ToString());
            }
        }
Пример #27
0
        public static void GenerateBankAccounts(BusTicketContext context)
        {
            string[] accountNumbers = new string[]
            {
                "123343473",
                "343255",
                "34354623423",
                "34354234",
                "3434232434",
                "342377684534"
            };

            var customerIds = context.Customers.Select(p => p.Id).ToArray();

            var validBankAccounts = new List <BankAccount>();

            var rnd = new Random();

            foreach (var id in customerIds)
            {
                var     index   = rnd.Next(0, accountNumbers.Length - 1);
                decimal balance = rnd.Next(100, 100000) / (decimal)rnd.Next(1, 20);

                var bankAccount = new BankAccount
                {
                    AccountNumber = accountNumbers[index],
                    CustomerId    = id,
                    Balance       = balance
                };

                validBankAccounts.Add(bankAccount);
            }

            context.AddRange(validBankAccounts);
            context.SaveChanges();
        }
        internal string PublishReview(string[] args)
        {
            int    customerId     = int.Parse(args[0]);
            double grade          = double.Parse(args[1]);
            string busCompanyName = args[2];
            string content        = args[3];

            using (var context = new BusTicketContext())
            {
                var customer = context.Customers
                               .Include(c => c.Reviews)
                               .SingleOrDefault(c => c.Id == customerId);

                var company = context.Companies
                              .FirstOrDefault(c => c.Name == busCompanyName);

                if (company == null)
                {
                    throw new CustomException($"No such company '{busCompanyName}'");
                }

                var review = new Review
                {
                    Customer   = customer,
                    CustomerId = customer.Id,
                    Company    = company,
                    CompanyId  = company.Id,
                    Content    = content,
                    Grade      = grade
                };

                context.Reviews.Add(review);
                context.SaveChanges();
                return($"Customer {customer.FullName} published review for company {busCompanyName}");
            }
        }
 public BusCompanyService(BusTicketContext dbContext)
 {
     this._dbContext = dbContext;
 }
Пример #30
0
 public BusStationService(BusTicketContext dbContext, ITownService townService)
 {
     this._dbContext   = dbContext;
     this._townService = townService;
 }